{"product_id":"react-agent-với-llamaindex-claude-ly-luận-hanh-dộng","title":"ReAct Agent với LlamaIndex + Claude — Lý luận + Hành động","description":"\n\u003cp\u003e\u003cstrong\u003eReAct\u003c\/strong\u003e (Reasoning + Acting) là pattern AI agent kết hợp \u003cem\u003elý luận\u003c\/em\u003e (Chain-of-Thought) với \u003cem\u003ehành động\u003c\/em\u003e (Tool Use) trong vòng lặp lặp đi lặp lại. Agent suy nghĩ về bước tiếp theo, thực hiện action, quan sát kết quả, rồi lại suy nghĩ tiếp — cho đến khi đạt được mục tiêu.\u003c\/p\u003e\n\n\u003cp\u003eLlamaIndex cung cấp \u003ccode\u003eReActAgent\u003c\/code\u003e được tối ưu hóa để hoạt động với Claude, giúp bạn xây dựng AI agent có khả năng giải quyết bài toán đa bước một cách tự chủ.\u003c\/p\u003e\n\n\u003ch2\u003eReAct hoạt động như thế nào?\u003c\/h2\u003e\n\n\u003cp\u003eVòng lặp ReAct bao gồm 4 bước:\u003c\/p\u003e\n\n\u003col\u003e\n  \u003cli\u003e\n\u003cstrong\u003eThought\u003c\/strong\u003e — Agent suy nghĩ: \"Tôi cần làm gì tiếp theo?\"\u003c\/li\u003e\n  \u003cli\u003e\n\u003cstrong\u003eAction\u003c\/strong\u003e — Agent chọn tool và gọi với các parameters\u003c\/li\u003e\n  \u003cli\u003e\n\u003cstrong\u003eObservation\u003c\/strong\u003e — Agent nhận kết quả từ tool\u003c\/li\u003e\n  \u003cli\u003e\n\u003cstrong\u003eRepeat hoặc Answer\u003c\/strong\u003e — Nếu chưa đủ thông tin, lặp lại. Nếu đủ, đưa ra câu trả lời cuối.\u003c\/li\u003e\n\u003c\/ol\u003e\n\n\u003cp\u003eVí dụ: \"Doanh thu Q1 2024 tăng hay giảm so với Q1 2023?\" Agent sẽ: (1) tìm doanh thu Q1 2024, (2) tìm doanh thu Q1 2023, (3) tính phần trăm thay đổi, (4) đưa ra kết luận.\u003c\/p\u003e\n\n\u003ch2\u003eCài đặt\u003c\/h2\u003e\n\n\u003cpre\u003e\u003ccode\u003epip install llama-index llama-index-llms-anthropic llama-index-tools-wikipedia\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eCấu hình cơ bản\u003c\/h2\u003e\n\n\u003cpre\u003e\u003ccode\u003eimport os\nfrom llama_index.core import Settings\nfrom llama_index.llms.anthropic import Anthropic\n\nSettings.llm = Anthropic(\n    model=\"claude-opus-4-5\",\n    max_tokens=2048\n)\n\nprint(\"LlamaIndex ReAct ready\")\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eTạo Custom Tools\u003c\/h2\u003e\n\n\u003cp\u003eTools là các function mà agent có thể gọi. Mỗi tool cần có \u003cstrong\u003etên rõ ràng\u003c\/strong\u003e và \u003cstrong\u003edocstring mô tả chi tiết\u003c\/strong\u003e để agent biết khi nào nên dùng:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003efrom llama_index.core.tools import FunctionTool\n\ndef calculate_revenue_growth(current: float, previous: float) -\u0026gt; str:\n    \"\"\"\n    Tính phần trăm tăng trưởng doanh thu giữa hai kỳ.\n    Args:\n        current: Doanh thu kỳ hiện tại (float)\n        previous: Doanh thu kỳ trước (float)\n    Returns:\n        Chuỗi mô tả phần trăm thay đổi và xu hướng\n    \"\"\"\n    if previous == 0:\n        return \"Không thể tính: doanh thu kỳ trước bằng 0\"\n    growth = ((current - previous) \/ previous) * 100\n    trend = \"tăng\" if growth \u0026gt; 0 else \"giảm\"\n    return f\"Doanh thu {trend} {abs(growth):.1f}% (từ {previous:,.0f} lên {current:,.0f})\"\n\ndef get_product_info(product_name: str) -\u0026gt; str:\n    \"\"\"\n    Lấy thông tin chi tiết về sản phẩm từ database.\n    Args:\n        product_name: Tên sản phẩm cần tra cứu\n    Returns:\n        Thông tin sản phẩm bao gồm giá, tồn kho, mô tả\n    \"\"\"\n    # Giả lập database lookup\n    products = {\n        \"claude_api\": {\n            \"name\": \"Claude API\",\n            \"price\": \"theo token\",\n            \"description\": \"AI API từ Anthropic\",\n            \"status\": \"active\"\n        },\n        \"claude_pro\": {\n            \"name\": \"Claude Pro\",\n            \"price\": \"$20\/tháng\",\n            \"description\": \"Gói subscription cho cá nhân\",\n            \"status\": \"active\"\n        }\n    }\n\n    key = product_name.lower().replace(\" \", \"_\")\n    product = products.get(key)\n\n    if product:\n        return f\"Sản phẩm: {product['name']}, Giá: {product['price']}, Mô tả: {product['description']}\"\n    else:\n        return f\"Không tìm thấy thông tin về sản phẩm: {product_name}\"\n\n# Wrap thành LlamaIndex FunctionTool\nrevenue_tool = FunctionTool.from_defaults(fn=calculate_revenue_growth)\nproduct_tool = FunctionTool.from_defaults(fn=get_product_info)\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eTạo ReActAgent\u003c\/h2\u003e\n\n\u003cpre\u003e\u003ccode\u003efrom llama_index.core.agent import ReActAgent\n\nagent = ReActAgent.from_tools(\n    tools=[revenue_tool, product_tool],\n    llm=Settings.llm,\n    verbose=True,  # In ra thought process\n    max_iterations=10  # Giới hạn số vòng lặp\n)\n\nprint(\"ReAct Agent ready!\")\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eChạy Agent\u003c\/h2\u003e\n\n\u003cp\u003eKhi \u003ccode\u003everbose=True\u003c\/code\u003e, bạn sẽ thấy toàn bộ quá trình suy nghĩ và hành động:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003e# Câu hỏi đơn giản - 1 tool\nresponse = agent.chat(\n    \"Sản phẩm Claude API là gì?\"\n)\nprint(f\"\nKết quả: {response.response}\")\n\n# Câu hỏi phức tạp - nhiều tools\nresponse = agent.chat(\n    \"Nếu doanh thu Q1 2024 là 5,000,000 và Q1 2023 là 3,800,000, \"\n    \"tăng trưởng bao nhiêu phần trăm?\"\n)\nprint(f\"\nKết quả: {response.response}\")\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003cp\u003eOutput verbose sẽ hiển thị như sau:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003eThought: Tôi cần tính phần trăm tăng trưởng doanh thu.\nAction: calculate_revenue_growth\nAction Input: {\"current\": 5000000, \"previous\": 3800000}\nObservation: Doanh thu tăng 31.6% (từ 3,800,000 lên 5,000,000)\nThought: Tôi đã có đủ thông tin để trả lời.\nAnswer: Doanh thu Q1 2024 tăng 31.6% so với Q1 2023...\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eThêm RAG Tools\u003c\/h2\u003e\n\n\u003cp\u003eĐiểm mạnh của LlamaIndex là kết hợp ReAct Agent với RAG — agent có thể search knowledge base như một tool:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003efrom llama_index.core import VectorStoreIndex, Document\nfrom llama_index.core.tools import QueryEngineTool\n\n# Tạo knowledge base\ndocs = [\n    Document(text=\"Chính sách hoàn tiền: Khách hàng có thể hoàn trả trong 30 ngày...\"),\n    Document(text=\"Điều khoản dịch vụ: Người dùng đồng ý không dùng cho mục đích phi pháp...\"),\n    Document(text=\"Hỗ trợ kỹ thuật: Email support@example.com hoặc hotline 1800-xxxx...\")\n]\n\nindex = VectorStoreIndex.from_documents(docs)\nquery_engine = index.as_query_engine(similarity_top_k=3)\n\n# Wrap query engine thành tool\nkb_tool = QueryEngineTool.from_defaults(\n    query_engine=query_engine,\n    name=\"knowledge_base\",\n    description=\"Tìm kiếm thông tin trong tài liệu nội bộ của công ty. \"\n                \"Dùng khi cần tra cứu chính sách, điều khoản, hoặc thông tin hỗ trợ.\"\n)\n\n# Agent với cả function tools và RAG tool\nfull_agent = ReActAgent.from_tools(\n    tools=[revenue_tool, product_tool, kb_tool],\n    llm=Settings.llm,\n    verbose=True\n)\n\n# Agent tự quyết định khi nào dùng tool nào\nresponse = full_agent.chat(\n    \"Chính sách hoàn tiền như thế nào và sản phẩm Claude Pro giá bao nhiêu?\"\n)\nprint(response.response)\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eMemory và Multi-turn Conversation\u003c\/h2\u003e\n\n\u003cp\u003eReActAgent tích hợp sẵn conversation memory:\u003c\/p\u003e\n\n\u003cpre\u003e\u003ccode\u003efrom llama_index.core.memory import ChatMemoryBuffer\n\nmemory = ChatMemoryBuffer.from_defaults(token_limit=4096)\n\nagent_with_memory = ReActAgent.from_tools(\n    tools=[revenue_tool, product_tool, kb_tool],\n    llm=Settings.llm,\n    memory=memory,\n    verbose=False  # Tắt verbose cho production\n)\n\n# Multi-turn conversation\nprint(agent_with_memory.chat(\"Sản phẩm Claude API là gì?\").response)\nprint(agent_with_memory.chat(\"Giá cả như thế nào?\").response)  # Nhớ context trước\nprint(agent_with_memory.chat(\"So sánh với Claude Pro đi.\").response)\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eError Handling và Robustness\u003c\/h2\u003e\n\n\u003cpre\u003e\u003ccode\u003efrom llama_index.core.agent import ReActAgent\nfrom llama_index.core.llms import ChatMessage\n\ndef safe_agent_chat(agent, message, fallback=\"Xin lỗi, tôi không thể xử lý yêu cầu này.\"):\n    \"\"\"Wrapper an toàn cho agent với error handling.\"\"\"\n    try:\n        response = agent.chat(message)\n        return response.response\n    except Exception as e:\n        print(f\"Agent error: {e}\")\n        return fallback\n\n# Sử dụng\nresult = safe_agent_chat(\n    agent,\n    \"Tính tăng trưởng doanh thu và tra cứu chính sách hoàn tiền\"\n)\nprint(result)\u003c\/code\u003e\u003c\/pre\u003e\n\n\u003ch2\u003eKết luận\u003c\/h2\u003e\n\n\u003cp\u003eReAct Agent với LlamaIndex + Claude là nền tảng mạnh mẽ để xây dựng AI có khả năng giải quyết bài toán đa bước. Agent tự quyết định thứ tự sử dụng tools, lý luận dựa trên kết quả trung gian, và đưa ra câu trả lời cuối cùng có căn cứ.\u003c\/p\u003e\n\n\u003cp\u003eBước tiếp theo: Khám phá \u003ca href=\"\/collections\/nang-cao\"\u003eMulti-Document Agent với LlamaIndex\u003c\/a\u003e để xây dựng agent truy vấn nhiều nguồn dữ liệu khác nhau, hoặc đọc về \u003ca href=\"\/collections\/nang-cao\"\u003eRouter Query Engine\u003c\/a\u003e để tự động chọn index phù hợp.\u003c\/p\u003e\n\n\u003chr\u003e\n\u003ch3\u003eBài viết liên quan\u003c\/h3\u003e\n\u003cul\u003e\n\u003cli\u003e\u003ca href=\"\/products\/calculator-tool-bai-h%E1%BB%8Dc-d%E1%BA%A7u-tien-v%E1%BB%81-tool-use-v%E1%BB%9Bi-claude\"\u003eCalculator Tool — Bài học đầu tiên về Tool Use với Claude\u003c\/a\u003e\u003c\/li\u003e\n\u003cli\u003e\u003ca href=\"\/products\/multi-document-agent-truy-v%E1%BA%A5n-nhi%E1%BB%81u-tai-li%E1%BB%87u-v%E1%BB%9Bi-llamaindex\"\u003eMulti-Document Agent — Truy vấn nhiều tài liệu với LlamaIndex\u003c\/a\u003e\u003c\/li\u003e\n\u003cli\u003e\u003ca href=\"\/products\/context-compaction-t%E1%BB%B1-d%E1%BB%99ng-nen-context-cho-conversations-dai\"\u003eContext Compaction — Tự động nén context cho conversations dài\u003c\/a\u003e\u003c\/li\u003e\n\u003cli\u003e\u003ca href=\"\/products\/building-effective-agents-v%E1%BB%9Bi-claude-h%C6%B0%E1%BB%9Bng-d%E1%BA%ABn-ki%E1%BA%BFn-truc\"\u003eBuilding Effective Agents với Claude — Hướng dẫn kiến trúc\u003c\/a\u003e\u003c\/li\u003e\n\u003cli\u003e\u003ca href=\"\/products\/autonomous-coding-agent-ai-t%E1%BB%B1-vi%E1%BA%BFt-code-t%E1%BB%AB-spec\"\u003eAutonomous Coding Agent — AI tự viết code từ spec\u003c\/a\u003e\u003c\/li\u003e\n\u003c\/ul\u003e","brand":"Minh Tuấn","offers":[{"title":"Default Title","offer_id":66959028977709,"sku":null,"price":0.0,"currency_code":"VND","in_stock":true}],"thumbnail_url":"\/\/cdn.shopify.com\/s\/files\/1\/0763\/9531\/5245\/files\/react-agent-v_i-llamaindex-claude-ly-lu_n-hanh-d_ng_f49b9ebb-a0b8-4271-8257-f4b856346611.jpg?v=1782891878","url":"https:\/\/claudeae.com\/products\/react-agent-v%e1%bb%9bi-llamaindex-claude-ly-lu%e1%ba%adn-hanh-d%e1%bb%99ng","provider":"Claude.vn","version":"1.0","type":"link"}