AutoGen debugowanie

⏱ Czas czytania: ~12 minut | 📊 Poziom: Sredniozaawansowany | 📅 Aktualizacja: Grudzien 2025

Debugowanie systemow multi-agent w AutoGen 0.4 moze byc wyzwaniem. Agenci rozmawiaja miedzy soba, wywoluja narzedzia, a bledy moga wystapic w wielu miejscach. Ten praktyczny artykul przedstawia najczestsze pulapki i sprawdzone techniki ich rozwiazywania.

🎯 W tym artykule:
  • Konfiguracja logowania dla AutoGen
  • 10 najczestszych bledow i ich rozwiazania
  • Techniki debugowania konwersacji multi-agent
  • Narzedzia do analizy przeplywu
  • Checklist przed wdrozeniem

Konfiguracja logowania

Pierwszy krok w debugowaniu to wlaczenie szczegolowego logowania. AutoGen 0.4 uzywa standardowego modulu logging Pythona.

Podstawowe logowanie

import logging

# Podstawowa konfiguracja
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# Wycisz zbyt gadatliwe loggery
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("openai").setLevel(logging.WARNING)

Rich logging (czytelniejszy output)

from rich.logging import RichHandler
from rich.console import Console

console = Console()

logging.basicConfig(
    level=logging.DEBUG,
    format="%(message)s",
    handlers=[RichHandler(
        console=console,
        rich_tracebacks=True,
        show_time=True,
        show_path=False
    )]
)

Logowanie do pliku

import logging
from datetime import datetime

# Logger z zapisem do pliku
log_file = f"autogen_debug_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(log_file),
        logging.StreamHandler()  # + konsola
    ]
)

logger = logging.getLogger(__name__)
logger.info(f"Logging to: {log_file}")

10 najczestszych pulapek

❌ #1: Nieskonczona petla konwersacji

Objaw: Agenci rozmawiaja w nieskonczonosc, zuzywajas tokeny i nigdy nie koncza.

# ❌ ZLE: Brak warunku zakonczenia
team = RoundRobinGroupChat(participants=[agent1, agent2])
result = await team.run(task="Discuss AI")  # moze trwac wiecznie!

# ✅ DOBRZE: Dodaj termination_condition
from autogen_agentchat.conditions import (
    MaxMessageTermination,
    TextMentionTermination,
    TokenUsageTermination
)

# Rozne strategie zakonczenia
team = RoundRobinGroupChat(
    participants=[agent1, agent2],
    termination_condition=MaxMessageTermination(max_messages=10)
)

# Lub kombinacja warunkow
from autogen_agentchat.conditions import OrTermination

team = RoundRobinGroupChat(
    participants=[agent1, agent2],
    termination_condition=OrTermination([
        MaxMessageTermination(max_messages=20),
        TextMentionTermination("TASK_COMPLETE"),
        TokenUsageTermination(max_tokens=10000)
    ])
)

❌ #2: Brak async/await

Objaw: RuntimeWarning: coroutine 'X' was never awaited

# ❌ ZLE: Brak await
result = agent.run(task="Hello")
print(result)  # <coroutine object...>

# ✅ DOBRZE: Uzyj await
result = await agent.run(task="Hello")
print(result.messages[-1].content)

# ✅ DOBRZE: Lub asyncio.run() w skryptach
import asyncio

async def main():
    result = await agent.run(task="Hello")
    return result

result = asyncio.run(main())

❌ #3: Stary format llm_config (0.2 vs 0.4)

Objaw: TypeError lub agent nie odpowiada

# ❌ ZLE: AutoGen 0.2 style (nie dziala w 0.4!)
llm_config = {
    "model": "gpt-4",
    "api_key": "sk-...",
    "temperature": 0.7
}
agent = AssistantAgent("assistant", llm_config=llm_config)

# ✅ DOBRZE: AutoGen 0.4 style z model_client
from autogen_ext.models.openai import OpenAIChatCompletionClient

model_client = OpenAIChatCompletionClient(
    model="gpt-4o",
    # api_key pobierany z OPENAI_API_KEY env var
)

agent = AssistantAgent(
    name="assistant",
    model_client=model_client,
    system_message="You are helpful."
)
⚠ Uwaga migracyjna:

AutoGen 0.4 to calkowita przebudowa frameworka. Kod z 0.2 NIE jest kompatybilny. Sprawdz migration guide.

❌ #4: Agenci nie koncza rozmowy

