-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcapital_agent.py
More file actions
176 lines (145 loc) · 5.53 KB
/
capital_agent.py
File metadata and controls
176 lines (145 loc) · 5.53 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# Copyright (c) Microsoft. All rights reserved.
"""An example of agent using Azure OpenAI with tool calls to look up capital cities.
Running this script directly will run a few sample tasks using the `capital_agent`,
which will test the healthiness of your Azure OpenAI setup.
Remember to have the following environment variables set:
- `AZURE_OPENAI_API_KEY`: Your Azure OpenAI API key.
- `AZURE_OPENAI_ENDPOINT`: Your Azure OpenAI endpoint URL.
"""
import asyncio
import json
import os
from typing import List, TypedDict, cast
import openai
import pandas as pd
from openai.types.chat import (
ChatCompletionMessageFunctionToolCallParam,
ChatCompletionMessageParam,
ChatCompletionToolMessageParam,
ChatCompletionToolParam,
)
from rich.console import Console
from agentlightning import LLM, AgentOpsTracer, InMemoryLightningStore, LitAgentRunner, rollout
CAPITALS = {
"japan": "Tokyo",
"france": "Paris",
"canada": "Ottawa",
"australia": "Canberra",
"brazil": "Brasília",
"egypt": "Cairo",
"kenya": "Nairobi",
"spain": "Madrid",
"italy": "Rome",
"germany": "Berlin",
"south korea": "Seoul",
"india": "New Delhi",
}
console = Console()
def country_capital_lookup(country: str) -> str:
return CAPITALS.get(country.strip().lower(), "Unknown")
class CapitalTask(TypedDict):
input: str
output: str
TOOLS: List[ChatCompletionToolParam] = [
{
"type": "function",
"function": {
"name": "country_capital_lookup",
"description": "Get the capital city of a given country.",
"parameters": {"type": "object", "properties": {"country": {"type": "string"}}, "required": ["country"]},
},
}
]
SYSTEM = (
"You are a concise assistant. "
"If the user asks for a country's capital, ALWAYS call the tool 'country_capital_lookup'. "
"Otherwise, answer briefly."
)
@rollout
def capital_agent(task: CapitalTask, llm: LLM) -> float:
"""Run one evaluation task with capital agent.
Returns 1.0 if output contains expected substring, else 0.0.
"""
console.print("[bold blue]======== Runner Start ========[/bold blue]")
console.print("[bold blue]Runner[/bold blue] [Step 1] Running task with input:", task)
prompt = task["input"]
expected = task["output"]
openai_client = openai.OpenAI(base_url=llm.endpoint, api_key=os.getenv("AZURE_OPENAI_API_KEY", ""))
messages: List[ChatCompletionMessageParam] = [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": prompt},
]
# --- Call #1 ---
first = openai_client.chat.completions.create(
model=llm.model,
messages=messages,
tools=TOOLS,
tool_choice="auto",
temperature=1.0,
)
msg = first.choices[0].message
console.print("[bold blue]Runner[/bold blue] [Step 2] First call response:", msg)
if msg.tool_calls:
assistant_tool_calls: List[ChatCompletionMessageFunctionToolCallParam] = []
tool_results: List[ChatCompletionToolMessageParam] = []
for tc in msg.tool_calls:
if tc.type == "function" and tc.function.name == "country_capital_lookup":
args = json.loads(tc.function.arguments or "{}")
result = country_capital_lookup(args.get("country", ""))
assistant_tool_calls.append(
{
"id": tc.id,
"type": "function",
"function": {
"name": tc.function.name,
"arguments": tc.function.arguments,
},
}
)
tool_results.append(
{
"role": "tool",
"tool_call_id": tc.id,
"content": result,
}
)
messages.append(
{
"role": "assistant",
"content": msg.content or "",
"tool_calls": assistant_tool_calls,
}
)
messages.extend(tool_results)
console.print("[bold blue]Runner[/bold blue] [Step 3] Messages after tool call:", messages)
# --- Call #2 ---
second = openai_client.chat.completions.create(
model=llm.model,
messages=messages,
temperature=1.0,
)
final_text = second.choices[0].message.content or ""
console.print("[bold blue]Runner[/bold blue] [Step 4] Second call response:", final_text)
else:
console.print("[bold blue]Runner[/bold blue] [Step 3] No tool calls made.")
final_text = msg.content or ""
final_text = final_text.strip()
reward = 1.0 if expected.lower() in final_text.lower() else 0.0
console.print(f"[bold blue]Runner[/bold blue] [Step Final] Final output: {final_text} | Reward: {reward}")
return reward
async def main():
# We don't put API key in LLM object for security reasons.
llm = LLM(
endpoint=os.getenv("AZURE_OPENAI_ENDPOINT", ""),
model="gpt-4.1-mini",
)
data = pd.read_csv("capital_samples.csv") # type: ignore
tracer = AgentOpsTracer()
runner = LitAgentRunner[CapitalTask](tracer=tracer)
store = InMemoryLightningStore()
with runner.run_context(agent=capital_agent, store=store):
for index in range(5):
sample = cast(CapitalTask, data.iloc[index].to_dict()) # type: ignore
await runner.step(sample, resources={"main_llm": llm})
if __name__ == "__main__":
asyncio.run(main())