AutoGen Multi-Agent Framework Cheat Blatt
Überblick
AutoGen ist ein bahnbrechendes Open-Source-Framework, das von Microsoft Research entwickelt wurde, das die Entwicklung von Large Language Model (LLM) Anwendungen revolutioniert, indem er anspruchsvolle multiagente Gespräche ermöglicht. Im Gegensatz zu herkömmlichen Single-Agent-Systemen ermöglicht AutoGen Entwicklern, komplexe Anwendungen zu erstellen, indem mehrere spezialisierte KI-Agenten, die miteinander konversieren können, an Aufgaben zusammenarbeiten und sogar Menschen in der Schleife nahtlos einbeziehen.
Was AutoGen besonders mächtig macht, ist sein Schwerpunkt auf Gespräch als primärer Mechanismus für Agenteninteraktion. Dieser Ansatz ermöglicht eine natürliche, flexible und dynamische Zusammenarbeit zwischen Agenten und spiegelt wider, wie menschliche Teams zusammenarbeiten, um komplexe Probleme zu lösen. AutoGen bietet eine reiche Reihe von Werkzeugen zur Definition von Agentenrollen, Fähigkeiten und Kommunikationsprotokollen, so dass es möglich ist, hochanpassungsfähige und intelligente Systeme zu bauen, die eine breite Palette von Aufgaben bewältigen können, von Codegenerierung und Datenanalyse bis hin zu kreativem Schreiben und strategischer Planung.
Der Rahmen ist sowohl für Einfachheit als auch für Erweiterbarkeit ausgelegt und bietet hochrangige Abstraktionen für gemeinsame multiagente Muster und bietet gleichzeitig tiefe Anpassungsmöglichkeiten für fortgeschrittene Anwendungsfälle. Mit seiner ereignisgetriebenen Architektur und Unterstützung für verschiedene LLMs und Tools ermöglicht AutoGen Entwicklern, KI-Anwendungen der nächsten Generation aufzubauen, die leistungsfähiger, robuster und human ausgerichtet sind als je zuvor.
Installation und Inbetriebnahme
Einfache Installation
# Install AutoGen
pip install pyautogen
# Install with specific integrations (e.g., OpenAI)
pip install "pyautogen[openai]"
# Install development version
pip install git+https://github.com/microsoft/autogen.git
# Install with all optional dependencies
pip install "pyautogen[all]"
```_
### Umweltkonfiguration
```python
import os
import autogen
# Configure LLM provider (OpenAI example)
config_list_openai = [
\\\\{
"model": "gpt-4",
"api_key": os.environ.get("OPENAI_API_KEY")
\\\\},
\\\\{
"model": "gpt-3.5-turbo",
"api_key": os.environ.get("OPENAI_API_KEY")
\\\\}
]
# Configure for other LLMs (e.g., Azure OpenAI, local models)
# See AutoGen documentation for specific configurations
# Set up logging
autogen.ChatCompletion.set_cache(seed=42) # For reproducibility
```_
### Projektstruktur
autogen_project/ ├── agents/ │ ├── init.py │ ├── researcher_agent.py │ └── coder_agent.py ├── workflows/ │ ├── init.py │ ├── coding_workflow.py │ └── research_workflow.py ├── tools/ │ ├── init.py │ └── custom_tools.py ├── skills/ │ ├── init.py │ └── code_execution_skill.py ├── config/ │ ├── init.py │ └── llm_config.py └── main.py ```_
Kernkonzepte
Agenten
Agenten sind die grundlegenden Bausteine in AutoGen. Sie sind Konversationseinheiten, die Nachrichten senden und empfangen können, Code ausführen, Call-Funktionen und interagieren mit Menschen.
Konversibel Agent
Dies ist die Basisklasse für die meisten Agenten in AutoGen, bietet Kernkonversationsfunktionen.
UserProxyAgent
Ein spezialisierter Agent, der als Proxy für menschliche Benutzer fungiert, so dass sie an Gesprächen teilnehmen, Eingabe und Code ausführen.
Assistentin
Ein Agent, der als KI-Assistent fungiert, typischerweise von einem LLM betrieben, in der Lage, Code zu schreiben, Fragen zu beantworten und Aufgaben zu erfüllen.
GruppeChat
AutoGen unterstützt multiagente Gespräche durch GroupChat und GroupChatManager und ermöglicht komplexe Interaktionen zwischen mehreren Agenten.
Agent Configuration
Grundlegende Agentenerstellung
```python import autogen
Assistant Agent (LLM-powered)
assistant = autogen.AssistantAgent( name="Assistant", llm_config=\\{ "config_list": config_list_openai, "temperature": 0.7, "timeout": 600 \\}, system_message="You are a helpful AI assistant. Provide concise and accurate answers." )
User Proxy Agent (Human in the loop)
user_proxy = autogen.UserProxyAgent( name="UserProxy", human_input_mode="TERMINATE", # Options: ALWAYS, TERMINATE, NEVER max_consecutive_auto_reply=10, is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"), code_execution_config=\\{ "work_dir": "coding_output", "use_docker": False # Set to True to use Docker for code execution \\}, system_message="A human user. Reply TERMINATE when the task is done or if you want to stop." ) ```_
Erweiterter Agent Anpassung
```python import autogen
Agent with custom reply function
def custom_reply_func(messages, sender, config): last_message = messages[-1]["content"] if "hello" in last_message.lower(): return "Hello there! How can I help you today?" return "I received your message."
custom_agent = autogen.ConversableAgent( name="CustomAgent", llm_config=False, # No LLM for this agent reply_func_list=[custom_reply_func] )
Agent with specific skills (function calling)
@autogen.register_function( name="get_stock_price", description="Get the current stock price for a given symbol.", parameters=\\{"symbol": \\{"type": "string", "description": "Stock symbol"\\}\\} ) def get_stock_price(symbol: str) -> str: # Implement stock price retrieval logic return f"The price of \\{symbol\\} is $150."
stock_analyst_agent = autogen.AssistantAgent( name="StockAnalyst", llm_config=\\{ "config_list": config_list_openai, "functions": [autogen.AssistantAgent.construct_function_description(get_stock_price)] \\}, function_map=\\{"get_stock_price": get_stock_price\\} ) ```_
Spezialisierte Agententypen
```python import autogen
TeachableAgent for learning from feedback
teachable_agent = autogen.TeachableAgent( name="TeachableAnalyst", llm_config=\\{"config_list": config_list_openai\\}, teach_config=\\{ "verbosity": 0, # 0 for no teaching, 1 for normal, 2 for detailed "reset_db": False, # Set to True to clear previous learnings "path_to_db_dir": "./teachable_agent_db" \\} )
RetrieveUserProxyAgent for RAG (Retrieval Augmented Generation)
rag_agent = autogen.retrieve_chat.RetrieveUserProxyAgent( name="RAGAgent", human_input_mode="TERMINATE", retrieve_config=\\{ "task": "qa", "docs_path": "./documents_for_rag", "chunk_token_size": 2000, "model": config_list_openai[0]["model"], "collection_name": "rag_collection", "get_or_create": True \\} ) ```_
Ansprechpartner
Zwei Agenten Chat
```python import autogen
Initiate chat between user_proxy and assistant
user_proxy.initiate_chat( assistant, message="What is the capital of France?", summary_method="reflection_with_llm", # For summarizing conversation history max_turns=5 )
Example with code execution
user_proxy.initiate_chat( assistant, message="Write a Python script to print numbers from 1 to 5 and run it." ) ```_
Gruppen Chat mit mehreren Agenten
```python import autogen
Define agents for group chat
planner = autogen.AssistantAgent( name="Planner", llm_config=\\{"config_list": config_list_openai\\}, system_message="You are a project planner. Create detailed plans for tasks." )
engineer = autogen.AssistantAgent( name="Engineer", llm_config=\\{"config_list": config_list_openai\\}, system_message="You are a software engineer. Implement the plans provided." )
reviewer = autogen.AssistantAgent( name="Reviewer", llm_config=\\{"config_list": config_list_openai\\}, system_message="You are a code reviewer. Review the implemented code for quality." )
Create group chat and manager
group_chat = autogen.GroupChat( agents=[user_proxy, planner, engineer, reviewer], messages=[], max_round=12, speaker_selection_method="auto" # auto, round_robin, random, manual )
manager = autogen.GroupChatManager( groupchat=group_chat, llm_config=\\{"config_list": config_list_openai\\} )
Initiate group chat
user_proxy.initiate_chat( manager, message="Develop a Python script to calculate Fibonacci numbers up to n." ) ```_
Erweiterte Konversationssteuerung
```python import autogen
Custom speaker selection
def custom_speaker_selector(last_speaker, groupchat): if last_speaker is user_proxy: return planner elif last_speaker is planner: return engineer elif last_speaker is engineer: return reviewer else: return user_proxy
custom_group_chat = autogen.GroupChat( agents=[user_proxy, planner, engineer, reviewer], messages=[], speaker_selection_method=custom_speaker_selector )
Nested chats
def initiate_nested_chat(recipient, message): user_proxy.initiate_chat(recipient, message=message, clear_history=False)
Example of agent calling nested chat
class MainAgent(autogen.AssistantAgent): def generate_reply(self, messages, sender, **kwargs): # ... logic ... if needs_specialized_help: initiate_nested_chat(specialist_agent, "Need help with this sub-task.") # ... process specialist_agent response ... return "Main task processed." ```_
Werkzeug- und Funktionsintegration
Mit integrierten Tools
AutoGen hat nicht eine große Reihe von vorgefertigten Werkzeugen wie einige andere Frameworks. Stattdessen konzentriert es sich auf die Freigabe von Agenten, um Code (Python-Skripte, Shell-Befehle) auszuführen, die dann mit jeder Bibliothek oder Werkzeug in der Ausführungsumgebung interagieren können.
Custom Function Calling (Skills)
```python import autogen
Define a function (skill)
@autogen.register_function def get_weather(location: str) -> str: """Get the current weather for a given location.""" # Replace with actual API call if location == "London": return "Weather in London is 15°C and cloudy." elif location == "Paris": return "Weather in Paris is 18°C and sunny." else: return f"Weather data not available for \\{location\\}."
Agent that can use the function
weather_assistant = autogen.AssistantAgent( name="WeatherAssistant", llm_config=\\{ "config_list": config_list_openai, "functions": [autogen.AssistantAgent.construct_function_description(get_weather)] \\}, function_map=\\{"get_weather": get_weather\\} )
User proxy to trigger function call
user_proxy.initiate_chat( weather_assistant, message="What is the weather in London?" ) ```_
Code Ausführung
```python import autogen
UserProxyAgent is configured for code execution by default
Ensure code_execution_config
is set appropriately
Example: Agent asks UserProxyAgent to execute code
coder_agent = autogen.AssistantAgent( name="Coder", llm_config=\\{"config_list": config_list_openai\\} )
user_proxy.initiate_chat( coder_agent, message="Write a Python script that creates a file named 'test.txt' with content 'Hello AutoGen!' and then execute it." )
UserProxyAgent will prompt for confirmation before executing the code.
```_
Mensch-in-the-Loop (HIL)
Menschliche Eingabe konfigurieren
```python import autogen
UserProxyAgent configured for human input
hil_user_proxy = autogen.UserProxyAgent( name="HumanReviewer", human_input_mode="ALWAYS", # ALWAYS: Human input required for every message # TERMINATE: Human input required if no auto-reply, or to terminate # NEVER: No human input (fully autonomous) is_termination_msg=lambda x: x.get("content", "").rstrip() == "APPROVE" )
Example workflow with human review
planner = autogen.AssistantAgent(name="Planner", llm_config=llm_config) executor = autogen.AssistantAgent(name="Executor", llm_config=llm_config)
groupchat_with_review = autogen.GroupChat( agents=[hil_user_proxy, planner, executor], messages=[], max_round=10 ) manager_with_review = autogen.GroupChatManager( groupchat=groupchat_with_review, llm_config=llm_config )
hil_user_proxy.initiate_chat( manager_with_review, message="Plan and execute a task to summarize a long document. I will review the plan and the final summary." ) ```_
Asynchrone menschliche Eingabe
AutoGen behandelt hauptsächlich HIL synchron innerhalb des Gesprächsflusses. Für komplexere asynchrone HIL würden Sie typischerweise mit externen Task-Management- oder UI-Systemen integrieren.
Erweiterte Funktionen
Lehrmittel
```python import autogen
Setup TeachableAgent
teachable_coder = autogen.TeachableAgent( name="TeachableCoder", llm_config=\\{"config_list": config_list_openai\\}, teach_config=\\{ "verbosity": 1, "reset_db": False, "path_to_db_dir": "./teachable_coder_db", "recall_threshold": 1.5, # Higher value means less recall \\} )
User teaches the agent
user_proxy.initiate_chat( teachable_coder, message="When I ask for a quick sort algorithm, always implement it in Python using a recursive approach." )
Later, the agent uses the learned information
user_proxy.initiate_chat( teachable_coder, message="Implement a quick sort algorithm." )
To clear learnings:
teachable_coder.clear_mem L() # For in-memory (if not using DB)
Or set teach_config["reset_db"] = True and re-initialize
```_
Retrieval Augmented Generation (RAG)
```python import autogen from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent
Ensure you have a directory with documents (e.g., ./my_documents)
Supported formats: .txt, .md, .pdf, .html, .htm, .json, .jsonl, .csv, .tsv, .xls, .xlsx, .doc, .docx, .ppt, .pptx, .odt, .rtf, .epub
Create a RetrieveAssistantAgent (combines LLM with retrieval)
retrieval_assistant = RetrieveAssistantAgent( name="RetrievalAssistant", system_message="You are a helpful assistant that answers questions based on provided documents.", llm_config=\\{"config_list": config_list_openai\\} )
Create a RetrieveUserProxyAgent to handle document processing and querying
rag_user_proxy = autogen.retrieve_chat.RetrieveUserProxyAgent( name="RAGUserProxy", human_input_mode="TERMINATE", max_consecutive_auto_reply=5, retrieve_config=\\{ "task": "qa", # Can be "qa", "code", "chat" "docs_path": "./my_documents", # Path to your documents "chunk_token_size": 2000, "model": config_list_openai[0]["model"], "collection_name": "my_rag_collection", "get_or_create": True, # Creates collection if it doesn_t exist "embedding_model": "all-mpnet-base-v2" # Example sentence transformer model \\}, code_execution_config=False )
Initiate RAG chat
The RAGUserProxy will first try to answer from documents, then pass to RetrievalAssistant if needed.
rag_user_proxy.initiate_chat( retrieval_assistant, problem="What are the main features of AutoGen according to the documents?" )
To update or add new documents, you might need to re-index or manage the collection.
rag_user_proxy.retrieve_config["update_context"] = True (for some RAG setups)
```_
Multi-Modal Konversationen
AutoGen unterstützt multimodale Eingaben (z.B. Bilder), wenn die zugrunde liegende LLM sie unterstützt (wie GPT-4V). ```python import autogen
Ensure your config_list points to a multimodal LLM (e.g., gpt-4-vision-preview)
multimodal_config_list = [ \\{ "model": "gpt-4-vision-preview", "api_key": os.environ.get("OPENAI_API_KEY") \\} ]
multimodal_agent = autogen.AssistantAgent( name="MultimodalAgent", llm_config=\\{"config_list": multimodal_config_list\\} )
Example message with an image URL
user_proxy.initiate_chat( multimodal_agent, message=[ \\{"type": "text", "text": "What is in this image?"\\}, \\{"type": "image_url", "image_url": \\{"url": "https://example.com/image.jpg"\\}\\} ] )
Example with local image (requires proper handling to make it accessible to the LLM)
This might involve uploading the image or using a local multimodal LLM setup.
For local images with OpenAI, you typically need to base64 encode them.
import base64
def image_to_base64(image_path): with open(image_path, "rb") as img_file: return base64.b64encode(img_file.read()).decode("utf-8")
local_image_path = "./path_to_your_image.png" base64_image = image_to_base64(local_image_path)
user_proxy.initiate_chat( multimodal_agent, message=[ \\{"type": "text", "text": "Describe this local image:"\\}, \\{"type": "image_url", "image_url": \\{"url": f"data:image/png;base64,\\{base64_image\\}"\\}\\} ] ) ```_
Agent Workflow Muster
Reflexion und Selbstdarstellung
```python import autogen
Agent that reflects on its own output
self_reflecting_agent = autogen.AssistantAgent( name="Reflector", llm_config=\\{"config_list": config_list_openai\\}, system_message="You are an AI that writes code. After writing code, reflect on its quality and correctness. If you find issues, try to correct them." )
User proxy to facilitate reflection
reflection_user_proxy = autogen.UserProxyAgent( name="ReflectionProxy", human_input_mode="NEVER", max_consecutive_auto_reply=3, # Allow a few turns for reflection # Custom message to trigger reflection or provide feedback # This often involves a more complex setup where the proxy or another agent critiques the output. )
This pattern is often implemented with a sequence of chats or a GroupChat
where one agent produces work and another critiques it, then the first agent revises.
Simplified example:
user_proxy.initiate_chat( self_reflecting_agent, message="Write a Python function to calculate factorial. Then, review your code for potential bugs or improvements and provide a revised version if necessary." ) ```_
Hierarchische Agententeams
Dies wird typischerweise mit GroupChatManager erreicht, wo ein Agent (z.B. ein Manager oder Planer) andere spezialisierte Agenten koordiniert. ```python import autogen
Manager Agent
manager_agent = autogen.AssistantAgent( name="Manager", llm_config=\\{"config_list": config_list_openai\\}, system_message="You are a project manager. Delegate tasks to your team (Engineer, Researcher) and synthesize their results." )
Specialist Agents
engineer_agent = autogen.AssistantAgent(name="Engineer", llm_config=llm_config) researcher_agent = autogen.AssistantAgent(name="Researcher", llm_config=llm_config)
Group Chat for the team
team_groupchat = autogen.GroupChat( agents=[user_proxy, manager_agent, engineer_agent, researcher_agent], messages=[], max_round=15, # Manager agent can be set to speak or select next speaker speaker_selection_method=lambda last_speaker, groupchat: manager_agent if last_speaker != manager_agent else user_proxy # Simplified example )
team_manager = autogen.GroupChatManager( groupchat=team_groupchat, llm_config=llm_config )
user_proxy.initiate_chat( team_manager, message="Develop a new feature for our app that requires research on user needs and then engineering implementation." ) ```_
Best Practices
Agent Design
- Clear Roles: Definieren Sie spezifische, eindeutige Rollen und Verantwortlichkeiten für jeden Agenten.
- *Systemnachrichten: Verwenden Sie detaillierte Systemnachrichten, um Agentverhalten und persona zu führen.
- Tool Access: Agenten nur mit den Werkzeugen, die sie für ihre Rolle benötigen.
- *LLM Konfiguration: Maßgeschneiderte LLM-Temperatur, Modell und andere Einstellungen pro Agent für optimale Leistung.
Konversationsmanagement
- *Terminationsbedingungen: Deutlich definieren, wann ein Gespräch oder eine Aufgabe abgeschlossen ist.
- *Max Turns/Rounds: Grenzen setzen, um unendliche Schleifen oder übermäßige Kosten zu verhindern.
- ** Sprachauswahl**: Wählen Sie geeignete Auswahlmethoden für Gruppenchats (auto, round_robin, custom).
- Summarisierung: Verwenden Sie Konversationszusammenfassung für langlaufende Chats, um Kontextfenster zu verwalten.
Code Execution Security
- *Sandboxing: Verwenden Sie Docker (
use_docker=True
incode_execution_config
) für eine sicherere Codeausführung, insbesondere mit nicht vertrauenswürdigem Code. - *Human Review: Implementieren Sie die menschliche Bewertung (
human_input_mode="ALWAYS"
oder"TERMINATE"
) bevor Sie potenziell riskanten Code ausführen. - *Einschränkte Umwelt: Wenn Sie Docker nicht verwenden, stellen Sie sicher, dass die Ausführung Umgebung begrenzte Berechtigungen hat.
Kostenmanagement
- Auswahl: Verwenden Sie weniger teure Modelle (z.B. GPT-3.5-turbo) für einfachere Aufgaben oder Agenten.
- *Max Tokens/Turns: Beschränken Sie die Länge der Gespräche und LLM Ausgänge.
- Caching: Verwenden Sie
autogen.ChatCompletion.set_cache()
, um LLM-Antworten zu speichern und redundante Anrufe zu reduzieren. - Monitoring: Verfolgen Sie Token-Nutzung und API-Kosten eng.
Debugging
- *Verbose Logging: AutoGen bietet Protokollierung; erhöhen Verbenheit für Debugging.
- *Step-by-Step Execution: Für komplexe Gruppenchats sollten Sie manuelle Lautsprecherauswahl oder Breakpoints beachten, um Flow zu verstehen.
- ** Agent Isolation**: Testmittel einzeln vor der Integration in größere Gruppen.
Fehlerbehebung
Gemeinsame Themen
Agenten Stuck in Loops
- Cause: Vague Kündigungsbedingungen, widersprüchliche Agentenziele oder übermäßig komplexe Interaktionen.
- Solution: Refine
is_termination_msg
Lambda, vereinfacht Agentenanleitungen, eingestellt __CODE_BLOCK_23_ odermax_round
_
Unerwartete Agent Behavior
- Cause: Deutliche Systemnachrichten, LLM-Fehlerinterpretationen oder falsche LLM-Konfigurationen.
- Solution: Systemnachrichten genauer machen, mit unterschiedlichen LLM-Temperaturen experimentieren, korrekte Funktion/Werkzeugbeschreibungen sicherstellen.
Code Ausführungsfehler
- Cause: Fehlende Abhängigkeiten in der Ausführungsumgebung, falscher Code, der von LLM generiert wird, Berechtigungsprobleme.
- Solution: Stellen Sie sicher, dass alle notwendigen Pakete installiert sind (oder verwenden Sie Docker), verbessern Sie die Eingabeaufforderungen für die Codegenerierung, überprüfen Sie die Datei/Netzwerkberechtigungen.
Funktion Calling Probleme
- Cause: Falsche Funktionsbeschreibungen für LLM, Fehler im benutzerdefinierten Funktionscode, LLM scheitert, gültige JSON für Argumente zu generieren.
- Solution: Stellen Sie sicher, dass Funktionsbeschreibungen klar und übereinstimmen, testen Sie benutzerdefinierte Funktionen gründlich, verfeinern Sie Eingabeaufforderungen, um LLM auf korrektes JSON-Format zu führen.
--
*Dieses AutoGen-Betrug-Blatt bietet einen umfassenden Leitfaden für den Aufbau anspruchsvoller multiagent AI-Anwendungen. Durch die Nutzung von AutoGen_s Konversationsrahmen können Entwickler hochfähige und kollaborative KI-Systeme erstellen. Denken Sie daran, die offizielle AutoGen Dokumentation für die neuesten Funktionen und detaillierte API Referenzen zu konsultieren. *