0Pricing
AI Agents · Lezione

Python asincrono per sviluppatori di agenti

Nozioni di base di asyncio, async def, await, event loop: il modello mentale dell’asincronia.

Python asincrono per sviluppatori di agenti è una lezione AI Agents gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento AI Agents, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso AI Agents include 4 lezioni in totale.

Perché utilizzare l’asincronia per gli agenti?

Gli agenti effettuano molte chiamate vincolate dall’I/O: API LLM, richieste web e query al database. Il codice sincrono rimane inattivo mentre queste chiamate vengono completate. Il codice asincrono esegue altre operazioni durante queste attese, migliorando drasticamente il throughput.

Nozioni di base sull’asincronia: async def e await

async def dichiara una funzione coroutine. await sospende l’esecuzione finché l’operazione attesa non viene completata, consentendo al ciclo degli eventi di eseguire nel frattempo altre coroutine.

import asyncio

async def fetch_data(source: str) -> str:
    print(f'Starting fetch from {source}')
    await asyncio.sleep(1)  # Simulates a network call
    print(f'Finished fetch from {source}')
    return f'Data from {source}'

async def main():
    # Sequential: takes 2 seconds total
    result1 = await fetch_data('source-A')
    result2 = await fetch_data('source-B')
    print('Sequential results:', result1, result2)

asyncio.run(main())

# asyncio.run() starts the event loop and runs main()
# It is the entry point for async programs

Il ciclo degli eventi

Il ciclo degli eventi è il componente centrale di asyncio. Gestisce una coda di coroutine e callback di I/O, eseguendole quando sono pronte. Tutto il codice asincrono viene eseguito all’interno del ciclo degli eventi su un singolo thread.

import asyncio

async def task_a():
    print('Task A: start')
    await asyncio.sleep(2)
    print('Task A: done')

async def task_b():
    print('Task B: start')
    await asyncio.sleep(1)
    print('Task B: done')

async def main():
    # asyncio.gather runs both tasks concurrently
    # Total time: ~2 seconds (not 3)
    await asyncio.gather(task_a(), task_b())
    print('Both tasks complete')

# Expected output order:
# Task A: start
# Task B: start
# Task B: done   <- after 1s
# Task A: done   <- after 2s
# Both tasks complete
asyncio.run(main())

Coroutine e thread a confronto

Le coroutine sono cooperative: cedono esplicitamente il controllo con await. I thread sono preemptive: il sistema operativo può passare dall’uno all’altro in qualsiasi momento. Le coroutine sono più leggere, non presentano problemi legati al GIL per l’I/O e sono più facili da comprendere.

import asyncio
import threading
import time

# Thread approach: multiple OS threads
def thread_worker(name):
    print(f'Thread {name}: start')
    time.sleep(1)  # Blocks the thread
    print(f'Thread {name}: done')

threads = [threading.Thread(target=thread_worker, args=(i,)) for i in range(3)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print('---')

# Coroutine approach: single-threaded event loop
async def coro_worker(name):
    print(f'Coro {name}: start')
    await asyncio.sleep(1)  # Suspends, does NOT block other coroutines
    print(f'Coro {name}: done')

async def main():
    await asyncio.gather(*[coro_worker(i) for i in range(3)])

asyncio.run(main())
# Both approaches run 3 tasks in ~1 second total, but coroutines use one thread

Punto di ingresso asyncio.run()

asyncio.run() crea un nuovo ciclo degli eventi, esegue la coroutine indicata fino al completamento e chiude il ciclo. È il punto di ingresso standard per i programmi asincroni in Python 3.7+.

import asyncio

async def agent_main():
    print('Agent starting')
    # All agent async work goes here
    results = await asyncio.gather(
        asyncio.sleep(0.1),  # Simulated LLM call
        asyncio.sleep(0.1),  # Simulated DB query
    )
    print('Agent done')
    return 'complete'

# Run the agent
result = asyncio.run(agent_main())
print('Result:', result)

# WRONG: calling asyncio.run() inside an already-running event loop
# In Jupyter notebooks, use: await agent_main() directly
# Or: nest_asyncio.apply() then asyncio.run()

Errore comune: operazioni bloccanti nel contesto asincrono

Non chiami mai funzioni bloccanti (time.sleep, requests.get, I/O di file sincrono) all’interno del codice asincrono. Questo blocca l’intero ciclo degli eventi, annullando tutta la concorrenza.

import asyncio
import time
import httpx

# WRONG: blocks the event loop
async def bad_agent_step():
    time.sleep(2)          # Blocks all other coroutines
    # requests.get(url)    # Also blocks - do NOT use requests in async code
    return 'done'

# RIGHT: use async equivalents
async def good_agent_step():
    await asyncio.sleep(2)  # Suspends, other coroutines can run
    
    async with httpx.AsyncClient() as client:
        response = await client.get('https://api.example.com/data')
    return response.text

# For CPU-intensive work: use run_in_executor
import concurrent.futures

async def cpu_intensive_step(data: str):
    loop = asyncio.get_event_loop()
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, expensive_cpu_fn, data)
    return result

