Agent开发——Day 04 async/await 异步编程 Day 04 案例分析async/await 异步编程案例一LLM 并发调用最贴近 Agent 开发的场景场景描述你在开发一个 Agent用户问了一个复杂问题你需要同时调用 3 个 LLMLLM-A生成初稿LLM-B检查事实LLM-C评估语气同步写法慢result_acall_llm_a(prompt)# 等 2 秒result_bcall_llm_b(prompt)# 等 2 秒result_ccall_llm_c(prompt)# 等 2 秒# 总共等 6 秒异步写法快result_a,result_b,result_cawaitasyncio.gather(call_llm_a(prompt),call_llm_b(prompt),call_llm_c(prompt),)# 总共等 2 秒最慢的那个结论asyncio.gather()是 Agent 开发中最常用的并发工具。案例二FastAPI 的本质理解为什么框架要求 asyncFastAPI、LangGraph 的 Server 模式都要求你写async def。原因是# FastAPI 路由必须是 async defapp.post(/chat)asyncdefchat(request:ChatRequest):# 当这里在等 LLM 响应时FastAPI 可以去处理其他用户的请求responseawaitcall_llm(request.message)return{reply:response}如果用同步def服务器处理一个用户时其他用户的请求全部排队等待。用async def等待 IO 的时候 CPU 可以去处理其他请求吞吐量大幅提升。案例三Day 3 代码的异步改造原始同步版本importrequestsdefcall_api_with_auth(api_key:str,prompt:str)-str:urlhttps://httpbin.org/postheaders{Authorization:fBearer{api_key},Content-Type:application/json}body{model:some-model,messages:[{role:user,content:prompt}]}responserequests.post(url,headersheaders,jsonbody,timeout10)response.raise_for_status()echoresponse.json()print(服务器收到的 headers:,echo[headers].get(Authorization))return调用成功异步改造版本见 day004.py关键变化同步异步import requestsimport httpx或import aiohttpdefasync defrequests.post()await client.post()直接调用函数asyncio.run(main())关键概念速查async def— 声明一个协程函数asyncdefmy_function():return结果调用它不会立刻执行而是返回一个协程对象承诺将来会执行。await— 等待协程完成resultawaitmy_function()# 挂起当前函数等 my_function 完成await只能在async def函数内部使用。asyncio.run()— 启动事件循环程序入口if__name____main__:asyncio.run(main())# 在同步代码中运行异步函数的唯一正确方式asyncio.gather()— 并发执行多个协程resultsawaitasyncio.gather(task1(),task2(),task3())# results 是一个列表顺序与传入顺序一致asyncio.sleep()— 异步等待不阻塞其他任务awaitasyncio.sleep(1)# 等1秒但期间其他协程可以运行# 对比time.sleep(1) 会阻塞整个程序