نماینده تحقیقاتی با Gemini و LlamaIndex

LlamaIndex چارچوبی برای ساخت عامل‌های دانش با استفاده از LLM های متصل به داده‌های شما است. این مثال به شما نشان می‌دهد که چگونه یک گردش کار چندعاملی برای یک عامل تحقیقاتی بسازید. در LlamaIndex، Workflows بلوک‌های سازنده عامل و سیستم‌های چندعاملی هستند.

شما به یک کلید API Gemini نیاز دارید. اگر از قبل آن را ندارید، می‌توانید آن را در Google AI Studio دریافت کنید . ابتدا، تمام کتابخانه‌های مورد نیاز LlamaIndex را نصب کنید. LlamaIndex از بسته google-genai در داخل خود استفاده می‌کند.

pip install llama-index llama-index-utils-workflow llama-index-llms-google-genai llama-index-tools-google

راه‌اندازی Gemini در LlamaIndex

موتور هر عامل LlamaIndex یک LLM است که استدلال و پردازش متن را مدیریت می‌کند. این مثال از Gemini 3 Flash استفاده می‌کند. مطمئن شوید که کلید API خود را به عنوان یک متغیر محیطی تنظیم کرده‌اید .

import os
from llama_index.llms.google_genai import GoogleGenAI

# Set your API key in the environment elsewhere, or with os.environ['GEMINI_API_KEY'] = '...'
assert 'GEMINI_API_KEY' in os.environ

llm = GoogleGenAI(model="gemini-3-flash-preview")

ابزارهای ساخت

عامل‌ها از ابزارهایی برای تعامل با دنیای خارج، مانند جستجو در وب یا ذخیره اطلاعات، استفاده می‌کنند. ابزارها در LlamaIndex می‌توانند توابع معمولی پایتون باشند یا از ToolSpecs از پیش موجود وارد شوند. Gemini با یک ابزار داخلی برای استفاده از جستجوی گوگل ارائه می‌شود که در اینجا استفاده می‌شود.

from google.genai import types

google_search_tool = types.Tool(
    google_search=types.GoogleSearch()
)

llm_with_search = GoogleGenAI(
    model="gemini-3-flash-preview",
    generation_config=types.GenerateContentConfig(tools=[google_search_tool])
)

حالا نمونه LLM را با یک پرس‌وجو که نیاز به جستجو دارد، آزمایش کنید. این راهنما یک حلقه رویداد در حال اجرا (مانند python -m asyncio یا Google Colab) را فرض می‌کند.

response = await llm_with_search.acomplete("What's the weather like today in Biarritz?")
print(response)

عامل تحقیق از توابع پایتون به عنوان ابزار استفاده خواهد کرد. روش‌های زیادی برای ساخت سیستمی جهت انجام این کار وجود دارد. در این مثال، از موارد زیر استفاده خواهید کرد:

  1. search_web از Gemini به همراه جستجوی گوگل برای جستجوی اطلاعات در مورد موضوع داده شده در وب استفاده می‌کند.
  2. record_notes تحقیقات یافت شده در وب را در وضعیت ذخیره می‌کند تا سایر ابزارها بتوانند از آن استفاده کنند.
  3. write_report با استفاده از اطلاعات یافت شده توسط ResearchAgent گزارش را می‌نویسد.
  4. review_report گزارش را بررسی کرده و بازخورد ارائه می‌دهد.

کلاس Context وضعیت را بین عامل‌ها/ابزارها منتقل می‌کند و هر عامل به وضعیت فعلی سیستم دسترسی خواهد داشت.

from llama_index.core.workflow import Context

async def search_web(ctx: Context, query: str) -> str:
    """Useful for searching the web about a specific query or topic"""
    response = await llm_with_search.acomplete(f"""Please research given this query or topic,
    and return the result\n<query_or_topic>{query}</query_or_topic>""")
    return response

