LlamaIndex เป็นเฟรมเวิร์กสำหรับการสร้างเอเจนต์ความรู้โดยใช้ LLM ที่เชื่อมต่อกับข้อมูลของคุณ ตัวอย่างนี้แสดงวิธีสร้างเวิร์กโฟลว์แบบหลายเอเจนต์สำหรับเอเจนต์การวิจัย ใน 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 สามารถเป็นฟังก์ชัน Python ปกติ หรือนำเข้าจาก ToolSpecs
ที่มีอยู่แล้วก็ได้ Gemini มาพร้อมเครื่องมือในตัวสำหรับใช้ Google Search ซึ่งใช้ในที่นี้
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)
Research Agent จะใช้ฟังก์ชัน Python เป็นเครื่องมือ คุณสร้างระบบเพื่อทำงานนี้ได้หลายวิธี ในตัวอย่างนี้ คุณจะใช้รายการต่อไปนี้
search_web
ใช้ Gemini กับ Google Search เพื่อค้นหาข้อมูลในเว็บเกี่ยวกับหัวข้อที่ระบุ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."
สร้างผู้ช่วยแบบหลายเอเจนต์
หากต้องการสร้างระบบแบบหลายเอเจนต์ คุณต้องกำหนดเอเจนต์และการโต้ตอบของเอเจนต์ ระบบของคุณจะมีเอเจนต์ 3 รายดังนี้
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"],
)
ตอนนี้คุณได้กำหนดเอเจนต์แล้ว จึงสร้าง 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
เป็นวิธีที่ยอดเยี่ยมในการเริ่มต้นใช้งานระบบแบบหลายเอเจนต์ แต่หากต้องการการควบคุมเพิ่มเติม คุณสร้างเวิร์กโฟลว์ได้ตั้งแต่ต้น เหตุผลบางประการที่คุณอาจต้องการสร้างเวิร์กโฟลว์ของคุณเองมีดังนี้
- ควบคุมกระบวนการได้มากขึ้น: คุณสามารถกำหนดเส้นทางที่แน่นอนที่ตัวแทนจะใช้ได้ ซึ่งรวมถึงการสร้างลูป การตัดสินใจในบางจุด หรือการให้ตัวแทนทำงานแบบคู่ขนานในงานต่างๆ
- ใช้ข้อมูลที่ซับซ้อน: ใช้ข้อมูลที่ซับซ้อนกว่าข้อความธรรมดา เวิร์กโฟลว์ที่กำหนดเองช่วยให้คุณใช้ Structured Data เพิ่มเติม เช่น ออบเจ็กต์ JSON หรือคลาสที่กำหนดเอง สำหรับอินพุตและเอาต์พุตได้
- ทำงานกับสื่อต่างๆ: สร้างเอเจนต์ที่เข้าใจและประมวลผลได้ไม่เพียงแค่ข้อความ แต่ยังรวมถึงรูปภาพ เสียง และวิดีโอด้วย
- การวางแผนที่ชาญฉลาดยิ่งขึ้น: คุณสามารถออกแบบเวิร์กโฟลว์ที่สร้างแผนโดยละเอียดก่อนที่ตัวแทนจะเริ่มทำงาน ซึ่งมีประโยชน์สำหรับงานที่ซับซ้อนซึ่งต้องทำหลายขั้นตอน
- เปิดใช้การแก้ไขด้วยตนเอง: สร้างเอเจนต์ที่ตรวจสอบงานของตนเองได้ หากผลลัพธ์ไม่ดีพอ เอเจนต์จะลองอีกครั้งได้ ซึ่งจะสร้างวงจรการปรับปรุงจนกว่าผลลัพธ์จะสมบูรณ์แบบ
ดูข้อมูลเพิ่มเติมเกี่ยวกับเวิร์กโฟลว์ LlamaIndex ได้ที่เอกสารประกอบเกี่ยวกับเวิร์กโฟลว์ LlamaIndex