-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautogen_basic.py
More file actions
57 lines (43 loc) · 1.84 KB
/
Copy pathautogen_basic.py
File metadata and controls
57 lines (43 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""Enforce an AutoGen ``BaseChatAgent.on_messages`` run with @protect.
AutoGen ships its own LLM client (``OpenAIChatCompletionClient``)
which may or may not route through httpx depending on the version
and the chat model. ``nullrun`` patches ``BaseChatAgent.on_messages``
so the agent lifecycle itself is tracked regardless of which LLM
client is underneath, and also wraps the OpenAI-compat client's
``create`` method for streaming-safe token capture.
``@protect`` adds the *gate* layer (budget / kill / pause);
``@guarded`` translates any ``NullRunError`` into a friendly exit.
Run:
pip install "nullrun[autogen]" autogen-agentchat autogen-ext
export NULLRUN_API_KEY=nr_live_...
export OPENAI_API_KEY=sk-...
python examples/autogen_basic.py
"""
from __future__ import annotations
from _env import load_env
load_env() # populate os.environ from examples/.env (no-op if absent)
import asyncio
import os
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
from nullrun import guarded, init_or_die, protect, shutdown
init_or_die() # reads NULLRUN_API_KEY from os.environ; friendly exit if missing
@guarded
@protect
def run_agent(prompt: str) -> str:
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
agent = AssistantAgent(
name="assistant",
model_client=model_client,
system_message="You are a concise assistant. Answer in one sentence.",
)
result = asyncio.run(agent.run(task=prompt))
# AutoGen returns a TaskResult whose messages list contains the
# final TextMessage from the agent.
last = result.messages[-1]
return last.content if isinstance(last.content, str) else str(last.content)
if __name__ == "__main__":
try:
print(run_agent("What is the capital of France?"))
finally:
shutdown()