Objaw: Rozmowa trwa do limitu wiadomosci zamiast skonczyc sie naturalnie.

# ❌ ZLE: Agent nie wie kiedy skonczyc
agent = AssistantAgent(
    name="assistant",
    system_message="You are helpful.",
    model_client=model_client
)

# ✅ DOBRZE: Dodaj instrukcje zakonczenia
agent = AssistantAgent(
    name="assistant",
    system_message="""You are a helpful assistant.

IMPORTANT: When the task is fully completed, you MUST end your response 
with the exact phrase: TASK_COMPLETE

Do not say TASK_COMPLETE until you are certain the task is done.""",
    model_client=model_client
)

# + odpowiedni termination_condition
from autogen_agentchat.conditions import TextMentionTermination

team = RoundRobinGroupChat(
    participants=[agent],
    termination_condition=TextMentionTermination("TASK_COMPLETE")
)

❌ #5: Narzedzia nie sa wywolywane

Objaw: Agent opisuje co zrobilby, zamiast uzyc narzedzia.

# ❌ ZLE: Brak lub zly docstring
def search(query):
    return f"Results for {query}"

# ✅ DOBRZE: Pelny docstring z typami i opisami
def search(query: str) -> str:
    """Search the web for information.
    
    Use this tool when you need to find current information 
    about any topic from the internet.
    
    Args:
        query: The search query string. Be specific and concise.
        
    Returns:
        Search results as a formatted string with relevant information.
    """
    return f"Results for {query}"

# Oraz dodaj wyrazna instrukcje w system_message
agent = AssistantAgent(
    name="researcher",
    system_message="""You are a research assistant.
    
You have access to the 'search' tool. 
ALWAYS use the search tool when you need information - never make things up.""",
    model_client=model_client,
    tools=[search]
)

❌ #6: Bledne importy (0.2 vs 0.4)

Objaw: ModuleNotFoundError lub ImportError

# ❌ ZLE: Stare importy z 0.2
from autogen import AssistantAgent, UserProxyAgent

# ✅ DOBRZE: Nowe importy z 0.4
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
from autogen_agentchat.teams import RoundRobinGroupChat, SelectorGroupChat
from autogen_agentchat.conditions import MaxMessageTermination
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.models.anthropic import AnthropicChatCompletionClient

❌ #7: Przekroczenie limitu tokenow

Objaw: InvalidRequestError: context length exceeded

# ✅ Rozwiazanie 1: Limituj historie wiadomosci
from autogen_agentchat.agents import AssistantAgent

agent = AssistantAgent(
    name="assistant",
    model_client=model_client,
    system_message="Be concise.",
    max_consecutive_auto_reply=5  # limituj odpowiedzi
)

# ✅ Rozwiazanie 2: Uzyj modelu z wiekszym kontekstem
model_client = OpenAIChatCompletionClient(
    model="gpt-4o"  # 128K context
)

# ✅ Rozwiazanie 3: Token termination
from autogen_agentchat.conditions import TokenUsageTermination

team = RoundRobinGroupChat(
    participants=[agent1, agent2],
    termination_condition=TokenUsageTermination(max_tokens=50000)
)

❌ #8: Agent nie uzywa wszystkich narzedzi

Objaw: Agent uzywa tylko czesci dostepnych narzedzi.

# ✅ DOBRZE: Opisz narzedzia w system_message
agent = AssistantAgent(
    name="analyst",
    system_message="""You are a data analyst with these tools:

1. **search** - Search the web for information
2. **calculate** - Perform mathematical calculations  
3. **plot** - Create visualizations

For analytical tasks:
- First SEARCH for relevant data
- Then CALCULATE statistics
- Finally PLOT the results

Always use all relevant tools to provide comprehensive analysis.""",
    model_client=model_client,
    tools=[search, calculate, plot]
)

❌ #9: Streaming nie dziala

Objaw: Brak streamingu mimo uzycia run_stream().

# ❌ ZLE: Nieobsluzony stream
stream = team.run_stream(task="Hello")
# nic sie nie dzieje...

# ✅ DOBRZE: Iteruj po streamie
async for message in team.run_stream(task="Hello"):
    if hasattr(message, 'content'):
        print(f"{message.source}: {message.content}")
    elif hasattr(message, 'messages'):
        # TaskResult na koncu
        print("Task complete!")

❌ #10: Blad przy laczeniu z roznymi LLM

Objaw: Problemy z formatowaniem wiadomosci miedzy modelami.

