Trung cấpHướng dẫnClaude APINguồn: Anthropic

ReAct Agent với LlamaIndex + Claude — Lý luận + Hành động

Nghe bài viết
00:00

Điểm nổi bật

Nhấn để đến mục tương ứng

  1. 1 Để áp dụng react hoạt động như thế nào? hiệu quả, bạn cần nắm rõ: Vòng lặp ReAct bao gồm 4 bước: Thought — Agent suy nghĩ: "Tôi cần làm gì tiếp theo?" Action — Agent chọn tool và gọi với các parameters Observation — Agent nhận kết quả từ tool Repeat hoặc Answer — đây là bước quan trọng giúp tối ưu quy trình làm việc với AI trong thực tế.
  2. 2 Về tạo custom tools, thực tế cho thấy Tools là các function mà agent có thể gọi. Mỗi tool cần có tên rõ ràng và docstring mô tả chi tiết để agent biết khi nào nên dùng: float — đây là con dao hai lưỡi nếu không hiểu rõ giới hạn và điều kiện áp dụng của nó.
  3. 3 Dữ liệu từ tạo reactagent cho thấy: agent ReActAgent.from_tools toolsrevenue_tool, product_tool, llmSettings.llm, verboseTrue, # In ra thought process max_iterations10 # Giới hạn số vòng lặp print"ReAct Agent ready!" — những con số này phản ánh mức độ cải thiện thực tế mà người dùng có thể kỳ vọng.
  4. 4 Để áp dụng thêm rag tools hiệu quả, bạn cần nắm rõ: Đ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: Document # Tạo knowledge base docs Documenttext"Chính sách hoàn tiền: Khách hàng có thể hoàn trả trong 30 ngày — đây là bước quan trọng giúp tối ưu quy trình làm việc với AI trong thực tế.
  5. 5 Về memory và multi-turn conversation, thực tế cho thấy ReActAgent tích hợp sẵn conversation memory: memory ChatMemoryBuffer.from_defaultstoken_limit4096 agent_with_memory ReActAgent.from_tools toolsrevenue_tool, product_tool, kb_tool, llmSettings.llm, memorymemory, verboseFalse # Tắt verbose cho production # Multi-turn conversation printagent_with_memory.chat"Sản phẩm Claude API là — đây là con dao hai lưỡi nếu không hiểu rõ giới hạn và điều kiện áp dụng của nó.
black corded electronic device