async def record_notes(ctx: Context, notes: str, notes_title: str) -> str:
    """Useful for recording notes on a given topic."""
    current_state = await ctx.store.get("state")
    if "research_notes" not in current_state:
        current_state["research_notes"] = {}
    current_state["research_notes"][notes_title] = notes
    await ctx.store.set("state", current_state)
    return "Notes recorded."

async def write_report(ctx: Context, report_content: str) -> str:
    """Useful for writing a report on a given topic."""
    current_state = await ctx.store.get("state")
    current_state["report_content"] = report_content
    await ctx.store.set("state", current_state)
    return "Report written."

async def review_report(ctx: Context, review: str) -> str:
    """Useful for reviewing a report and providing feedback."""
    current_state = await ctx.store.get("state")
    current_state["review"] = review
    await ctx.store.set("state", current_state)
    return "Report reviewed."

ساخت یک دستیار چندعاملی

برای ساخت یک سیستم چندعاملی، شما عامل‌ها و تعاملات آنها را تعریف می‌کنید. سیستم شما سه عامل خواهد داشت:

  1. یک ResearchAgent در وب به دنبال اطلاعات مربوط به موضوع داده شده می‌گردد.
  2. یک WriteAgent گزارش را با استفاده از اطلاعات یافت شده توسط ResearchAgent می‌نویسد.
  3. یک ReviewAgent گزارش را بررسی کرده و بازخورد ارائه می‌دهد.

این مثال از کلاس AgentWorkflow برای ایجاد یک سیستم چندعاملی استفاده می‌کند که این عامل‌ها را به ترتیب اجرا می‌کند. هر عامل یک system_prompt می‌گیرد که به آن می‌گوید چه کاری باید انجام دهد و نحوه کار با سایر عامل‌ها را پیشنهاد می‌دهد.

به صورت اختیاری، می‌توانید با مشخص کردن اینکه سیستم چندعامله شما با استفاده از can_handoff_to می‌تواند با کدام عامل‌های دیگر صحبت کند، به آن کمک کنید (اگر اینطور نباشد، سیستم سعی می‌کند خودش این موضوع را کشف کند).

from llama_index.core.agent.workflow import (
    AgentInput,
    AgentOutput,
    ToolCall,
    ToolCallResult,
    AgentStream,
)
from llama_index.core.agent.workflow import FunctionAgent, ReActAgent

research_agent = FunctionAgent(
    name="ResearchAgent",
    description="Useful for searching the web for information on a given topic and recording notes on the topic.",
    system_prompt=(
        "You are the ResearchAgent that can search the web for information on a given topic and record notes on the topic. "
        "Once notes are recorded and you are satisfied, you should hand off control to the WriteAgent to write a report on the topic."
    ),
    llm=llm,
    tools=[search_web, record_notes],
    can_handoff_to=["WriteAgent"],
)

write_agent = FunctionAgent(
    name="WriteAgent",
    description="Useful for writing a report on a given topic.",
    system_prompt=(
        "You are the WriteAgent that can write a report on a given topic. "
        "Your report should be in a markdown format. The content should be grounded in the research notes. "
        "Once the report is written, you should get feedback at least once from the ReviewAgent."
    ),
    llm=llm,
    tools=[write_report],
    can_handoff_to=["ReviewAgent", "ResearchAgent"],
)

review_agent = FunctionAgent(
    name="ReviewAgent",
    description="Useful for reviewing a report and providing feedback.",
    system_prompt=(
        "You are the ReviewAgent that can review a report and provide feedback. "
        "Your feedback should either approve the current report or request changes for the WriteAgent to implement."
    ),
    llm=llm,
    tools=[review_report],
    can_handoff_to=["ResearchAgent","WriteAgent"],
)

Agentها تعریف شده‌اند، حالا می‌توانید AgentWorkflow ایجاد کرده و آن را اجرا کنید.

from llama_index.core.agent.workflow import AgentWorkflow

agent_workflow = AgentWorkflow(
    agents=[research_agent, write_agent, review_agent],
    root_agent=research_agent.name,
    initial_state={
        "research_notes": {},
        "report_content": "Not written yet.",
        "review": "Review required.",
    },
)

