0Pricing
AI Engineering Academy · บทเรียน

การสร้าง Agent แบบ ReAct ด้วย LangChain

ประกอบ Agent แบบ ReAct ให้สมบูรณ์โดยใช้ AgentExecutor ของ LangChain พร้อมเครื่องมือค้นหาเว็บ เครื่องมือคำนวณ และเครื่องมือค้นหาเอกสาร จากนั้นติดตามขั้นตอนการใช้เหตุผลของ Agent

การสร้าง Agent แบบ ReAct ด้วย LangChain เป็นบทเรียน AI Engineering Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Engineering Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Engineering Academy มีบทเรียนทั้งหมด 4 บทเรียน

ระบบนิเวศเอเจนต์ของ LangChain

LangChain มีชุดเครื่องมือครบถ้วนสำหรับสร้างเอเจนต์: เครื่องมือ กำหนดสิ่งที่เอเจนต์ทำได้ พรอมต์ ให้คำสั่งและรูปแบบการให้เหตุผลแก่เอเจนต์ LLM ทำหน้าที่คิด และ AgentExecutor จัดการวงจรที่ส่งคำเรียกใช้เครื่องมือและป้อนข้อมูลสังเกตการณ์กลับมา คุณสามารถกำหนดค่าแต่ละส่วนแยกกันได้ จึงสลับส่วนประกอบได้โดยไม่ต้องเขียนทุกอย่างใหม่

การประกอบเอเจนต์ ReAct

วิธีที่รวดเร็วที่สุดในการสร้างเอเจนต์ ReAct ใน LangChain คือใช้ create_react_agent โดยส่ง LLM รายการเครื่องมือ และแม่แบบพรอมต์ให้กับฟังก์ชันนี้ ฟังก์ชันจะส่งคืนสิ่งที่เรียกใช้งานได้ซึ่งสร้างขั้นตอน Thought/Action/Observation โดยอัตโนมัติ จากนั้นครอบสิ่งนี้ด้วย AgentExecutor เพื่อจัดการวงจรการทำงาน

from langchain import hub
from langchain.agents import create_react_agent, AgentExecutor
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool

# 1. Define tools
@tool
def search(query: str) -> str:
    '''Search the web for current information. Input: a search query string.'''
    return f'Search results for "{query}": [mock result]'

@tool
def calculator(expression: str) -> str:
    '''Evaluate a math expression. Input: a valid Python math expression.'''
    try:
        return str(eval(expression))
    except Exception as e:
        return str(e)

tools = [search, calculator]

# 2. Load a ReAct prompt template
prompt = hub.pull('hwchase17/react')

# 3. Create the agent
llm = ChatOpenAI(model='gpt-4o', temperature=0)
agent = create_react_agent(llm, tools, prompt)

การทำงานด้วย AgentExecutor

AgentExecutor จัดการวงจร Thought/Action/Observation ในระหว่างพัฒนา ให้ส่ง verbose=True เพื่อพิมพ์ทุกขั้นตอนไปยังคอนโซล — การติดตามนี้มีประโยชน์อย่างยิ่งต่อการแก้ไขข้อบกพร่อง พารามิเตอร์ max_iterations เป็นกลไกป้องกันวงจรไม่รู้จบ

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,       # Print each step
    max_iterations=10,  # Safety limit
    handle_parsing_errors=True  # Don't crash on format errors
)

# Invoke with a user question
result = agent_executor.invoke({
    'input': 'What is the square root of 144 multiplied by the number of days in a leap year?'
})

print('Final answer:', result['output'])

การอ่านการติดตามแบบละเอียด

การติดตามแบบละเอียดจะแสดงวิธีที่เอเจนต์ให้เหตุผลอย่างชัดเจน ในแต่ละรอบ โมเดลจะแสดง Thought ของโมเดล การดำเนินการที่เลือก และ Observation จากเครื่องมือ ข้อมูลนี้ช่วยให้คุณระบุได้อย่างแม่นยำว่าเอเจนต์ทำงานผิดพลาดตรงไหน — ไม่ว่าจะเป็นการเลือกเครื่องมือผิด ส่งอาร์กิวเมนต์ผิด หรือตีความข้อมูลสังเกตการณ์ผิด

# Example verbose output from AgentExecutor:
#
# > Entering new AgentExecutor chain...
# Thought: I need to find the square root of 144 first, then multiply by days in a leap year.
# Action: calculator
# Action Input: 144 ** 0.5
# Observation: 12.0
# Thought: 12.0 times 366 days in a leap year.
# Action: calculator
# Action Input: 12.0 * 366
# Observation: 4392.0
# Thought: I have the final answer.
# Final Answer: 4392.0
# > Finished chain.

