LangChain Agent Troubleshooting แก้ปัญหา

LangChain Agent Troubleshooting แก้ปัญหา

LangChain เป็น open source framework สำหรับสร้าง applications ที่ใช้ Large Language Models (LLMs) โดย Agents เป็น feature สำคัญที่ให้ LLM ตัดสินใจว่าจะใช้ tools อะไร เพื่อตอบคำถามหรือทำงานที่ซับซ้อน แต่การพัฒนา LangChain Agents มักพบปัญหาหลายอย่าง เช่น agent loop ไม่จบ, tool เรียกผิด, output parsing error, memory overflow และ performance ช้า บทความนี้รวบรวมปัญหาที่พบบ่อยและวิธีแก้ไขอย่างเป็นระบบ

FAQ - คำถามที่พบบ่อย
Q: Agent loop ไม่หยุดทำอย่างไร?
A: 1. ตั้ง max_iterations=10 (สำคัญที่สุด) 2. ใช้ early_stopping_method="force" 3. ปรับ prompt ให้ชัด: "เมื่อได้คำตอบแล้วให้ตอบทันที" 4. ใช้ model ที่ดีกว่า (GPT-4 แทน GPT-3.5) 5. ลดจำนวน tools ให้น้อยลง
Q: OutputParserException แก้อย่างไร?
A: ง่ายที่สุด: handle_parsing_errors=True (auto-retry) ดีกว่า: ใช้ OpenAI Functions agent (structured output, ไม่ต้อง parse) Advanced: ใช้ OutputFixingParser ครอบ parser เดิม ตรวจสอบ: max_tokens เพียงพอหรือไม่ (output ถูกตัด = parse fail)
Q: LangChain กับ LlamaIndex ต่างกัน?
A: LangChain: general purpose framework, agents, chains, tools, memory ครบ LlamaIndex: เน้น RAG (Retrieval-Augmented Generation), data indexing, query engine ใช้ LangChain: complex agents, multi-tool workflows, chatbots ใช้ LlamaIndex: document Q&A, knowledge base, search ใช้ทั้งคู่ได้: LlamaIndex สำหรับ RAG tool + LangChain สำหรับ agent orchestration
Q: Agent ช้ามากทำอย่างไร?
A: 1. ใช้ streaming=True (user เห็น response ทันที) 2. Cache: ใช้ SQLiteCache หรือ RedisCache สำหรับ repeated queries 3. Model: ใช้ gpt-4o-mini แทน gpt-4 สำหรับ simple tasks 4. Async: ใช้ ainvoke() สำหรับ parallel tool execution 5. ลด iterations: max_iterations=5 + เขียน prompt ให้ดี





