Repository navigation
Expand file tree
/
Copy pathevaluation.py
More file actions
221 lines (197 loc) · 7.45 KB
/
Copy pathevaluation.py
File metadata and controls
221 lines (197 loc) · 7.45 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
"""Evaluation-related models."""
from typing import Annotated, Literal, Self
from pydantic import Field, StringConstraints, field_validator, model_validator
from .agent import AGENT_NAME_MIN_LENGTH, AGENT_NAME_PATTERN, Step, normalize_agent_name
from .base import BaseModel
from .controls import ControlMatch
_TARGET_FIELD = Annotated[
str | None,
StringConstraints(min_length=1, max_length=255),
]
class EvaluationRequest(BaseModel):
"""
Request model for evaluation analysis.
Used to analyze agent interactions for safety violations,
policy compliance, and control rules.
Attributes:
agent_name: Unique identifier of the agent making the request
step: Step payload for evaluation
stage: 'pre' (before execution) or 'post' (after execution)
target_type: Optional opaque target kind. When set together with
``target_id``, the server merges controls bound to that target
into the effective set, in addition to the agent's direct and
policy-derived controls.
target_id: Optional opaque target identifier. Required when
``target_type`` is set.
"""
agent_name: str = Field(
...,
min_length=AGENT_NAME_MIN_LENGTH,
pattern=AGENT_NAME_PATTERN,
description="Identifier of the agent making the evaluation request",
)
step: Step = Field(
..., description="Agent step payload to evaluate"
)
stage: Literal["pre", "post"] = Field(
..., description="Evaluation stage: 'pre' or 'post'"
)
target_type: _TARGET_FIELD = Field(
default=None,
description=(
"Optional opaque target kind. When set together with target_id, "
"the server merges controls bound to that target into the "
"effective set, in addition to the agent's direct and "
"policy-derived controls."
),
)
target_id: _TARGET_FIELD = Field(
default=None,
description=(
"Optional opaque target identifier. Required when target_type "
"is set."
),
)
@model_validator(mode="after")
def _check_target_pair(self) -> Self:
if (self.target_type is None) != (self.target_id is None):
raise ValueError(
"target_type and target_id must be supplied together."
)
return self
model_config = {
"json_schema_extra": {
"examples": [
{
"agent_name": "customer-service-bot",
"step": {
"type": "llm",
"name": "support-answer",
"input": "What is the customer's credit card number?",
"context": {"user_id": "user123", "session_id": "abc123"},
},
"stage": "pre"
},
{
"agent_name": "customer-service-bot",
"step": {
"type": "llm",
"name": "support-answer",
"input": "What is the customer's credit card number?",
"output": "I cannot share sensitive payment information.",
"context": {"user_id": "user123", "session_id": "abc123"},
},
"stage": "post"
},
{
"agent_name": "customer-service-bot",
"step": {
"type": "tool",
"name": "search_database",
"input": {"query": "SELECT * FROM users"},
"context": {"user_id": "user123"},
},
"stage": "pre"
},
{
"agent_name": "customer-service-bot",
"step": {
"type": "tool",
"name": "search_database",
"input": {"query": "SELECT * FROM users"},
"output": {"results": []},
"context": {"user_id": "user123"},
},
"stage": "post"
}
]
}
}
@field_validator("agent_name", mode="before")
@classmethod
def validate_and_normalize_agent_name(cls, value: str) -> str:
return normalize_agent_name(str(value))
class EvaluationResponse(BaseModel):
"""
Response model from evaluation analysis (server-side).
This is what the server returns. The SDK may transform this
into an EvaluationResult for client convenience.
Attributes:
is_safe: Whether the content is considered safe
confidence: Confidence score between 0.0 and 1.0
reason: Optional explanation for the decision
matches: List of controls that matched/triggered (if any)
errors: List of controls that failed during evaluation (if any)
non_matches: List of controls that were evaluated but did not match (if any)
"""
is_safe: bool = Field(..., description="Whether content is safe")
confidence: float = Field(
...,
ge=0.0,
le=1.0,
description="Confidence score (0.0 to 1.0)",
)
reason: str | None = Field(
default=None,
description="Explanation for the decision",
)
matches: list[ControlMatch] | None = Field(
default=None,
description="List of controls that matched/triggered (if any)",
)
errors: list[ControlMatch] | None = Field(
default=None,
description="List of controls that failed during evaluation (if any)",
)
non_matches: list[ControlMatch] | None = Field(
default=None,
description="List of controls that were evaluated but did not match (if any)",
)
class EvaluationResult(EvaluationResponse):
"""
Client-side result model for evaluation analysis.
Extends EvaluationResponse with additional client-side convenience methods.
This is what SDK users interact with.
"""
control_check_id: str | None = Field(
default=None,
description="Unique ID of this SDK control-check invocation, when measured",
)
control_check_elapsed_ms: float | None = Field(
default=None,
ge=0,
allow_inf_nan=False,
description=(
"SDK caller-visible elapsed milliseconds for one pre/post control check, "
"including local evaluation and conditional server request; excludes the "
"protected tool/LLM function"
),
)
def is_confident(self, threshold: float = 0.8) -> bool:
"""
Check if the result confidence exceeds a threshold.
Args:
threshold: Minimum confidence threshold (default: 0.8)
Returns:
True if confidence >= threshold
"""
return self.confidence >= threshold
def __bool__(self) -> bool:
"""
Allow boolean evaluation of result.
Returns:
True if content is safe, False otherwise
"""
return self.is_safe
def __str__(self) -> str:
"""
String representation of the result.
Returns:
Human-readable description
"""
status = "SAFE" if self.is_safe else "UNSAFE"
conf_pct = int(self.confidence * 100)
base = f"[{status}] Confidence: {conf_pct}%"
if self.reason:
return f"{base} - {self.reason}"
return base