Rumah >Peranti teknologi >AI >Aliran Kerja Multi-Agen dengan Llamaindex untuk Penyelidikan & Penulisan
Ejen model bahasa yang besar adalah alat yang berkuasa untuk mengautomasikan tugas seperti carian, penjanaan kandungan, dan semakan kualiti. Walau bagaimanapun, ejen tunggal sering tidak dapat melakukan segala -galanya dengan cekap, terutamanya apabila anda perlu mengintegrasikan sumber luaran (seperti carian web) dan beberapa langkah khusus (mis., Penggubalan vs kajian semula). Aliran kerja multi-agen membolehkan anda memecah tugas-tugas ini di kalangan agen yang berbeza, masing-masing dengan alat, kekangan, dan tanggungjawabnya sendiri. Dalam artikel ini, kita akan melihat bagaimana untuk membina sistem tiga-ejen-Penyelarasan, Writeagent, dan Reviewent-di mana setiap ejen mengendalikan bahagian tertentu dalam mewujudkan laporan sejarah ringkas di Internet. Kami juga akan memastikan sistem tidak akan terjebak dalam gelung carian, yang boleh membuang masa dan kredit.
Jadual Kandungan Model Bahasa (LLM)-OpenAI GPT-4 Alat penting untuk aliran kerja
############################################################################### # 1. INSTALLATION ############################################################################### # Make sure you have the following installed: # pip install llama-index langchain duckduckgo-search ############################################################################### # 2. IMPORTS ############################################################################### %pip install llama-index langchain duckduckgo-search from llama_index.llms.openai import OpenAI # For DuckDuckGo search via LangChain from langchain.utilities import DuckDuckGoSearchAPIWrapper # llama-index workflow classes from llama_index.core.workflow import Context from llama_index.core.agent.workflow import ( FunctionAgent, AgentWorkflow, AgentInput, AgentOutput, ToolCall, ToolCallResult, AgentStream ) import asyncio ############################################################################### # 3. CREATE LLM ############################################################################### # Replace "sk-..." with your actual OpenAI API key llm = OpenAI(model="gpt-4", api_key="OPENAI_API_KEY")
API untuk perkhidmatan luaran
############################################################################### # 1. INSTALLATION ############################################################################### # Make sure you have the following installed: # pip install llama-index langchain duckduckgo-search ############################################################################### # 2. IMPORTS ############################################################################### %pip install llama-index langchain duckduckgo-search from llama_index.llms.openai import OpenAI # For DuckDuckGo search via LangChain from langchain.utilities import DuckDuckGoSearchAPIWrapper # llama-index workflow classes from llama_index.core.workflow import Context from llama_index.core.agent.workflow import ( FunctionAgent, AgentWorkflow, AgentInput, AgentOutput, ToolCall, ToolCallResult, AgentStream ) import asyncio ############################################################################### # 3. CREATE LLM ############################################################################### # Replace "sk-..." with your actual OpenAI API key llm = OpenAI(model="gpt-4", api_key="OPENAI_API_KEY")alur kerja ejen - Penyelarasan Pelaksanaan Tugas
Bina aliran kerja
Jalankan aliran kerja
############################################################################### # 4. DEFINE DUCKDUCKGO SEARCH TOOL WITH SAFEGUARDS ############################################################################### # We wrap LangChain's DuckDuckGoSearchAPIWrapper with our own logic # to prevent repeated or excessive searches. duckduckgo = DuckDuckGoSearchAPIWrapper() MAX_SEARCH_CALLS = 2 search_call_count = 0 past_queries = set() async def safe_duckduckgo_search(query: str) -> str: """ A DuckDuckGo-based search function that: 1) Prevents more than MAX_SEARCH_CALLS total searches. 2) Skips duplicate queries. """ global search_call_count, past_queries # Check for duplicate queries if query in past_queries: return f"Already searched for '{query}'. Avoiding duplicate search." # Check if we've reached the max search calls if search_call_count >= MAX_SEARCH_CALLS: return "Search limit reached, no more searches allowed." # Otherwise, perform the search search_call_count += 1 past_queries.add(query) # DuckDuckGoSearchAPIWrapper.run(...) is synchronous, but we have an async signature result = duckduckgo.run(query) return str(result) ############################################################################### # 5. OTHER TOOL FUNCTIONS: record_notes, write_report, review_report ############################################################################### async def record_notes(ctx: Context, notes: str, notes_title: str) -> str: """Store research notes under a given title in the shared context.""" current_state = await ctx.get("state") if "research_notes" not in current_state: current_state["research_notes"] = {} current_state["research_notes"][notes_title] = notes await ctx.set("state", current_state) return "Notes recorded." async def write_report(ctx: Context, report_content: str) -> str: """Write a report in markdown, storing it in the shared context.""" current_state = await ctx.get("state") current_state["report_content"] = report_content await ctx.set("state", current_state) return "Report written." async def review_report(ctx: Context, review: str) -> str: """Review the report and store feedback in the shared context.""" current_state = await ctx.get("state") current_state["review"] = review await ctx.set("state", current_state) return "Report reviewed."
acara aliran untuk debug atau pemerhatian
############################################################################### # 6. DEFINE AGENTS ############################################################################### # We have three agents with distinct responsibilities: # 1. ResearchAgent - uses DuckDuckGo to gather info (max 2 searches). # 2. WriteAgent - composes the final report. # 3. ReviewAgent - reviews the final report. research_agent = FunctionAgent( name="ResearchAgent", description=( "A research agent that searches the web using DuckDuckGo. " "It must not exceed 2 searches total, and must avoid repeating the same query. " "Once sufficient information is collected, it should hand off to the WriteAgent." ), system_prompt=( "You are the ResearchAgent. Your goal is to gather sufficient information on the topic. " "Only perform at most 2 distinct searches. If you have enough info or have reached 2 searches, " "handoff to the next agent. Avoid infinite loops!" ), llm=llm, tools=[ safe_duckduckgo_search, # Our DuckDuckGo-based search function record_notes ], can_handoff_to=["WriteAgent"] ) write_agent = FunctionAgent( name="WriteAgent", description=( "Writes a markdown report based on the research notes. " "Then hands off to the ReviewAgent for feedback." ), system_prompt=( "You are the WriteAgent. Draft a structured markdown report based on the notes. " "After writing, hand off to the ReviewAgent." ), llm=llm, tools=[write_report], can_handoff_to=["ReviewAgent", "ResearchAgent"] ) review_agent = FunctionAgent( name="ReviewAgent", description=( "Reviews the final report for correctness. Approves or requests changes." ), system_prompt=( "You are the ReviewAgent. Read the report, provide feedback, and either approve " "or request revisions. If revisions are needed, handoff to WriteAgent." ), llm=llm, tools=[review_report], can_handoff_to=["WriteAgent"] )
############################################################################### # 1. INSTALLATION ############################################################################### # Make sure you have the following installed: # pip install llama-index langchain duckduckgo-search ############################################################################### # 2. IMPORTS ############################################################################### %pip install llama-index langchain duckduckgo-search from llama_index.llms.openai import OpenAI # For DuckDuckGo search via LangChain from langchain.utilities import DuckDuckGoSearchAPIWrapper # llama-index workflow classes from llama_index.core.workflow import Context from llama_index.core.agent.workflow import ( FunctionAgent, AgentWorkflow, AgentInput, AgentOutput, ToolCall, ToolCallResult, AgentStream ) import asyncio ############################################################################### # 3. CREATE LLM ############################################################################### # Replace "sk-..." with your actual OpenAI API key llm = OpenAI(model="gpt-4", api_key="OPENAI_API_KEY")
Setelah aliran kerja selesai, kami mengekstrak keadaan akhir, yang mengandungi laporan yang dihasilkan. Kandungan Laporan dicetak, diikuti dengan sebarang maklum balas ulasan dari ejen semakan. Ini memastikan output selesai dan boleh ditapis lebih lanjut jika perlu.
############################################################################### # 4. DEFINE DUCKDUCKGO SEARCH TOOL WITH SAFEGUARDS ############################################################################### # We wrap LangChain's DuckDuckGoSearchAPIWrapper with our own logic # to prevent repeated or excessive searches. duckduckgo = DuckDuckGoSearchAPIWrapper() MAX_SEARCH_CALLS = 2 search_call_count = 0 past_queries = set() async def safe_duckduckgo_search(query: str) -> str: """ A DuckDuckGo-based search function that: 1) Prevents more than MAX_SEARCH_CALLS total searches. 2) Skips duplicate queries. """ global search_call_count, past_queries # Check for duplicate queries if query in past_queries: return f"Already searched for '{query}'. Avoiding duplicate search." # Check if we've reached the max search calls if search_call_count >= MAX_SEARCH_CALLS: return "Search limit reached, no more searches allowed." # Otherwise, perform the search search_call_count += 1 past_queries.add(query) # DuckDuckGoSearchAPIWrapper.run(...) is synchronous, but we have an async signature result = duckduckgo.run(query) return str(result) ############################################################################### # 5. OTHER TOOL FUNCTIONS: record_notes, write_report, review_report ############################################################################### async def record_notes(ctx: Context, notes: str, notes_title: str) -> str: """Store research notes under a given title in the shared context.""" current_state = await ctx.get("state") if "research_notes" not in current_state: current_state["research_notes"] = {} current_state["research_notes"][notes_title] = notes await ctx.set("state", current_state) return "Notes recorded." async def write_report(ctx: Context, report_content: str) -> str: """Write a report in markdown, storing it in the shared context.""" current_state = await ctx.get("state") current_state["report_content"] = report_content await ctx.set("state", current_state) return "Report written." async def review_report(ctx: Context, review: str) -> str: """Review the report and store feedback in the shared context.""" current_state = await ctx.get("state") current_state["review"] = review await ctx.set("state", current_state) return "Report reviewed."
Mengelakkan gelung carian tak terhingga
Hard Limitwe Set
max_search_calls = 2Penyelidikan
menerima permintaan pengguna untuk menulis laporan ringkas mengenai sejarah Internet. mungkin melakukan sehingga dua carian duckduckgo yang berbeza (mis., "Sejarah Internet" dan "World Wide Web Tim Berners-Lee," dan lain-lain), kemudian memanggil Record_notes untuk menyimpan ringkasan.
membaca "penyelidikan_notes" dari konteks yang dikongsi. draf laporan markdown pendek.
Menilai kandungan. Jika perubahan diperlukan, ia boleh lulus kawalan kembali ke Writeagent. Jika tidak, ia meluluskan laporan.
final_state ["Report_Content"].
Kesimpulandengan memisahkan aliran kerja anda ke dalam agen yang berbeza untuk carian
,kajian , anda boleh membuat sistem yang kuat, modular yang: mengumpulkan maklumat yang relevan (dengan cara yang terkawal, menghalang carian yang berlebihan) menghasilkan output berstruktur, berkualiti tinggi
a. Dalam kod, kami menggunakan kaunter global (search_call_count) dan malar (max_search_calls = 2). Apabila ejen carian memanggil Safe_DuckDuckGo_Search, ia memeriksa sama ada kaunter telah mencapai had. Jika ya, ia mengembalikan mesej dan bukannya melakukan carian lain.
a. Kami mengekalkan set python yang dipanggil Past_queries untuk mengesan pertanyaan berulang. Sekiranya pertanyaan sudah ada dalam set itu, alat itu akan melangkaui carian sebenar dan mengembalikan mesej ringkas, menghalang pertanyaan pendua daripada berjalan.
Q5. Adakah saya memerlukan GPT-4, atau bolehkah saya menggunakan model lain?
Media yang ditunjukkan dalam artikel ini tidak dimiliki oleh Analytics Vidhya dan digunakan pada budi bicara penulis.
Atas ialah kandungan terperinci Aliran Kerja Multi-Agen dengan Llamaindex untuk Penyelidikan & Penulisan. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!