def expensive_cpu_fn(data):
    # CPU-bound work runs in separate process
    return data.upper()

print('Blocking vs non-blocking patterns demonstrated')

Await dimenticato: un bug silenzioso

Dimenticare await non genera un errore: restituisce un oggetto coroutine invece del risultato. Si tratta di un bug silenzioso che causa errori nelle fasi successive o risultati vuoti.

import asyncio

async def get_answer() -> str:
    await asyncio.sleep(0.1)
    return 'The answer is 42'

async def bad_call():
    result = get_answer()   # WRONG: forgot await
    print(type(result))     # <class 'coroutine'> - not a string!
    # Using result as a string here causes AttributeError or wrong behavior
    return result

async def good_call():
    result = await get_answer()  # CORRECT
    print(type(result))           # <class 'str'>
    return result

async def main():
    bad = await bad_call()
    print('Bad result:', bad)    # coroutine object, not the string
    
    good = await good_call()
    print('Good result:', good)  # 'The answer is 42'
    
    # Clean up the uncollected coroutine
    if asyncio.iscoroutine(bad):
        bad.close()

asyncio.run(main())

Problema del ciclo degli eventi annidato

Chiamare asyncio.run() all’interno di un ciclo degli eventi già in esecuzione (ad esempio in Jupyter o FastAPI) genera un RuntimeError. Soluzioni: utilizzi direttamente await oppure usi nest_asyncio per i notebook.

import asyncio

async def my_agent_coroutine():
    await asyncio.sleep(0.1)
    return 'done'

# In FastAPI or other async frameworks, the event loop is already running
# Use await directly in async endpoints:
async def fastapi_endpoint():
    # WRONG inside async context:
    # result = asyncio.run(my_agent_coroutine())  # RuntimeError!
    
    # CORRECT: just await
    result = await my_agent_coroutine()
    return result

# In Jupyter notebooks: install nest_asyncio
# import nest_asyncio
# nest_asyncio.apply()
# Then asyncio.run() works

# Detect if running in event loop:
def run_agent(coro):
    try:
        loop = asyncio.get_running_loop()
        # Already in async context
        import concurrent.futures
        with concurrent.futures.ThreadPoolExecutor() as pool:
            future = pool.submit(asyncio.run, coro)
            return future.result()
    except RuntimeError:
        # No running loop
        return asyncio.run(coro)

print('Nested event loop solution defined')

asyncio.create_task

Utilizzi asyncio.create_task() per pianificare l’esecuzione di una coroutine senza attenderla immediatamente. In questo modo può avviare più attività e attenderne il completamento in un secondo momento.

import asyncio

async def background_job(job_id: int) -> str:
    await asyncio.sleep(0.5)
    return f'Job {job_id} completed'

async def main():
    # Start all tasks without waiting
    task1 = asyncio.create_task(background_job(1))
    task2 = asyncio.create_task(background_job(2))
    task3 = asyncio.create_task(background_job(3))
    
    # Do other work while tasks run
    print('Tasks started, doing other work...')
    await asyncio.sleep(0.1)
    print('Other work done')
    
    # Now wait for all tasks
    results = await asyncio.gather(task1, task2, task3)
    print('All results:', results)
    
    # Or wait for the first to complete
    task_a = asyncio.create_task(background_job(4))
    task_b = asyncio.create_task(background_job(5))
    done, pending = await asyncio.wait([task_a, task_b], return_when=asyncio.FIRST_COMPLETED)
    for t in pending:
        t.cancel()  # Cancel remaining tasks
    print('First result:', done.pop().result())