در حین اجرای گردش کار، می‌توانید رویدادها، فراخوانی ابزارها و به‌روزرسانی‌ها را به کنسول منتقل کنید.

from llama_index.core.agent.workflow import (
    AgentInput,
    AgentOutput,
    ToolCall,
    ToolCallResult,
    AgentStream,
)

research_topic = """Write me a report on the history of the web.
Briefly describe the history of the world wide web, including
the development of the internet and the development of the web,
including 21st century developments"""

handler = agent_workflow.run(
    user_msg=research_topic
)

current_agent = None
current_tool_calls = ""
async for event in handler.stream_events():
    if (
        hasattr(event, "current_agent_name")
        and event.current_agent_name != current_agent
    ):
        current_agent = event.current_agent_name
        print(f"\n{'='*50}")
        print(f"🤖 Agent: {current_agent}")
        print(f"{'='*50}\n")
    elif isinstance(event, AgentOutput):
        if event.response.content:
            print("📤 Output:", event.response.content)
        if event.tool_calls:
            print(
                "🛠️  Planning to use tools:",
                [call.tool_name for call in event.tool_calls],
            )
    elif isinstance(event, ToolCallResult):
        print(f"🔧 Tool Result ({event.tool_name}):")
        print(f"  Arguments: {event.tool_kwargs}")
        print(f"  Output: {event.tool_output}")
    elif isinstance(event, ToolCall):
        print(f"🔨 Calling Tool: {event.tool_name}")
        print(f"  With arguments: {event.tool_kwargs}")

پس از تکمیل گردش کار، می‌توانید خروجی نهایی گزارش و همچنین وضعیت بررسی نهایی از طرف نماینده بررسی را چاپ کنید.

state = await handler.ctx.store.get("state")
print("Report Content:\n", state["report_content"])
print("\n------------\nFinal Review:\n", state["review"])

با گردش‌های کاری سفارشی، فراتر بروید

AgentWorkflow یک راه عالی برای شروع کار با سیستم‌های چندعاملی است. اما اگر به کنترل بیشتری نیاز دارید چه؟ می‌توانید یک گردش کار را از ابتدا بسازید. در اینجا چند دلیل برای اینکه ممکن است بخواهید گردش کار خودتان را بسازید، آورده شده است:

  • کنترل بیشتر بر فرآیند : شما می‌توانید مسیر دقیقی را که عوامل شما طی می‌کنند، تعیین کنید. این شامل ایجاد حلقه‌ها، تصمیم‌گیری در نقاط خاص یا کار موازی عوامل بر روی وظایف مختلف می‌شود.
  • استفاده از داده‌های پیچیده : فراتر از متن ساده عمل کنید. گردش‌های کاری سفارشی به شما امکان می‌دهند از داده‌های ساختاریافته‌تری مانند اشیاء JSON یا کلاس‌های سفارشی برای ورودی‌ها و خروجی‌های خود استفاده کنید.
  • کار با رسانه‌های مختلف : عواملی بسازید که نه تنها متن، بلکه تصاویر، صدا و ویدیو را نیز درک و پردازش کنند.
  • برنامه‌ریزی هوشمندانه‌تر : می‌توانید گردش کاری طراحی کنید که قبل از شروع کار اپراتورها، ابتدا یک برنامه دقیق ایجاد کند. این برای کارهای پیچیده‌ای که نیاز به مراحل متعدد دارند، مفید است.
  • فعال کردن خود-اصلاحی : عواملی ایجاد کنید که بتوانند کار خود را بررسی کنند. اگر خروجی به اندازه کافی خوب نباشد، عامل می‌تواند دوباره امتحان کند و یک حلقه بهبود ایجاد کند تا نتیجه کامل شود.

برای کسب اطلاعات بیشتر در مورد گردش‌های کاری LlamaIndex، به مستندات گردش‌های کاری LlamaIndex مراجعه کنید.