การทำงานของเอเจนต์แบบอะซิงโครนัส
เรียนรู้การนำรูปแบบอะซิงโครนัสมาใช้ เพื่อให้เอเจนต์ทำงานแบบขนานและตอบสนองได้ดียิ่งขึ้น
การทำงานของเอเจนต์แบบอะซิงโครนัส เป็นบทเรียน AI Agents with LangChain & Autonomous Workflows ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents with LangChain & Autonomous Workflows และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Asynchronous Agents?
Imagine your AI agent needs to do several things at once: fetch data from two APIs, analyze text with an LLM, and then store a result. If it does these synchronously (one after another), it waits for each step to complete before starting the next.
This waiting can make your agent slow and unresponsive, especially when dealing with network calls or complex computations.
Synchronous vs. Asynchronous
Synchronous execution is like a single-lane road: only one car can pass at a time. If a car breaks down, all traffic stops.
- Synchronous: Tasks run one by one.
- Asynchronous: Tasks can start, pause while waiting for something (like an API response), and let other tasks run in the meantime. It's like a multi-lane highway or juggling multiple balls.
Asynchronous programming helps agents utilize idle time more effectively.
Python's Async/Await Keywords
Python uses the async and await keywords to enable asynchronous programming. Think of them as signals:
async def: Defines a function (called a coroutine) that can run asynchronously.await: Pauses the current coroutine until the awaited task is complete, allowing other tasks to run.
Let's see a basic example:
import asyncio
async def say_hello():
print("Hello ")
await asyncio.sleep(1) # Simulate a delay
print("World!")
async def main():
await say_hello()
if __name__ == "__main__":
asyncio.run(main())The asyncio Event Loop
Behind the scenes, Python's asyncio library manages how asynchronous tasks run. It uses an event loop.
- The event loop constantly monitors tasks.
- When an
awaitstatement pauses a task, the event loop switches to another ready task. - Once the awaited task is done, the event loop resumes the paused task.
This allows non-blocking operations, improving overall efficiency.
Async LLM Calls in LangChain
Many LangChain components, especially LLMs, offer asynchronous versions of their methods. For example, instead of .invoke(), you can often use .ainvoke() for an asynchronous call.
This is crucial for making your agent responsive when querying large language models, which can take time.
import asyncio
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
async def main():
# Make sure you have your OpenAI API key set up
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
# Using .ainvoke() for an asynchronous call
response = await llm.ainvoke([HumanMessage(content="What is the capital of Canada?")])
print(response.content)
if __name__ == "__main__":
asyncio.run(main())Running Multiple LLM Calls Concurrently
The real power of async shines when you need to make multiple LLM calls. You don't have to wait for each one to finish before starting the next.
Use asyncio.gather() to run several asynchronous tasks in parallel and collect their results.
import asyncio
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
async def main():
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
# Create multiple asynchronous LLM invocation tasks
task1 = llm.ainvoke([HumanMessage(content="Tell me a fact about the sun.")])
task2 = llm.ainvoke([HumanMessage(content="Tell me a fact about the moon.")])
task3 = llm.ainvoke([HumanMessage(content="Tell me a fact about Earth.")])
# Run all tasks concurrently and wait for them to complete
results = await asyncio.gather(task1, task2, task3)
for i, res in enumerate(results):
print(f"Result {i+1}: {res.content}\n")
if __name__ == "__main__":
asyncio.run(main())Asynchronous Tool Execution
Just like LLMs, your custom tools can also be asynchronous! If your tool performs I/O-bound operations (like fetching data from a database or an external API), making it asynchronous will significantly improve agent performance.
To create an async tool, implement the _arun method in your BaseTool subclass.
import asyncio
from langchain.tools import BaseTool
class AsyncWebSearchTool(BaseTool):
name: str = "AsyncWebSearch"
description: str = "Searches the web asynchronously for a query."
async def _arun(self, query: str) -> str:
# Simulate an asynchronous web search API call
await asyncio.sleep(1.5)
return f"Results for '{query}': Found 5 articles."
def _run(self, query: str) -> str:
# Fallback for synchronous calls (optional but good practice)
return f"Sync results for '{query}': Found 4 articles."
async def main():
tool = AsyncWebSearchTool()
result = await tool.arun("latest AI news")
print(result)
if __name__ == "__main__":
asyncio.run(main())Building Async Chains & Agents
When you combine asynchronous LLMs and tools into chains or agents, LangChain automatically leverages their async capabilities. Most LangChain runnables and chains also provide an .ainvoke() method.
This means you can build entire asynchronous workflows, allowing your agent to process complex tasks involving multiple steps and external calls much faster.
import asyncio
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableSequence
async def main():
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
prompt = ChatPromptTemplate.from_template("What is a unique fact about {animal}?")
# Define a simple chain
chain = prompt | llm
# Invoke the chain asynchronously
response = await chain.ainvoke({"animal": "platypus"})
print(response.content)
if __name__ == "__main__":
asyncio.run(main())Quick Check: Async Benefits
Let's check your understanding of asynchronous execution.
Recap: Mastering Async Agents
Great job! You've learned the fundamentals of asynchronous execution in Python and how to apply it to your LangChain agents.
- Asynchronous programming (
async/await) allows agents to perform tasks concurrently instead of waiting for each one. - This significantly improves responsiveness and throughput for I/O-bound operations.
- LangChain's LLMs, tools, and chains often provide asynchronous methods (e.g.,
.ainvoke(),.arun()) to leverage this power.
By integrating async patterns, you can build more efficient and high-performing autonomous workflows!
คำถามที่พบบ่อย
บทเรียน “การทำงานของเอเจนต์แบบอะซิงโครนัส” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การทำงานของเอเจนต์แบบอะซิงโครนัส” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents with LangChain & Autonomous Workflows ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การทำงานของเอเจนต์แบบอะซิงโครนัส”
เรียนรู้การนำรูปแบบอะซิงโครนัสมาใช้ เพื่อให้เอเจนต์ทำงานแบบขนานและตอบสนองได้ดียิ่งขึ้น คุณปฏิบัติ AI Agents with LangChain & Autonomous Workflows ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents with LangChain & Autonomous Workflows หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents with LangChain & Autonomous Workflows บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การทำงานของเอเจนต์แบบอะซิงโครนัส” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents with LangChain & Autonomous Workflows นี้ได้ไหม
ได้ บทเรียน AI Agents with LangChain & Autonomous Workflows ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การออกแบบเวิร์กโฟลว์ที่ซับซ้อน
- การทำงานของเอเจนต์แบบอะซิงโครนัส
- การจัดการข้อผิดพลาดและความทนทาน
- การอนุมัติโดยมนุษย์ในกระบวนการ