-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmodels.py
More file actions
444 lines (367 loc) · 13.4 KB
/
models.py
File metadata and controls
444 lines (367 loc) · 13.4 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Literal, Optional, Union
if TYPE_CHECKING:
from ldai.evaluator import Evaluator
from typing_extensions import Self
@dataclass(frozen=True)
class LDTool:
"""
A single tool entry from the root-level tools map in an AI Config flag variation.
Distinct from model.parameters.tools[] which is the raw array passed to LLM providers.
"""
name: str
description: Optional[str] = None
type: Optional[str] = None
parameters: Optional[Dict[str, Any]] = None
custom_parameters: Optional[Dict[str, Any]] = None
def to_dict(self) -> dict:
result: Dict[str, Any] = {'name': self.name}
if self.description is not None:
result['description'] = self.description
if self.type is not None:
result['type'] = self.type
if self.parameters is not None:
result['parameters'] = self.parameters
if self.custom_parameters is not None:
result['customParameters'] = self.custom_parameters # camelCase in wire format
return result
@dataclass
class LDMessage:
role: Literal['system', 'user', 'assistant']
content: str
def to_dict(self) -> dict:
"""
Render the given message as a dictionary object.
"""
return {
'role': self.role,
'content': self.content,
}
class ModelConfig:
"""
Configuration related to the model.
"""
def __init__(
self,
name: str,
parameters: Optional[Dict[str, Any]] = None,
custom: Optional[Dict[str, Any]] = None,
region: Optional[str] = None,
):
"""
:param name: The name of the model.
:param parameters: Additional model-specific parameters.
:param custom: Additional customer provided data.
:param region: The region the model is deployed in.
"""
self._name = name
self._parameters = parameters
self._custom = custom
self._region = region
@property
def name(self) -> str:
"""
The name of the model.
"""
return self._name
def get_parameter(self, key: str) -> Any:
"""
Retrieve model-specific parameters.
Accessing a named, typed attribute (e.g. name) will result in the call
being delegated to the appropriate property.
"""
if key == 'name':
return self.name
if self._parameters is None:
return None
return self._parameters.get(key)
def get_custom(self, key: str) -> Any:
"""
Retrieve customer provided data.
"""
if self._custom is None:
return None
return self._custom.get(key)
@property
def region(self) -> Optional[str]:
"""
The region the model is deployed in.
"""
return self._region
def to_dict(self) -> dict:
"""
Render the given model config as a dictionary object.
"""
return {
'name': self._name,
'parameters': self._parameters,
'custom': self._custom,
'region': self._region,
}
class ProviderConfig:
"""
Configuration related to the provider.
"""
def __init__(self, name: str):
self._name = name
@property
def name(self) -> str:
"""
The name of the provider.
"""
return self._name
def to_dict(self) -> dict:
"""
Render the given provider config as a dictionary object.
"""
return {
'name': self._name,
}
# ============================================================================
# Judge Types
# ============================================================================
@dataclass(frozen=True)
class JudgeConfiguration:
"""
Configuration for judge attachment to AI Configs.
"""
@dataclass(frozen=True)
class Judge:
"""
Configuration for a single judge attachment.
"""
key: str
sampling_rate: float
def to_dict(self) -> dict:
"""
Render the judge as a dictionary object.
"""
return {
'key': self.key,
'samplingRate': self.sampling_rate,
}
judges: List['JudgeConfiguration.Judge']
def to_dict(self) -> dict:
"""
Render the judge configuration as a dictionary object.
"""
return {
'judges': [judge.to_dict() for judge in self.judges],
}
# ============================================================================
# Base AI Config Types
# ============================================================================
@dataclass(frozen=True)
class AIConfigDefault:
"""
Base AI Config interface for default implementations with optional enabled property.
"""
enabled: Optional[bool] = None
model: Optional[ModelConfig] = None
provider: Optional[ProviderConfig] = None
@classmethod
def disabled(cls) -> Self:
return cls(enabled=False)
def _base_to_dict(self) -> Dict[str, Any]:
"""
Render the base config fields as a dictionary object.
"""
return {
'_ldMeta': {
'enabled': self.enabled or False,
},
'model': self.model.to_dict() if self.model else None,
'provider': self.provider.to_dict() if self.provider else None,
}
@dataclass(frozen=True)
class AIConfig:
"""
Base AI Config interface without mode-specific fields.
Instances are always created by the SDK client, which injects a real
``create_tracker`` factory. User code should never need to construct
this directly -- use the ``*Default`` variants for default values.
``create_tracker`` is a zero-argument callable: each invocation creates a
new tracker for a fresh AI run. Each call mints a new ``runId`` (a UUIDv4)
that LaunchDarkly uses to correlate the run's events in metrics views.
Call it once per AI run; metrics from different ``runId``s cannot be
combined.
"""
key: str
enabled: bool
#: Factory that creates a new tracker for a fresh AI run. Each call mints a
#: new ``runId`` (a UUIDv4) so LaunchDarkly can correlate the run's events
#: in metrics views. Call this once per AI run; metrics from different
#: ``runId``s cannot be combined.
create_tracker: Callable[[], Any]
model: Optional[ModelConfig] = None
provider: Optional[ProviderConfig] = None
def _base_to_dict(self) -> Dict[str, Any]:
"""
Render the base config fields as a dictionary object.
"""
return {
'_ldMeta': {
'enabled': self.enabled,
},
'model': self.model.to_dict() if self.model else None,
'provider': self.provider.to_dict() if self.provider else None,
}
# ============================================================================
# Completion Config Types
# ============================================================================
@dataclass(frozen=True)
class AICompletionConfigDefault(AIConfigDefault):
"""
Default Completion AI Config (default mode).
"""
messages: Optional[List[LDMessage]] = None
judge_configuration: Optional[JudgeConfiguration] = None
tools: Optional[Dict[str, 'LDTool']] = None
def to_dict(self) -> dict:
"""
Render the given default values as an AICompletionConfigDefault-compatible dictionary object.
"""
result = self._base_to_dict()
result['messages'] = [message.to_dict() for message in self.messages] if self.messages else None
if self.judge_configuration is not None:
result['judgeConfiguration'] = self.judge_configuration.to_dict()
if self.tools is not None:
result['tools'] = {k: v.to_dict() for k, v in self.tools.items()}
return result
@dataclass(frozen=True)
class AICompletionConfig(AIConfig):
"""
Completion AI Config (default mode).
"""
evaluator: 'Evaluator' = field(kw_only=True, repr=False, compare=False, hash=False)
messages: Optional[List[LDMessage]] = None
judge_configuration: Optional[JudgeConfiguration] = None
tools: Optional[Dict[str, 'LDTool']] = None
def to_dict(self) -> dict:
"""
Render the given completion config as a dictionary object.
"""
result = self._base_to_dict()
result['messages'] = [message.to_dict() for message in self.messages] if self.messages else None
if self.judge_configuration is not None:
result['judgeConfiguration'] = self.judge_configuration.to_dict()
if self.tools is not None:
result['tools'] = {k: v.to_dict() for k, v in self.tools.items()}
return result
# ============================================================================
# Agent Config Types
# ============================================================================
@dataclass(frozen=True)
class AIAgentConfigDefault(AIConfigDefault):
"""
Default Agent-specific AI Config with instructions.
"""
instructions: Optional[str] = None
judge_configuration: Optional[JudgeConfiguration] = None
tools: Optional[Dict[str, 'LDTool']] = None
def to_dict(self) -> Dict[str, Any]:
"""
Render the given agent config default as a dictionary object.
"""
result = self._base_to_dict()
if self.instructions is not None:
result['instructions'] = self.instructions
if self.judge_configuration is not None:
result['judgeConfiguration'] = self.judge_configuration.to_dict()
if self.tools is not None:
result['tools'] = {k: v.to_dict() for k, v in self.tools.items()}
return result
@dataclass(frozen=True)
class AIAgentConfig(AIConfig):
"""
Agent-specific AI Config with instructions.
"""
evaluator: 'Evaluator' = field(kw_only=True, repr=False, compare=False, hash=False)
instructions: Optional[str] = None
judge_configuration: Optional[JudgeConfiguration] = None
tools: Optional[Dict[str, 'LDTool']] = None
def to_dict(self) -> Dict[str, Any]:
"""
Render the given agent config as a dictionary object.
"""
result = self._base_to_dict()
if self.instructions is not None:
result['instructions'] = self.instructions
if self.judge_configuration is not None:
result['judgeConfiguration'] = self.judge_configuration.to_dict()
if self.tools is not None:
result['tools'] = {k: v.to_dict() for k, v in self.tools.items()}
return result
# ============================================================================
# Judge Config Types
# ============================================================================
@dataclass(frozen=True)
class AIJudgeConfigDefault(AIConfigDefault):
"""
Default Judge-specific AI Config with required evaluation metric key.
"""
messages: Optional[List[LDMessage]] = None
evaluation_metric_key: Optional[str] = None
def to_dict(self) -> dict:
"""
Render the given judge config default as a dictionary object.
"""
result = self._base_to_dict()
result['messages'] = [message.to_dict() for message in self.messages] if self.messages else None
result['evaluationMetricKey'] = self.evaluation_metric_key
return result
@dataclass(frozen=True)
class AIJudgeConfig(AIConfig):
"""
Judge-specific AI Config with required evaluation metric key.
"""
messages: Optional[List[LDMessage]] = None
evaluation_metric_key: Optional[str] = None
def to_dict(self) -> dict:
"""
Render the given judge config as a dictionary object.
"""
result = self._base_to_dict()
result['messages'] = [message.to_dict() for message in self.messages] if self.messages else None
result['evaluationMetricKey'] = self.evaluation_metric_key
return result
# ============================================================================
# Agent Request Config
# ============================================================================
@dataclass
class AIAgentConfigRequest:
"""
Configuration for a single agent request.
Combines agent key with its specific default configuration and variables.
"""
key: str
default: Optional[AIAgentConfigDefault] = None
variables: Optional[Dict[str, Any]] = None
# Type alias for multiple agents
AIAgents = Dict[str, AIAgentConfig]
# Type alias for all AI Config variants
AIConfigKind = Union[AIAgentConfig, AICompletionConfig, AIJudgeConfig]
# ============================================================================
# AI Config Agent Graph Edge Type
# ============================================================================
@dataclass
class Edge:
"""
Edge configuration for an agent graph.
"""
key: str
source_config: str
target_config: str
handoff: Optional[dict] = field(default_factory=dict)
# ============================================================================
# AI Config Agent Graph
# ============================================================================
@dataclass
class AIAgentGraphConfig:
"""
Agent graph configuration.
"""
key: str
root_config_key: str
edges: List[Edge]
enabled: bool = True