# ✅ Uzyj odpowiednich klientow dla roznych modeli
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.models.anthropic import AnthropicChatCompletionClient

# OpenAI agent
openai_client = OpenAIChatCompletionClient(model="gpt-4o")
agent1 = AssistantAgent(
    name="gpt_agent",
    model_client=openai_client
)

# Anthropic agent
anthropic_client = AnthropicChatCompletionClient(model="claude-sonnet-4-20250514")
agent2 = AssistantAgent(
    name="claude_agent",
    model_client=anthropic_client
)

# Moga wspolpracowac w jednym zespole!
team = RoundRobinGroupChat(participants=[agent1, agent2])

Techniki debugowania konwersacji

Sledzenie przeplywu wiadomosci

async def debug_run(team, task: str):
    """Uruchom zespol z pelnym debugowaniem."""
    print(f"\n{'='*60}")
    print(f"TASK: {task}")
    print(f"{'='*60}\n")
    
    message_count = 0
    
    async for message in team.run_stream(task=task):
        if hasattr(message, 'content'):
            message_count += 1
            print(f"\n[{message_count}] {message.source}:")
            print(f"  Type: {type(message).__name__}")
            print(f"  Content: {message.content[:200]}..." 
                  if len(message.content) > 200 
                  else f"  Content: {message.content}")
            
            # Sprawdz czy sa tool calls
            if hasattr(message, 'tool_calls') and message.tool_calls:
                print(f"  Tools called: {[t.name for t in message.tool_calls]}")
        
        elif hasattr(message, 'messages'):
            # TaskResult
            print(f"\n{'='*60}")
            print(f"COMPLETED: {message_count} messages")
            print(f"Stop reason: {message.stop_reason}")
            return message
    
# Uzycie
result = await debug_run(team, "Analyze this data...")

Eksport historii do JSON

import json
from datetime import datetime

def export_conversation(result, filename: str = None):
    """Eksportuj konwersacje do JSON."""
    if not filename:
        filename = f"conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
    
    messages = []
    for msg in result.messages:
        messages.append({
            "source": msg.source,
            "type": type(msg).__name__,
            "content": msg.content if hasattr(msg, 'content') else str(msg)
        })
    
    with open(filename, 'w') as f:
        json.dump({
            "timestamp": datetime.now().isoformat(),
            "message_count": len(messages),
            "stop_reason": str(result.stop_reason),
            "messages": messages
        }, f, indent=2)
    
    print(f"Exported to: {filename}")

Checklist przed wdrozeniem

✅ Checklist debugowania AutoGen 0.4:
  • Async/await — Czy wszystkie wywolania run() maja await?
  • Termination — Czy jest termination_condition?
  • Model client — Czy uzywasz model_client (nie llm_config)?
  • Importy — Czy importujesz z autogen_agentchat (nie autogen)?
  • Docstrings — Czy narzedzia maja pelne docstrings z typami?
  • System message — Czy zawiera instrukcje uzycia narzedzi i zakonczenia?
  • Logging — Czy logowanie jest wlaczone?
  • Token limits — Czy jest TokenUsageTermination?
  • Error handling — Czy obslugiwane sa wyjatki?
  • Timeout — Czy jest timeout na poziomie aplikacji?
🚨 Red flags – natychmiast sprawdz:
  • Rozmowa trwa > 30 sekund bez odpowiedzi
  • Zuzycie tokenow rosnie bardzo szybko
  • Agent powtarza te same odpowiedzi
  • Narzedzia nigdy nie sa wywolywane

Przydatne komendy diagnostyczne

# Sprawdz wersje
pip show autogen-agentchat autogen-ext

# Sprawdz dostepne modele
python -c "from autogen_ext.models.openai import OpenAIChatCompletionClient; print('OK')"

# Test polaczenia z API
python -c "
from autogen_ext.models.openai import OpenAIChatCompletionClient
import asyncio

async def test():
    client = OpenAIChatCompletionClient(model='gpt-4o-mini')
    # prosty test
    print('Connection OK')

asyncio.run(test())
"

📚 Bibliografia

  1. Microsoft. (2025). AutoGen 0.4 Documentation. microsoft.github.io/autogen
  2. Microsoft. (2025). AutoGen Migration Guide (0.2 to 0.4). microsoft.github.io/autogen/docs/migration-guide
  3. Microsoft. (2025). AutoGen AgentChat Tutorial. microsoft.github.io/autogen/docs/tutorial
  4. Microsoft. (2025). AutoGen GitHub Repository. github.com/microsoft/autogen