การใช้เครื่องมือ LangChain ในตัว

LangChain มาพร้อมเครื่องมือสำเร็จรูปมากมายสำหรับงานทั่วไป คุณสามารถเพิ่มเครื่องมือค้นหาเว็บจาก langchain_community.tools ได้โดยไม่ต้องเขียนโค้ด เครื่องมือเหล่านี้จัดการการยืนยันตัวตนกับ API และการแยกวิเคราะห์การตอบกลับให้คุณ

from langchain_community.tools import DuckDuckGoSearchRun
from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper

# Web search tool
search_tool = DuckDuckGoSearchRun()

# Wikipedia lookup tool
wiki_tool = WikipediaQueryRun(
    api_wrapper=WikipediaAPIWrapper(top_k_results=2)
)

# Add to your agent
tools_with_search = [search_tool, wiki_tool, calculator]
agent_executor.tools = tools_with_search

การค้นหาเอกสารในฐานะเครื่องมือ RAG

รูปแบบที่ทรงพลังอย่างหนึ่งคือการเปิดให้ใช้ pipeline ของ RAG เป็นเครื่องมือของเอเจนต์ เอเจนต์จะตัดสินใจว่าเมื่อใดควรดึงข้อมูลจากฐานความรู้ เมื่อใดควรใช้เครื่องมืออื่น หรือเมื่อใดควรอาศัยข้อมูลที่เรียนรู้มา วิธีนี้ทำให้ระบบ RAG ของคุณทำงานแบบพลวัต — เอเจนต์จะเรียกใช้ระบบนี้เฉพาะเมื่อเกี่ยวข้อง

from langchain_core.tools import tool

@tool
def lookup_knowledge_base(query: str) -> str:
    '''Search the company knowledge base for internal policies, procedures, and documentation.
    Use when the user asks about company-specific information not available publicly.
    Input: a natural language question or keyword query.
    '''
    # Your RAG pipeline here
    retrieved_chunks = vector_store.similarity_search(query, k=3)
    context = '\n'.join([doc.page_content for doc in retrieved_chunks])
    return context if context else 'No relevant documents found.'

การสตรีมเอาต์พุตของเอเจนต์

เพื่อประสบการณ์ผู้ใช้ที่ดีขึ้น ให้สตรีมคำตอบสุดท้ายของเอเจนต์ทีละโทเคนแทนการรอการตอบกลับทั้งหมด ใช้ agent_executor.astream_events เพื่อรับเหตุการณ์ทันทีที่เกิดขึ้น รวมถึงขั้นตอนระหว่างการทำงานและสตรีมเอาต์พุตสุดท้าย

import asyncio

async def stream_agent(user_input: str):
    async for event in agent_executor.astream_events(
        {'input': user_input},
        version='v1'
    ):
        kind = event['event']
        if kind == 'on_chat_model_stream':
            chunk = event['data']['chunk']
            if chunk.content:
                print(chunk.content, end='', flush=True)
        elif kind == 'on_tool_start':
            print(f'\n[Calling tool: {event["name"]}]')
        elif kind == 'on_tool_end':
            print(f'[Tool result: {str(event["data"]["output"])[:100]}]')

asyncio.run(stream_agent('What is the latest news about AI?'))

การส่งหน่วยความจำให้เอเจนต์

ผสานการให้เหตุผลของเอเจนต์เข้ากับหน่วยความจำการสนทนา เพื่อให้เอเจนต์จดจำการโต้ตอบก่อนหน้า ใช้ RunnableWithMessageHistory ครอบตัวดำเนินการเอเจนต์ และจัดเตรียมคลังประวัติการสนทนา จากนั้นเอเจนต์จะมีทั้งความจำเกี่ยวกับการโต้ตอบที่ผ่านมาและความสามารถในการเรียกใช้เครื่องมือ

from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory

session_store = {}

def get_session_history(session_id: str):
    if session_id not in session_store:
        session_store[session_id] = ChatMessageHistory()
    return session_store[session_id]

agent_with_memory = RunnableWithMessageHistory(
    agent_executor,
    get_session_history,
    input_messages_key='input',
    history_messages_key='chat_history'
)

การปรับแต่งพรอมต์ ReAct

พรอมต์เริ่มต้นจากฮับทำงานได้ดี แต่บ่อยครั้งคุณจำเป็นต้องใช้พรอมต์ระบบแบบกำหนดเองสำหรับขอบเขตงานเฉพาะ พรอมต์แบบกำหนดเองช่วยให้คุณเพิ่มคำสั่งเกี่ยวกับบุคลิก กฎการจัดรูปแบบเอาต์พุต และคำแนะนำเฉพาะด้านก่อนคำอธิบายเครื่องมือได้ ใช้ ChatPromptTemplate พร้อมตัวแทนตำแหน่ง ReAct ที่จำเป็น