ReAct (Reasoning + Acting) là pattern AI agent kết hợp lý luận (Chain-of-Thought) với hành động (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.

LlamaIndex cung cấp ReActAgent đượ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ủ.

ReAct hoạt động như thế nào?

Vòng lặp ReAct bao gồm 4 bước:

  1. Thought — Agent suy nghĩ: "Tôi cần làm gì tiếp theo?"
  2. Action — Agent chọn tool và gọi với các parameters
  3. Observation — Agent nhận kết quả từ tool
  4. Repeat hoặc Answer — Nếu chưa đủ thông tin, lặp lại. Nếu đủ, đưa ra câu trả lời cuối.

Ví 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.

Cài đặt

pip install llama-index llama-index-llms-anthropic llama-index-tools-wikipedia

Cấu hình cơ bản

import os
from llama_index.core import Settings
from llama_index.llms.anthropic import Anthropic

Settings.llm = Anthropic(
    model="claude-opus-4-5",
    max_tokens=2048
)

print("LlamaIndex ReAct ready")

Tạo Custom Tools

Tools là các function mà agent có thể gọi. Mỗi tool cần có tên rõ ràngdocstring mô tả chi tiết để agent biết khi nào nên dùng:

from llama_index.core.tools import FunctionTool

def calculate_revenue_growth(current: float, previous: float) -> str:
    """
    Tính phần trăm tăng trưởng doanh thu giữa hai kỳ.
    Args:
        current: Doanh thu kỳ hiện tại (float)
        previous: Doanh thu kỳ trước (float)
    Returns:
        Chuỗi mô tả phần trăm thay đổi và xu hướng
    """
    if previous == 0:
        return "Không thể tính: doanh thu kỳ trước bằng 0"
    growth = ((current - previous) / previous) * 100
    trend = "tăng" if growth > 0 else "giảm"
    return f"Doanh thu {trend} {abs(growth):.1f}% (từ {previous:,.0f} lên {current:,.0f})"

def get_product_info(product_name: str) -> str:
    """
    Lấy thông tin chi tiết về sản phẩm từ database.
    Args:
        product_name: Tên sản phẩm cần tra cứu
    Returns:
        Thông tin sản phẩm bao gồm giá, tồn kho, mô tả
    """
    # Giả lập database lookup
    products = {
        "claude_api": {
            "name": "Claude API",
            "price": "theo token",
            "description": "AI API từ Anthropic",
            "status": "active"
        },
        "claude_pro": {
            "name": "Claude Pro",
            "price": "$20/tháng",
            "description": "Gói subscription cho cá nhân",
            "status": "active"
        }
    }

    key = product_name.lower().replace(" ", "_")
    product = products.get(key)

    if product:
        return f"Sản phẩm: {product['name']}, Giá: {product['price']}, Mô tả: {product['description']}"
    else:
        return f"Không tìm thấy thông tin về sản phẩm: {product_name}"

# Wrap thành LlamaIndex FunctionTool
revenue_tool = FunctionTool.from_defaults(fn=calculate_revenue_growth)
product_tool = FunctionTool.from_defaults(fn=get_product_info)

Tạo ReActAgent

from llama_index.core.agent import ReActAgent

agent = ReActAgent.from_tools(
    tools=[revenue_tool, product_tool],
    llm=Settings.llm,
    verbose=True,  # In ra thought process
    max_iterations=10  # Giới hạn số vòng lặp
)

print("ReAct Agent ready!")

Chạy Agent

Khi verbose=True, bạn sẽ thấy toàn bộ quá trình suy nghĩ và hành động:

# Câu hỏi đơn giản - 1 tool
response = agent.chat(
    "Sản phẩm Claude API là gì?"
)
print(f"
Kết quả: {response.response}")

# Câu hỏi phức tạp - nhiều tools
response = agent.chat(
    "Nếu doanh thu Q1 2024 là 5,000,000 và Q1 2023 là 3,800,000, "
    "tăng trưởng bao nhiêu phần trăm?"
)
print(f"
Kết quả: {response.response}")

Output verbose sẽ hiển thị như sau:

Thought: Tôi cần tính phần trăm tăng trưởng doanh thu.
Action: calculate_revenue_growth
Action Input: {"current": 5000000, "previous": 3800000}
Observation: Doanh thu tăng 31.6% (từ 3,800,000 lên 5,000,000)
Thought: Tôi đã có đủ thông tin để trả lời.
Answer: Doanh thu Q1 2024 tăng 31.6% so với Q1 2023...

Thêm RAG Tools

Đ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:

from llama_index.core import VectorStoreIndex, Document
from llama_index.core.tools import QueryEngineTool

# Tạo knowledge base
docs = [
    Document(text="Chính sách hoàn tiền: Khách hàng có thể hoàn trả trong 30 ngày..."),
    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..."),
    Document(text="Hỗ trợ kỹ thuật: Email support@example.com hoặc hotline 1800-xxxx...")
]

index = VectorStoreIndex.from_documents(docs)
query_engine = index.as_query_engine(similarity_top_k=3)

# Wrap query engine thành tool
kb_tool = QueryEngineTool.from_defaults(
    query_engine=query_engine,
    name="knowledge_base",
    description="Tìm kiếm thông tin trong tài liệu nội bộ của công ty. "
                "Dùng khi cần tra cứu chính sách, điều khoản, hoặc thông tin hỗ trợ."
)

# Agent với cả function tools và RAG tool
full_agent = ReActAgent.from_tools(
    tools=[revenue_tool, product_tool, kb_tool],
    llm=Settings.llm,
    verbose=True
)

# Agent tự quyết định khi nào dùng tool nào
response = full_agent.chat(
    "Chính sách hoàn tiền như thế nào và sản phẩm Claude Pro giá bao nhiêu?"
)
print(response.response)

Memory và Multi-turn Conversation

ReActAgent tích hợp sẵn conversation memory:

from llama_index.core.memory import ChatMemoryBuffer

memory = ChatMemoryBuffer.from_defaults(token_limit=4096)

agent_with_memory = ReActAgent.from_tools(
    tools=[revenue_tool, product_tool, kb_tool],
    llm=Settings.llm,
    memory=memory,
    verbose=False  # Tắt verbose cho production
)

# Multi-turn conversation
print(agent_with_memory.chat("Sản phẩm Claude API là gì?").response)
print(agent_with_memory.chat("Giá cả như thế nào?").response)  # Nhớ context trước
print(agent_with_memory.chat("So sánh với Claude Pro đi.").response)

Error Handling và Robustness

from llama_index.core.agent import ReActAgent
from llama_index.core.llms import ChatMessage

def safe_agent_chat(agent, message, fallback="Xin lỗi, tôi không thể xử lý yêu cầu này."):
    """Wrapper an toàn cho agent với error handling."""
    try:
        response = agent.chat(message)
        return response.response
    except Exception as e:
        print(f"Agent error: {e}")
        return fallback

# Sử dụng
result = safe_agent_chat(
    agent,
    "Tính tăng trưởng doanh thu và tra cứu chính sách hoàn tiền"
)
print(result)

Kết luận

ReAct 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ứ.

Bước tiếp theo: Khám phá Multi-Document Agent với LlamaIndex để xây dựng agent truy vấn nhiều nguồn dữ liệu khác nhau, hoặc đọc về Router Query Engine để tự động chọn index phù hợp.


Bài viết liên quan

Tính năng liên quan:ReActAgentTool UseLlamaIndex

Bai viet co huu ich khong?

Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.

Bình luận (0)
Ảnh đại diện
Đăng nhập để bình luận...
Đăng nhập để bình luận
  • Đang tải bình luận...

Đăng ký nhận bản tin

Nhận bài viết hay nhất về sản phẩm và vận hành, gửi thẳng vào hộp thư của bạn.

Bảo mật thông tin. Hủy đăng ký bất cứ lúc nào. Chính sách bảo mật.