Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Skills Asynchronous and Concurrent Processing

Skills Asynchronous and Concurrent Processing

When a Skill needs to wait for multiple time-consuming operations at once (such as network requests or file I/O), asynchronous programming can greatly reduce total waiting time.

This article introduces the application scenarios and usage of Python asyncio in Skill scripts.


Synchronous vs asynchronous: when to use async

Scenario Recommended approach Reason
Single file processing, single API call Synchronization Async benefits are unclear, code is simpler
Send multiple HTTP requests simultaneously Asynchronous Concurrent waiting, total time ≈ longest single time
Read multiple files simultaneously Async or thread pool Switch tasks while waiting for I/O
CPU-intensive computation (such as image processing) Multiprocessing asyncio does not bypass the GIL

Asynchronous does not equal parallel. Python's asyncio is a single-threaded event loop, suitable for I/O-intensive tasks (waiting for network or disk). CPU-intensive tasks should use ProcessPoolExecutor。


Send multiple HTTP requests asynchronously

Suppose a Skill needs to call 3 API endpoints at the same time; the synchronous total time is the sum of the three requests, while the asynchronous total time is roughly equal to the slowest one.

Example

File path: scripts/async_requests.py

Call multiple APIs concurrently and aggregate results

import

asyncio

import

aiohttp      

pip install aiohttp --break-system-packages

import

json

import

sys

import

time

API_KEY  

=

"your_api_key"

BASE_URL

=

"https://api.example.com/v1"

async

def

fetch_one

(

session: aiohttp.

ClientSession

,

                    endpoint:

str

,

payload:

dict

)

dict

:

   

"""Send a single POST request asynchronously"""

    url    

=

BASE_URL + endpoint

    headers

=

{

"Authorization"

: f

"Bearer {API_KEY}"

}

   

try

:

        async

with

session.

post

(

url

,

json

=

payload

,

                                headers

=

headers

,

timeout

=

aiohttp.

ClientTimeout

(

total

=

30

)

)

as

resp:

            resp.

raise_for_status

(

)

           

return

{

"endpoint"

: endpoint

,

"status"

:

"ok"

,

"data"

: await resp.

json

(

)

}

   

except

Exception

as

e:

       

return

{

"endpoint"

: endpoint

,

"status"

:

"error"

,

"message"

:

str

(

e

)

}

async

def

fetch_all

(

requests:

list

)

list

:

   

"""
    Send all requests concurrently and wait for completion

    Parameters:
        requests: list, each item is an (endpoint, payload) tuple
    """

    async

with

aiohttp.

ClientSession

(

)

as

session:

        tasks

=

[

            fetch_one

(

session

,

endpoint

,

payload

)

           

for

endpoint

,

payload

in

requests

       

]

       

gather executes all tasks concurrently; return_exceptions=True prevents one failure from affecting others

       

return

await asyncio.

gather

(

*tasks

,

return_exceptions

=

True

)

def

main

(

)

:

   

Define the list of requests to call concurrently

    requests

=

[

       

(

"/summarize"

,

{

"text"

:

"runoob is a technology learning platform"

,

"lang"

:

"zh"

}

)

,

       

(

"/keywords"

,

 

{

"text"

:

"RUNOOB provides various programming tutorials"

,

"top_n"

:

5

}

)

,

       

(

"/sentiment"

,

{

"text"

:

"The tutorials on this platform are of high quality"

}

)

,

   

]

    t0      

=

time

.

perf_counter

(

)

    results

=

asyncio.

run

(

fetch_all

(

requests

)

)

    elapsed

=

time

.

perf_counter

(

)

   

print

(

f

"Completed {len(results)} requests concurrently, total time {elapsed:.2f} seconds"

)

   

print

(

json.

dumps

(

results

,

ensure_ascii

=

False

,

indent

=

2

)

)

if

name

==

"main"

:

    main

(

)



并发完成 3 个请求,总耗时 1.23 秒

(同步串行约需 3.5 秒,并发节省约 65% 时间)


Read multiple files asynchronously

For scenarios requiring reading multiple files at once, aiofiles provides an asynchronous version of file I/O.

Example

File path: scripts/async_file_reader.py

import

asyncio

import

aiofiles  

pip install aiofiles --break-system-packages

import

os

async

def

read_file

(

file_path:

str

)

dict

:

   

"""Read a single file asynchronously"""

   

try

:

        async

with

aiofiles.

open

(

file_path

,

encoding

=

"utf-8"

)

as

f:

            content

=

await f.

read

(

)

       

return

{

           

"file"

:    

os

.

path

.

basename

(

file_path

)

,

           

"chars"

:  

len

(

content

)

,

           

"lines"

:   content.

count

(

"\n"

)

,

           

"status"

:  

"ok"

       

}

   

except

Exception

as

e:

       

return

{

"file"

: file_path

,

"status"

:

"error"

,

"message"

:

str

(

e

)

}

async

def

read_all_files

(

file_paths:

list

)

list

:

   

"""Read all files concurrently"""

    tasks

=

[

read_file

(

fp

)

for

fp

in

file_paths

]

   

return

await asyncio.

gather

(

*tasks

)

if

name

==

"main"

:

   

import

glob

,

json

   

Read all .txt files in the upload directory

    files

=

glob

.

glob

(

"/mnt/user-data/uploads/*.txt"

)

   

if

not

files:

       

print

(

"No .txt files found"

)

   

else

:

        results

=

asyncio.

run

(

read_all_files

(

files

)

)

       

print

(

json.

dumps

(

results

,

ensure_ascii

=

False

,

indent

=

2

)

)


Timeout control and task cancellation

In asynchronous tasks, timeout control is especially important. asyncio.wait_for can set a maximum wait time for a single task.

Example

File path: scripts/async_timeout.py

import

asyncio

async

def

slow_task

(

name:

str

,

delay:

float

)

str

:

   

"""Simulate a time-consuming task"""

    await asyncio.

sleep

(

delay

)

   

return

f

"{name} completed"

async

def

run_with_timeout

(

)

:

    tasks

=

{

       

"Fast task"

: slow_task

(

"Fast task"

,

0.5

)

,

       

"Slow task"

: slow_task

(

"Slow task"

,

5.0

)

,

   

}

    results

=

{

}

   

for

name

,

coro

in

tasks.

items

(

)

:

       

try

:

           

Wait at most 2 seconds per task

            result

=

await asyncio.

wait_for

(

coro

,

timeout

=

2.0

)

            results

[

name

]

=

{

"status"

:

"ok"

,

"result"

: result

}

       

except

asyncio.

TimeoutError

:

            results

[

name

]

=

{

"status"

:

"timeout"

,

"message"

:

"Not completed within 2 seconds"

}

   

return

results

if

name

==

"main"

:

   

import

json

    output

=

asyncio.

run

(

run_with_timeout

(

)

)

   

print

(

json.

dumps

(

output

,

ensure_ascii

=

False

,

indent

=

2

)

)



{

  "快速任务": {"status": "ok",      "result": "快速任务 完成"},

  "慢速任务": {"status": "timeout", "message": "超过 2 秒未完成"}

}


Explain how to call asynchronous scripts in SKILL.md



## Concurrent API Calls



When the user provides multiple texts that need to be analyzed simultaneously, run an asynchronous script to improve speed:



```bash

python scripts/async_requests.py

This script sends all requests concurrently; the total time is roughly equal to the slowest single request, rather than the sum of all requests.