from langchain_core.prompts import ChatPromptTemplate

custom_prompt = ChatPromptTemplate.from_messages([
    ('system', '''You are a helpful customer support agent for TechCorp.
Always be polite and professional. When you do not know something, use your tools.

You have access to these tools:
{tools}

Tool names: {tool_names}

Use this format:
Thought: ...
Action: tool_name
Action Input: input_value
Observation: result
Final Answer: your response to the customer
'''),
    ('human', '{input}'),
    ('assistant', '{agent_scratchpad}')
])

agent = create_react_agent(llm, tools, custom_prompt)

การสังเกตขั้นตอนการให้เหตุผลของเอเจนต์

AgentExecutor จะส่งคืนขั้นตอนระหว่างการทำงานพร้อมกับเอาต์พุตสุดท้ายเมื่อคุณตั้งค่า return_intermediate_steps=True แต่ละขั้นตอนเป็นทูเพิลที่ประกอบด้วยการดำเนินการของเอเจนต์และข้อมูลสังเกตการณ์จากเครื่องมือ ข้อมูลนี้มีประโยชน์สำหรับการสร้าง UI ที่แสดงกระบวนการให้เหตุผลของเอเจนต์แก่ผู้ใช้

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    return_intermediate_steps=True
)

result = agent_executor.invoke({'input': 'What is 2 to the power of 10?'})

print('Final answer:', result['output'])
print('Reasoning steps:')
for step in result['intermediate_steps']:
    action, observation = step
    print(f'  Tool: {action.tool}, Input: {action.tool_input}')
    print(f'  Observation: {observation}')

การทดสอบเอเจนต์อย่างละเอียด

ทดสอบเอเจนต์ของคุณด้วยชุดคำถามตัวแทนที่ครอบคลุม: งานที่ใช้เครื่องมือเดียว งานหลายขั้นที่ต้องเรียกใช้เครื่องมือหลายครั้ง งานที่ไม่จำเป็นต้องใช้เครื่องมือ (โมเดลตอบจากข้อมูลที่เรียนรู้มา) และอินพุตเชิงปรปักษ์ เช่น คำถามที่ออกแบบมาเพื่อทำให้การเลือกเครื่องมือสับสน ติดตามอัตราการผ่านและรูปแบบความล้มเหลว เพื่อปรับปรุงคำอธิบายเครื่องมือและพรอมต์

ตรวจสอบความเข้าใจอย่างรวดเร็ว

ทดสอบความเข้าใจเกี่ยวกับการสร้างเอเจนต์ ReAct ด้วย LangChain

สรุปบทเรียน

ในบทเรียนนี้ คุณได้เรียนรู้ว่า create_react_agent ประกอบ LLM เครื่องมือ และพรอมต์เข้าด้วยกันเป็นเอเจนต์ ReAct AgentExecutor จัดการวงจร Thought/Action/Observation พร้อมขีดจำกัดด้านความปลอดภัยที่กำหนดค่าได้ และ verbose=True กับ return_intermediate_steps=True ช่วยให้คุณมองเห็นกระบวนการให้เหตุผลของเอเจนต์ได้อย่างครบถ้วน ต่อไป เราจะเรียนรู้วิธีจัดการความล้มเหลวของเอเจนต์และป้องกันวงจรไม่รู้จบ

คำถามที่พบบ่อย

บทเรียน “การสร้าง Agent แบบ ReAct ด้วย LangChain” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การสร้าง Agent แบบ ReAct ด้วย LangChain” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Engineering Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Engineering Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การสร้าง Agent แบบ ReAct ด้วย LangChain”

ประกอบ Agent แบบ ReAct ให้สมบูรณ์โดยใช้ AgentExecutor ของ LangChain พร้อมเครื่องมือค้นหาเว็บ เครื่องมือคำนวณ และเครื่องมือค้นหาเอกสาร จากนั้นติดตามขั้นตอนการใช้เหตุผลของ Agent คุณปฏิบัติ AI Engineering Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Engineering Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Engineering Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การสร้าง Agent แบบ ReAct ด้วย LangChain” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Engineering Academy นี้ได้ไหม

ได้ บทเรียน AI Engineering Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เฟรมเวิร์ก ReAct: คิด ลงมือทำ สังเกต
  2. การกำหนดเครื่องมือสำหรับ Agent
  3. การสร้าง Agent แบบ ReAct ด้วย LangChain
  4. การจัดการข้อผิดพลาดและลูปของเอเจนต์
← กลับไปที่ AI Engineering Academy