asyncio.run(main())

Gestori di contesto asincroni

Molte librerie asincrone utilizzano gestori di contesto asincroni con async with. Questo garantisce la corretta configurazione e il corretto rilascio di connessioni e risorse nel codice asincrono.

import asyncio
import httpx

async def fetch_multiple_urls(urls: list) -> list:
    # async with ensures the client is properly closed
    async with httpx.AsyncClient(timeout=10.0) as client:
        # Fetch all URLs concurrently
        tasks = [client.get(url) for url in urls]
        responses = await asyncio.gather(*tasks, return_exceptions=True)
        
        results = []
        for url, response in zip(urls, responses):
            if isinstance(response, Exception):
                results.append({'url': url, 'error': str(response)})
            else:
                results.append({'url': url, 'status': response.status_code})
        return results

# Async generators for streaming
async def stream_agent_events():
    events = ['thinking', 'searching', 'generating', 'done']
    for event in events:
        await asyncio.sleep(0.2)  # Simulate event arrival
        yield event

async def consume_stream():
    async for event in stream_agent_events():
        print(f'Event: {event}')

asyncio.run(consume_stream())

Gestione degli errori nel codice asincrono

Utilizzi asyncio.gather(..., return_exceptions=True) per intercettare i guasti delle singole attività senza interrompere l’intero batch. Verifichi ogni risultato per individuare i tipi di eccezione.

import asyncio

async def might_fail(task_id: int) -> str:
    await asyncio.sleep(0.1)
    if task_id == 2:
        raise ValueError(f'Task {task_id} failed')
    return f'Task {task_id} succeeded'

async def robust_gather():
    tasks = [might_fail(i) for i in range(1, 5)]
    
    # return_exceptions=True: exceptions are returned as values, not raised
    results = await asyncio.gather(*tasks, return_exceptions=True)
    
    successes = []
    failures = []
    for i, result in enumerate(results):
        if isinstance(result, Exception):
            failures.append({'task': i + 1, 'error': str(result)})
        else:
            successes.append(result)
    
    print(f'Succeeded: {len(successes)}, Failed: {len(failures)}')
    print('Failures:', failures)
    return successes, failures

asyncio.run(robust_gather())

Verifica delle conoscenze: Python asincrono

Verifichi la Sua comprensione di Python asincrono per lo sviluppo di agenti.

Riepilogo di Python asincrono

Regole fondamentali di Python asincrono per chi sviluppa agenti: utilizzi async def/await per tutte le operazioni vincolate dall’I/O; non chiami mai funzioni bloccanti in un contesto asincrono; utilizzi asyncio.gather() per l’esecuzione parallela; utilizzi return_exceptions=True per chiamate parallele tolleranti ai guasti; utilizzi async with per la gestione delle risorse; esegua le operazioni ad alta intensità di CPU in un process pool executor.

Domande Frequenti

La lezione «Python asincrono per sviluppatori di agenti» è gratuita?

Sì — il testo completo di «Python asincrono per sviluppatori di agenti» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso AI Agents, passa a CoddyKit PRO. Il corso AI Agents include 4 lezioni in totale.

Cosa imparerò in «Python asincrono per sviluppatori di agenti»?

Nozioni di base di asyncio, async def, await, event loop: il modello mentale dell’asincronia. Eserciti AI Agents con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare AI Agents?

Non è richiesta alcuna esperienza precedente. AI Agents su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.

Quanto tempo richiede la lezione «Python asincrono per sviluppatori di agenti»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione AI Agents?

Sì. Ogni lezione AI Agents include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Python asincrono per sviluppatori di agenti
  2. Code di eventi e message broker
  3. Esecuzione parallela non bloccante degli strumenti
  4. Framework asincroni per agenti: LangChain e oltre
← Torna a AI Agents