‫Research Agent مع Gemini 2.5 Pro وLlamaIndex

‫LlamaIndex هو إطار عمل لإنشاء وكلاء معرفة باستخدام نماذج لغوية كبيرة مرتبطة ببياناتك. يوضّح لك هذا المثال كيفية إنشاء سير عمل يتضمّن عدة وكلاء لوكيل بحث. في 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 هو نموذج لغوي كبير يعالج الاستدلال ومعالجة النصوص. يستخدم هذا المثال Gemini 2.5 Pro. تأكَّد من ضبط مفتاح واجهة برمجة التطبيقات كمتغيّر بيئة.

from llama_index.llms.google_genai import GoogleGenAI

llm = GoogleGenAI(model="gemini-2.5-pro")

أدوات الإنشاء

تستخدم البرامج أدوات للتفاعل مع العالم الخارجي، مثل البحث على الويب أو تخزين المعلومات. يمكن أن تكون الأدوات في LlamaIndex دوال Python عادية أو يتم استيرادها من ToolSpecs حالية. يتضمّن Gemini أداة مدمجة لاستخدام "بحث Google"، وهي الأداة المستخدَمة هنا.

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)

سيستخدم "العميل البحثي" دوال Python كأدوات. هناك العديد من الطرق التي يمكنك اتّباعها لإنشاء نظام ينفّذ هذه المهمة. في هذا المثال، ستستخدم ما يلي:

  1. يستخدم search_web Gemini مع "بحث Google" للبحث على الويب عن معلومات حول الموضوع المحدّد.
  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"],
)

تم تحديد "الوكلاء"، ويمكنك الآن إنشاء 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.