agent-eval-gate 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_eval/__init__.py +3 -0
- agent_eval/agents/__init__.py +79 -0
- agent_eval/agents/anthropic_agent.py +186 -0
- agent_eval/agents/http_agent.py +53 -0
- agent_eval/agents/openai_agent.py +137 -0
- agent_eval/agents/python_agent.py +37 -0
- agent_eval/checks.py +207 -0
- agent_eval/cli.py +120 -0
- agent_eval/judge.py +182 -0
- agent_eval/loader.py +94 -0
- agent_eval/matching.py +70 -0
- agent_eval/models.py +174 -0
- agent_eval/pricing.py +56 -0
- agent_eval/pricing.yaml +7 -0
- agent_eval/py.typed +0 -0
- agent_eval/report.py +183 -0
- agent_eval/runner.py +247 -0
- agent_eval/toolbox.py +92 -0
- agent_eval/tracing.py +38 -0
- agent_eval_gate-0.2.0.dist-info/METADATA +215 -0
- agent_eval_gate-0.2.0.dist-info/RECORD +24 -0
- agent_eval_gate-0.2.0.dist-info/WHEEL +4 -0
- agent_eval_gate-0.2.0.dist-info/entry_points.txt +2 -0
- agent_eval_gate-0.2.0.dist-info/licenses/LICENSE +21 -0
agent_eval/__init__.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Agent adapters. Every adapter turns (user input, mock toolbox) into a Trajectory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Literal, Protocol
|
|
7
|
+
|
|
8
|
+
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
|
9
|
+
|
|
10
|
+
from agent_eval.models import Trajectory
|
|
11
|
+
from agent_eval.toolbox import Toolbox
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Agent(Protocol):
|
|
15
|
+
name: str
|
|
16
|
+
model: str
|
|
17
|
+
|
|
18
|
+
def run(self, user_input: str, toolbox: Toolbox) -> Trajectory: ...
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AgentConfig(BaseModel):
|
|
22
|
+
"""Agent under test, loaded from YAML (see examples/support-agent/agents/)."""
|
|
23
|
+
|
|
24
|
+
model_config = ConfigDict(extra="forbid")
|
|
25
|
+
|
|
26
|
+
name: str
|
|
27
|
+
provider: Literal["anthropic", "openai", "python", "http"]
|
|
28
|
+
model: str = ""
|
|
29
|
+
system_prompt: str = ""
|
|
30
|
+
system_prompt_file: str | None = None # relative to the config file; read at load time
|
|
31
|
+
max_steps: int = Field(default=10, ge=1)
|
|
32
|
+
max_tokens: int = Field(default=16_000, ge=1)
|
|
33
|
+
|
|
34
|
+
# provider: anthropic (Claude on the Claude API, Amazon Bedrock or Vertex AI)
|
|
35
|
+
platform: Literal["anthropic", "bedrock", "vertex"] = "anthropic"
|
|
36
|
+
effort: Literal["low", "medium", "high", "xhigh", "max"] | None = "high"
|
|
37
|
+
refusal_fallback: bool = True
|
|
38
|
+
aws_region: str | None = None
|
|
39
|
+
gcp_project: str | None = None
|
|
40
|
+
gcp_region: str = "global"
|
|
41
|
+
|
|
42
|
+
# provider: openai (OpenAI, Azure OpenAI, Vertex AI and vLLM OpenAI-compatible APIs)
|
|
43
|
+
base_url: str | None = None
|
|
44
|
+
api_key_env: str = "OPENAI_API_KEY"
|
|
45
|
+
|
|
46
|
+
# provider: python ("path/to/file.py:ClassName", relative to the config file)
|
|
47
|
+
entrypoint: str | None = None
|
|
48
|
+
|
|
49
|
+
# provider: http (black-box agent service that returns its own trajectory)
|
|
50
|
+
endpoint: str | None = None
|
|
51
|
+
headers: dict[str, str] = Field(default_factory=dict)
|
|
52
|
+
timeout_s: float = Field(default=120.0, gt=0)
|
|
53
|
+
|
|
54
|
+
source_dir: Path = Field(default=Path(), exclude=True)
|
|
55
|
+
|
|
56
|
+
@field_validator("endpoint", "base_url")
|
|
57
|
+
@classmethod
|
|
58
|
+
def _http_only(cls, value: str | None) -> str | None:
|
|
59
|
+
if value is not None and not value.startswith(("https://", "http://")):
|
|
60
|
+
raise ValueError("must be an http(s) URL")
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def build_agent(config: AgentConfig) -> Agent:
|
|
65
|
+
if config.provider == "anthropic":
|
|
66
|
+
from agent_eval.agents.anthropic_agent import AnthropicAgent
|
|
67
|
+
|
|
68
|
+
return AnthropicAgent(config)
|
|
69
|
+
if config.provider == "openai":
|
|
70
|
+
from agent_eval.agents.openai_agent import OpenAICompatibleAgent
|
|
71
|
+
|
|
72
|
+
return OpenAICompatibleAgent(config)
|
|
73
|
+
if config.provider == "http":
|
|
74
|
+
from agent_eval.agents.http_agent import HttpAgent
|
|
75
|
+
|
|
76
|
+
return HttpAgent(config)
|
|
77
|
+
from agent_eval.agents.python_agent import load_python_agent
|
|
78
|
+
|
|
79
|
+
return load_python_agent(config)
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Claude tool-use loop on the Claude API, Amazon Bedrock or Vertex AI (Anthropic SDK).
|
|
2
|
+
|
|
3
|
+
A manual loop rather than the SDK's tool runner, because the harness must intercept
|
|
4
|
+
every tool call (answer it from the scenario's mocks and record it) and enforce a step
|
|
5
|
+
limit.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import anthropic
|
|
15
|
+
|
|
16
|
+
from agent_eval import tracing
|
|
17
|
+
from agent_eval.agents import AgentConfig
|
|
18
|
+
from agent_eval.models import Trajectory, Usage
|
|
19
|
+
from agent_eval.toolbox import Toolbox
|
|
20
|
+
|
|
21
|
+
FALLBACK_BETA = "server-side-fallback-2026-07-01"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def make_client(config: AgentConfig) -> Any:
|
|
25
|
+
"""Use each platform's dedicated client class; credentials come from the environment
|
|
26
|
+
(Claude API key or profile, AWS credential chain, Google ADC)."""
|
|
27
|
+
if config.platform == "bedrock":
|
|
28
|
+
region = config.aws_region or os.environ.get("AWS_REGION")
|
|
29
|
+
if not region:
|
|
30
|
+
raise ValueError("platform bedrock needs aws_region (or AWS_REGION)")
|
|
31
|
+
return anthropic.AnthropicBedrockMantle(aws_region=region)
|
|
32
|
+
if config.platform == "vertex":
|
|
33
|
+
project = config.gcp_project or os.environ.get("GOOGLE_CLOUD_PROJECT")
|
|
34
|
+
if not project:
|
|
35
|
+
raise ValueError("platform vertex needs gcp_project (or GOOGLE_CLOUD_PROJECT)")
|
|
36
|
+
return anthropic.AnthropicVertex(project_id=project, region=config.gcp_region)
|
|
37
|
+
return anthropic.Anthropic(max_retries=4)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def echoable_content(content: list[Any]) -> list[Any]:
|
|
41
|
+
"""The assistant turn to send back on the next request.
|
|
42
|
+
|
|
43
|
+
After a mid-output refusal fallback, model-internal blocks (thinking, tool use)
|
|
44
|
+
that precede the final ``fallback`` block are omitted; text before it is kept,
|
|
45
|
+
the fallback block stays where it appeared, and everything after echoes unchanged.
|
|
46
|
+
"""
|
|
47
|
+
boundary = max((i for i, block in enumerate(content) if block.type == "fallback"), default=-1)
|
|
48
|
+
if boundary <= 0:
|
|
49
|
+
return list(content)
|
|
50
|
+
kept_before = [block for block in content[:boundary] if block.type == "text"]
|
|
51
|
+
return [*kept_before, *content[boundary:]]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _usage(raw: Any) -> Usage:
|
|
55
|
+
return Usage(
|
|
56
|
+
input_tokens=raw.input_tokens or 0,
|
|
57
|
+
output_tokens=raw.output_tokens or 0,
|
|
58
|
+
cache_read_input_tokens=raw.cache_read_input_tokens or 0,
|
|
59
|
+
cache_creation_input_tokens=raw.cache_creation_input_tokens or 0,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class AnthropicAgent:
|
|
64
|
+
def __init__(self, config: AgentConfig, client: Any | None = None) -> None:
|
|
65
|
+
if not config.model:
|
|
66
|
+
raise ValueError("provider anthropic needs a model (e.g. claude-opus-5-5)")
|
|
67
|
+
self.name = config.name
|
|
68
|
+
self.model = config.model
|
|
69
|
+
self._config = config
|
|
70
|
+
self._client = client if client is not None else make_client(config)
|
|
71
|
+
# Server-side refusal fallbacks exist on the Claude API only. Runs served by a
|
|
72
|
+
# fallback model are flagged in the results, so they are never silently scored
|
|
73
|
+
# as the model under test.
|
|
74
|
+
self._fallback = config.refusal_fallback and config.platform == "anthropic"
|
|
75
|
+
|
|
76
|
+
def _tools(self, toolbox: Toolbox) -> list[dict[str, Any]]:
|
|
77
|
+
tools = []
|
|
78
|
+
for spec in toolbox.specs:
|
|
79
|
+
tool: dict[str, Any] = {
|
|
80
|
+
"name": spec.name,
|
|
81
|
+
"description": spec.description,
|
|
82
|
+
"input_schema": spec.input_schema,
|
|
83
|
+
}
|
|
84
|
+
if spec.input_schema.get("additionalProperties") is False:
|
|
85
|
+
tool["strict"] = True # schema-valid arguments guaranteed
|
|
86
|
+
tools.append(tool)
|
|
87
|
+
return tools
|
|
88
|
+
|
|
89
|
+
def _create(self, messages: list[dict[str, Any]], tools: list[dict[str, Any]]) -> Any:
|
|
90
|
+
cfg = self._config
|
|
91
|
+
kwargs: dict[str, Any] = {
|
|
92
|
+
"model": self.model,
|
|
93
|
+
"max_tokens": cfg.max_tokens,
|
|
94
|
+
"messages": messages,
|
|
95
|
+
"tools": tools,
|
|
96
|
+
}
|
|
97
|
+
if cfg.system_prompt:
|
|
98
|
+
kwargs["system"] = cfg.system_prompt
|
|
99
|
+
if cfg.effort:
|
|
100
|
+
kwargs["output_config"] = {"effort": cfg.effort}
|
|
101
|
+
if self._fallback:
|
|
102
|
+
kwargs["betas"] = [FALLBACK_BETA]
|
|
103
|
+
kwargs["fallbacks"] = "default"
|
|
104
|
+
return self._client.beta.messages.create(**kwargs)
|
|
105
|
+
|
|
106
|
+
def run(self, user_input: str, toolbox: Toolbox) -> Trajectory:
|
|
107
|
+
messages: list[dict[str, Any]] = [{"role": "user", "content": user_input}]
|
|
108
|
+
tools = self._tools(toolbox)
|
|
109
|
+
usage = Usage()
|
|
110
|
+
model, output, stop_reason, refusal = self.model, "", None, None
|
|
111
|
+
served_by_fallback = False
|
|
112
|
+
steps = 0
|
|
113
|
+
while steps < self._config.max_steps:
|
|
114
|
+
steps += 1
|
|
115
|
+
attributes = {
|
|
116
|
+
"gen_ai.operation.name": "chat",
|
|
117
|
+
"gen_ai.provider.name": "anthropic",
|
|
118
|
+
"gen_ai.request.model": self.model,
|
|
119
|
+
}
|
|
120
|
+
with tracing.span(f"chat {self.model}", attributes) as span:
|
|
121
|
+
try:
|
|
122
|
+
response = self._create(messages, tools)
|
|
123
|
+
except anthropic.RateLimitError as exc:
|
|
124
|
+
return Trajectory(
|
|
125
|
+
model=model, steps=steps, usage=usage, error=f"rate limited: {exc.message}"
|
|
126
|
+
)
|
|
127
|
+
except anthropic.APIStatusError as exc:
|
|
128
|
+
return Trajectory(
|
|
129
|
+
model=model,
|
|
130
|
+
steps=steps,
|
|
131
|
+
usage=usage,
|
|
132
|
+
error=f"API error {exc.status_code}: {exc.message}",
|
|
133
|
+
)
|
|
134
|
+
except anthropic.APIConnectionError as exc:
|
|
135
|
+
return Trajectory(
|
|
136
|
+
model=model, steps=steps, usage=usage, error=f"connection error: {exc}"
|
|
137
|
+
)
|
|
138
|
+
step_usage = _usage(response.usage)
|
|
139
|
+
span.set_attribute("gen_ai.response.model", response.model)
|
|
140
|
+
span.set_attribute("gen_ai.usage.input_tokens", step_usage.input_tokens)
|
|
141
|
+
span.set_attribute("gen_ai.usage.output_tokens", step_usage.output_tokens)
|
|
142
|
+
|
|
143
|
+
usage += step_usage
|
|
144
|
+
model = response.model
|
|
145
|
+
stop_reason = response.stop_reason
|
|
146
|
+
served_by_fallback = served_by_fallback or any(
|
|
147
|
+
getattr(item, "type", None) == "fallback_message"
|
|
148
|
+
for item in (response.usage.iterations or [])
|
|
149
|
+
)
|
|
150
|
+
output = "".join(b.text for b in response.content if b.type == "text").strip()
|
|
151
|
+
|
|
152
|
+
if stop_reason == "refusal":
|
|
153
|
+
details = response.stop_details
|
|
154
|
+
refusal = details.category if details is not None else None
|
|
155
|
+
break
|
|
156
|
+
turn = echoable_content(response.content)
|
|
157
|
+
messages.append({"role": "assistant", "content": turn})
|
|
158
|
+
if stop_reason == "pause_turn":
|
|
159
|
+
continue
|
|
160
|
+
calls = [block for block in turn if block.type == "tool_use"]
|
|
161
|
+
if stop_reason != "tool_use" or not calls:
|
|
162
|
+
break
|
|
163
|
+
results = []
|
|
164
|
+
for block in calls:
|
|
165
|
+
outcome = toolbox.call(block.name, dict(block.input))
|
|
166
|
+
results.append(
|
|
167
|
+
{
|
|
168
|
+
"type": "tool_result",
|
|
169
|
+
"tool_use_id": block.id,
|
|
170
|
+
"content": json.dumps(outcome.result),
|
|
171
|
+
"is_error": outcome.is_error,
|
|
172
|
+
}
|
|
173
|
+
)
|
|
174
|
+
messages.append({"role": "user", "content": results}) # all results in one turn
|
|
175
|
+
else:
|
|
176
|
+
stop_reason = "max_steps"
|
|
177
|
+
|
|
178
|
+
return Trajectory(
|
|
179
|
+
output=output,
|
|
180
|
+
usage=usage,
|
|
181
|
+
model=model,
|
|
182
|
+
stop_reason=stop_reason,
|
|
183
|
+
steps=steps,
|
|
184
|
+
served_by_fallback=served_by_fallback,
|
|
185
|
+
refusal_category=refusal,
|
|
186
|
+
)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Black-box agent service: POST the scenario input, receive the agent's own trajectory.
|
|
2
|
+
|
|
3
|
+
Use it to evaluate a deployed agent (any framework) in a staging environment. The
|
|
4
|
+
service executes its own tools, so mock responses do not apply; assertions run against
|
|
5
|
+
the tool calls it reports.
|
|
6
|
+
|
|
7
|
+
Request: {"input": "...", "tools": [{"name", "description", "input_schema"}, ...]}
|
|
8
|
+
Response: {"output": "...", "tool_calls": [{"name", "args", "result"}], "model": "...",
|
|
9
|
+
"usage": {"input_tokens", "output_tokens"}, "stop_reason": "..."}
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import urllib.request
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from agent_eval.agents import AgentConfig
|
|
19
|
+
from agent_eval.models import Trajectory
|
|
20
|
+
from agent_eval.toolbox import Toolbox
|
|
21
|
+
|
|
22
|
+
_FIELDS = ("output", "tool_calls", "usage", "stop_reason", "model", "refusal_category")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class HttpAgent:
|
|
26
|
+
def __init__(self, config: AgentConfig) -> None:
|
|
27
|
+
if not config.endpoint:
|
|
28
|
+
raise ValueError("provider http needs an endpoint")
|
|
29
|
+
self.name = config.name
|
|
30
|
+
self.model = config.model or "remote"
|
|
31
|
+
self._endpoint = config.endpoint
|
|
32
|
+
self._headers = {"content-type": "application/json", **config.headers}
|
|
33
|
+
self._timeout = config.timeout_s
|
|
34
|
+
|
|
35
|
+
def run(self, user_input: str, toolbox: Toolbox) -> Trajectory:
|
|
36
|
+
payload = {
|
|
37
|
+
"input": user_input,
|
|
38
|
+
"tools": [
|
|
39
|
+
spec.model_dump(include={"name", "description", "input_schema"})
|
|
40
|
+
for spec in toolbox.specs
|
|
41
|
+
],
|
|
42
|
+
}
|
|
43
|
+
request = urllib.request.Request( # noqa: S310 - scheme validated as http(s) in AgentConfig
|
|
44
|
+
self._endpoint,
|
|
45
|
+
data=json.dumps(payload).encode(),
|
|
46
|
+
headers=self._headers,
|
|
47
|
+
method="POST",
|
|
48
|
+
)
|
|
49
|
+
with urllib.request.urlopen(request, timeout=self._timeout) as response: # noqa: S310
|
|
50
|
+
body: dict[str, Any] = json.load(response)
|
|
51
|
+
data = {key: body[key] for key in _FIELDS if key in body}
|
|
52
|
+
data.setdefault("model", self.model)
|
|
53
|
+
return Trajectory.model_validate(data)
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Function-calling loop for OpenAI-compatible Chat Completions endpoints.
|
|
2
|
+
|
|
3
|
+
Covers OpenAI, Azure OpenAI (``https://<resource>.openai.azure.com/openai/v1/``),
|
|
4
|
+
Vertex AI's OpenAI-compatible endpoint and self-hosted vLLM, by setting ``base_url``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import openai
|
|
14
|
+
from openai.types.chat import (
|
|
15
|
+
ChatCompletionFunctionToolParam,
|
|
16
|
+
ChatCompletionMessageFunctionToolCall,
|
|
17
|
+
ChatCompletionMessageParam,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
from agent_eval import tracing
|
|
21
|
+
from agent_eval.agents import AgentConfig
|
|
22
|
+
from agent_eval.models import Trajectory, Usage
|
|
23
|
+
from agent_eval.toolbox import Toolbox
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class OpenAICompatibleAgent:
|
|
27
|
+
def __init__(self, config: AgentConfig, client: Any | None = None) -> None:
|
|
28
|
+
if not config.model:
|
|
29
|
+
raise ValueError("provider openai needs a model (or Azure deployment name)")
|
|
30
|
+
self.name = config.name
|
|
31
|
+
self.model = config.model
|
|
32
|
+
self._config = config
|
|
33
|
+
self._client = (
|
|
34
|
+
client
|
|
35
|
+
if client is not None
|
|
36
|
+
else openai.OpenAI(
|
|
37
|
+
base_url=config.base_url,
|
|
38
|
+
api_key=os.environ.get(config.api_key_env),
|
|
39
|
+
max_retries=4,
|
|
40
|
+
)
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
def run(self, user_input: str, toolbox: Toolbox) -> Trajectory:
|
|
44
|
+
cfg = self._config
|
|
45
|
+
messages: list[ChatCompletionMessageParam] = []
|
|
46
|
+
if cfg.system_prompt:
|
|
47
|
+
messages.append({"role": "system", "content": cfg.system_prompt})
|
|
48
|
+
messages.append({"role": "user", "content": user_input})
|
|
49
|
+
tools: list[ChatCompletionFunctionToolParam] = [
|
|
50
|
+
{
|
|
51
|
+
"type": "function",
|
|
52
|
+
"function": {
|
|
53
|
+
"name": spec.name,
|
|
54
|
+
"description": spec.description,
|
|
55
|
+
"parameters": spec.input_schema,
|
|
56
|
+
},
|
|
57
|
+
}
|
|
58
|
+
for spec in toolbox.specs
|
|
59
|
+
]
|
|
60
|
+
usage = Usage()
|
|
61
|
+
model, output, stop_reason, refusal = self.model, "", None, None
|
|
62
|
+
steps = 0
|
|
63
|
+
while steps < cfg.max_steps:
|
|
64
|
+
steps += 1
|
|
65
|
+
attributes = {"gen_ai.operation.name": "chat", "gen_ai.request.model": self.model}
|
|
66
|
+
with tracing.span(f"chat {self.model}", attributes):
|
|
67
|
+
try:
|
|
68
|
+
response = self._client.chat.completions.create(
|
|
69
|
+
model=self.model, messages=messages, tools=tools
|
|
70
|
+
)
|
|
71
|
+
except openai.RateLimitError as exc:
|
|
72
|
+
return Trajectory(
|
|
73
|
+
model=model, steps=steps, usage=usage, error=f"rate limited: {exc.message}"
|
|
74
|
+
)
|
|
75
|
+
except openai.APIStatusError as exc:
|
|
76
|
+
return Trajectory(
|
|
77
|
+
model=model,
|
|
78
|
+
steps=steps,
|
|
79
|
+
usage=usage,
|
|
80
|
+
error=f"API error {exc.status_code}: {exc.message}",
|
|
81
|
+
)
|
|
82
|
+
except openai.APIConnectionError as exc:
|
|
83
|
+
return Trajectory(
|
|
84
|
+
model=model, steps=steps, usage=usage, error=f"connection error: {exc}"
|
|
85
|
+
)
|
|
86
|
+
if response.usage is not None:
|
|
87
|
+
usage += Usage(
|
|
88
|
+
input_tokens=response.usage.prompt_tokens,
|
|
89
|
+
output_tokens=response.usage.completion_tokens,
|
|
90
|
+
)
|
|
91
|
+
model = response.model or model
|
|
92
|
+
choice = response.choices[0]
|
|
93
|
+
message = choice.message
|
|
94
|
+
stop_reason = choice.finish_reason
|
|
95
|
+
if message.refusal:
|
|
96
|
+
output, stop_reason, refusal = message.refusal, "refusal", "model_refusal"
|
|
97
|
+
break
|
|
98
|
+
output = (message.content or "").strip()
|
|
99
|
+
calls = [
|
|
100
|
+
c
|
|
101
|
+
for c in (message.tool_calls or [])
|
|
102
|
+
if isinstance(c, ChatCompletionMessageFunctionToolCall)
|
|
103
|
+
]
|
|
104
|
+
assistant: dict[str, Any] = {"role": "assistant", "content": message.content}
|
|
105
|
+
if calls:
|
|
106
|
+
assistant["tool_calls"] = [
|
|
107
|
+
{
|
|
108
|
+
"id": c.id,
|
|
109
|
+
"type": "function",
|
|
110
|
+
"function": {"name": c.function.name, "arguments": c.function.arguments},
|
|
111
|
+
}
|
|
112
|
+
for c in calls
|
|
113
|
+
]
|
|
114
|
+
messages.append(assistant) # type: ignore[arg-type] # dict built to the assistant-message shape
|
|
115
|
+
if not calls:
|
|
116
|
+
break
|
|
117
|
+
for call in calls:
|
|
118
|
+
try:
|
|
119
|
+
args = json.loads(call.function.arguments or "{}")
|
|
120
|
+
except json.JSONDecodeError:
|
|
121
|
+
outcome = toolbox.reject(call.function.name, "arguments are not valid JSON")
|
|
122
|
+
else:
|
|
123
|
+
outcome = toolbox.call(call.function.name, args)
|
|
124
|
+
messages.append(
|
|
125
|
+
{"role": "tool", "tool_call_id": call.id, "content": json.dumps(outcome.result)}
|
|
126
|
+
)
|
|
127
|
+
else:
|
|
128
|
+
stop_reason = "max_steps"
|
|
129
|
+
|
|
130
|
+
return Trajectory(
|
|
131
|
+
output=output,
|
|
132
|
+
usage=usage,
|
|
133
|
+
model=model,
|
|
134
|
+
stop_reason=stop_reason,
|
|
135
|
+
steps=steps,
|
|
136
|
+
refusal_category=refusal,
|
|
137
|
+
)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Load an agent implemented in Python: ``entrypoint: path/to/agent.py:ClassName``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import importlib.util
|
|
7
|
+
import inspect
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from agent_eval.agents import Agent, AgentConfig
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def load_python_agent(config: AgentConfig) -> Agent:
|
|
14
|
+
if not config.entrypoint or ":" not in config.entrypoint:
|
|
15
|
+
raise ValueError("provider python needs entrypoint 'path/to/file.py:ClassName'")
|
|
16
|
+
file_part, class_name = config.entrypoint.rsplit(":", 1)
|
|
17
|
+
path = (config.source_dir / file_part).resolve()
|
|
18
|
+
if not path.is_file():
|
|
19
|
+
raise FileNotFoundError(f"agent entrypoint not found: {path}")
|
|
20
|
+
|
|
21
|
+
module_name = f"agent_eval_user_{hashlib.sha256(str(path).encode()).hexdigest()[:12]}"
|
|
22
|
+
spec = importlib.util.spec_from_file_location(module_name, path)
|
|
23
|
+
if spec is None or spec.loader is None: # pragma: no cover - defensive
|
|
24
|
+
raise ImportError(f"cannot import {path}")
|
|
25
|
+
module = importlib.util.module_from_spec(spec)
|
|
26
|
+
spec.loader.exec_module(module)
|
|
27
|
+
|
|
28
|
+
cls: Any = getattr(module, class_name, None)
|
|
29
|
+
if cls is None:
|
|
30
|
+
raise AttributeError(f"{path} has no class {class_name}")
|
|
31
|
+
agent = cls(config) if inspect.signature(cls).parameters else cls()
|
|
32
|
+
if not callable(getattr(agent, "run", None)):
|
|
33
|
+
raise TypeError(f"{class_name} must define run(user_input, toolbox) -> Trajectory")
|
|
34
|
+
agent.name = config.name
|
|
35
|
+
if config.model:
|
|
36
|
+
agent.model = config.model
|
|
37
|
+
return agent
|