LlamaIndex چارچوبی برای ایجاد عوامل دانش با استفاده از LLM های متصل به داده های شما است. این مثال به شما نشان میدهد که چگونه یک گردش کار چند عاملی برای یک Research Agent بسازید. در LlamaIndex، Workflows
بلوک های سازنده سیستم های عامل یا چند عاملی هستند.
شما به یک کلید Gemini API نیاز دارید. اگر قبلاً ندارید، میتوانید در 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 2.5 Pro را در LlamaIndex راه اندازی کنید
موتور هر عامل LlamaIndex یک LLM است که استدلال و پردازش متن را مدیریت می کند. این مثال از Gemini 2.5 Pro استفاده می کند. مطمئن شوید که کلید API خود را به عنوان یک متغیر محیطی تنظیم کرده اید.
from llama_index.llms.google_genai import GoogleGenAI
llm = GoogleGenAI(model="gemini-2.5-pro")
ابزار بسازید
نمایندگان از ابزارهایی برای تعامل با دنیای خارج استفاده می کنند، مانند جستجو در وب یا ذخیره اطلاعات. ابزارهای موجود در LlamaIndex میتوانند توابع منظم پایتون باشند یا از ToolSpecs
از قبل موجود وارد شده باشند. Gemini یک ابزار داخلی برای استفاده از جستجوی گوگل دارد که در اینجا استفاده می شود.
from google.genai import types
google_search_tool = types.Tool(
google_search=types.GoogleSearch()
)
llm_with_search = GoogleGenAI(
model="gemini-2.5-pro",
generation_config=types.GenerateContentConfig(tools=[google_search_tool])
)
اکنون نمونه LLM را با یک کوئری که به جستجو نیاز دارد آزمایش کنید:
response = llm_with_search.complete("What's the weather like today in Biarritz?")
print(response)
عامل تحقیق از توابع پایتون به عنوان ابزار استفاده خواهد کرد. راه های زیادی وجود دارد که می توانید برای ساختن یک سیستم برای انجام این کار استفاده کنید. در این مثال از موارد زیر استفاده خواهید کرد:
-
search_web
از Gemini با جستجوی Google برای جستجوی وب برای اطلاعات مربوط به موضوع مورد نظر استفاده می کند. -
record_notes
تحقیقات موجود در وب را در حالت ذخیره می کند تا سایر ابزارها بتوانند از آن استفاده کنند. -
write_report
گزارش را با استفاده از اطلاعات یافت شده توسطResearchAgent
می نویسد -
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."
یک دستیار چند عامله بسازید
برای ساختن یک سیستم چند عاملی، شما عامل ها و تعاملات آنها را تعریف می کنید. سیستم شما دارای سه عامل خواهد بود:
- یک
ResearchAgent
در وب برای اطلاعات در مورد موضوع مورد نظر جستجو می کند. - یک
WriteAgent
گزارش را با استفاده از اطلاعات یافت شده توسطResearchAgent
می نویسد. - یک
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 Workflows، به مستندات LlamaIndex Workflows مراجعه کنید.