เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การสร้าง ReAct agent

เมื่อเรียนรู้องค์ประกอบพื้นฐานของ LangChain แล้ว ก็ถึงเวลาลงมือสร้าง ReAct agent ที่สามารถนับจำนวนตัวอักษร 'r' ในคำใดก็ได้ โดยใช้ tool ชื่อ count_r_in_word

สิ่งต่อไปนี้ถูกโหลดไว้ให้แล้ว: tool, ChatOpenAI, create_react_agent, math และ model

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การออกแบบระบบ Agentic ด้วย LangChain

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้าง agent ชื่อ app โดยใช้ create_react_agent() พร้อมส่ง model และ count_r_in_word เข้าไปในรายการ tools
  • กำหนดตัวแปร query ให้รับคำถามของผู้ใช้เป็น string
  • เรียกใช้ app ด้วย .invoke() พร้อมส่ง dictionary ที่มี key ชื่อ "messages" โดยระบุ query เป็น "human"
  • เข้าถึงข้อความสุดท้ายใน response และพิมพ์ attribute .content เพื่อดูคำตอบจาก agent

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Create the agent
____ = ____(model=____, tools=[____])

# Create a query
____ = "How many r's are in the word 'Terrarium'?"

# Invoke the agent and store the response
response = app.____({"messages": [("human", ____)]})

# Print the agent's response
print(____['messages'][____].____)
แก้ไขและรันโค้ด