docent-python 0.1.2a0__py3-none-any.whl → 0.1.4a0__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.

Potentially problematic release.


This version of docent-python might be problematic. Click here for more details.

@@ -1,19 +1,12 @@
1
1
  from docent.data_models.agent_run import AgentRun
2
2
  from docent.data_models.citation import Citation
3
- from docent.data_models.metadata import (
4
- BaseAgentRunMetadata,
5
- BaseMetadata,
6
- InspectAgentRunMetadata,
7
- )
8
3
  from docent.data_models.regex import RegexSnippet
9
- from docent.data_models.transcript import Transcript
4
+ from docent.data_models.transcript import Transcript, TranscriptGroup
10
5
 
11
6
  __all__ = [
12
7
  "AgentRun",
13
8
  "Citation",
14
9
  "RegexSnippet",
15
- "BaseAgentRunMetadata",
16
- "BaseMetadata",
17
- "InspectAgentRunMetadata",
18
10
  "Transcript",
11
+ "TranscriptGroup",
19
12
  ]
@@ -1,3 +1,4 @@
1
+ import json
1
2
  import sys
2
3
  from typing import Any, Literal, TypedDict, cast
3
4
  from uuid import uuid4
@@ -12,8 +13,11 @@ from pydantic import (
12
13
  )
13
14
 
14
15
  from docent.data_models._tiktoken_util import get_token_count, group_messages_into_ranges
15
- from docent.data_models.metadata import BaseAgentRunMetadata
16
- from docent.data_models.transcript import Transcript, TranscriptWithoutMetadataValidator
16
+ from docent.data_models.transcript import (
17
+ Transcript,
18
+ TranscriptWithoutMetadataValidator,
19
+ fake_model_dump,
20
+ )
17
21
 
18
22
 
19
23
  class FilterableField(TypedDict):
@@ -32,7 +36,7 @@ class AgentRun(BaseModel):
32
36
  name: Optional human-readable name for the agent run.
33
37
  description: Optional description of the agent run.
34
38
  transcripts: Dict mapping transcript IDs to Transcript objects.
35
- metadata: Additional structured metadata about the agent run.
39
+ metadata: Additional structured metadata about the agent run as a JSON-serializable dictionary.
36
40
  """
37
41
 
38
42
  id: str = Field(default_factory=lambda: str(uuid4()))
@@ -40,23 +44,34 @@ class AgentRun(BaseModel):
40
44
  description: str | None = None
41
45
 
42
46
  transcripts: dict[str, Transcript]
43
- metadata: BaseAgentRunMetadata
47
+ metadata: dict[str, Any] = Field(default_factory=dict)
44
48
 
45
49
  @field_serializer("metadata")
46
- def serialize_metadata(self, metadata: BaseAgentRunMetadata, _info: Any) -> dict[str, Any]:
50
+ def serialize_metadata(self, metadata: dict[str, Any], _info: Any) -> dict[str, Any]:
47
51
  """
48
- Custom serializer for the metadata field so the internal fields are explicitly preserved.
52
+ Custom serializer for the metadata field - returns the dict as-is since it's already serializable.
49
53
  """
50
- return metadata.model_dump(strip_internal_fields=False)
54
+ return fake_model_dump(metadata)
51
55
 
52
56
  @field_validator("metadata", mode="before")
53
57
  @classmethod
54
- def _validate_metadata_type(cls, v: Any) -> Any:
55
- if v is not None and not isinstance(v, BaseAgentRunMetadata):
56
- raise ValueError(
57
- f"metadata must be an instance of BaseAgentRunMetadata, got {type(v).__name__}"
58
- )
59
- return v
58
+ def _validate_metadata_json_serializable(cls, v: Any) -> dict[str, Any]:
59
+ """
60
+ Validates that metadata is a dictionary and is JSON-serializable.
61
+ """
62
+ if v is None:
63
+ return {}
64
+
65
+ if not isinstance(v, dict):
66
+ raise ValueError(f"metadata must be a dictionary, got {type(v).__name__}")
67
+
68
+ # Check that the metadata is JSON serializable
69
+ try:
70
+ json.dumps(fake_model_dump(cast(dict[str, Any], v)))
71
+ except (TypeError, ValueError) as e:
72
+ raise ValueError(f"metadata must be JSON-serializable: {e}")
73
+
74
+ return cast(dict[str, Any], v)
60
75
 
61
76
  @model_validator(mode="after")
62
77
  def _validate_transcripts_not_empty(self):
@@ -88,16 +103,11 @@ class AgentRun(BaseModel):
88
103
  transcripts_str = "\n\n".join(transcript_strs)
89
104
 
90
105
  # Gather metadata
91
- metadata_obj = self.metadata.model_dump(strip_internal_fields=True)
106
+ metadata_obj = fake_model_dump(self.metadata)
92
107
  if self.name is not None:
93
108
  metadata_obj["name"] = self.name
94
109
  if self.description is not None:
95
110
  metadata_obj["description"] = self.description
96
- # Add the field descriptions if they exist
97
- metadata_obj = {
98
- (f"{k} ({d})" if (d := self.metadata.get_field_description(k)) is not None else k): v
99
- for k, v in metadata_obj.items()
100
- }
101
111
 
102
112
  yaml_width = float("inf")
103
113
  transcripts_str = (
@@ -202,7 +212,7 @@ class AgentRun(BaseModel):
202
212
  _explore_dict(cast(dict[str, Any], v), f"{prefix}.{k}", depth + 1)
203
213
 
204
214
  # Look at the agent run metadata
205
- _explore_dict(self.metadata.model_dump(strip_internal_fields=True), "metadata", 0)
215
+ _explore_dict(fake_model_dump(self.metadata), "metadata", 0)
206
216
  # Look at the transcript metadata
207
217
  # TODO(mengk): restore this later when we have the ability to integrate with SQL.
208
218
  # for t_id, t in self.transcripts.items():
@@ -1,229 +1,229 @@
1
- import traceback
2
- from typing import Any, Optional
3
-
4
- from pydantic import (
5
- BaseModel,
6
- ConfigDict,
7
- Field,
8
- PrivateAttr,
9
- SerializerFunctionWrapHandler,
10
- model_serializer,
11
- model_validator,
12
- )
13
-
14
- from docent._log_util import get_logger
15
-
16
- logger = get_logger(__name__)
17
-
18
- SINGLETONS = (int, float, str, bool)
19
-
20
-
21
- class BaseMetadata(BaseModel):
22
- """Provides common functionality for accessing and validating metadata fields.
23
- All metadata classes should inherit from this class.
24
-
25
- Serialization Behavior:
26
- - Field descriptions are highly recommended and stored in serialized versions of the object.
27
- - When a subclass of BaseMetadata is uploaded to a server, all extra fields and their descriptions are retained.
28
- - To recover the original structure with proper typing upon download, use:
29
- `CustomMetadataClass.model_validate(obj.model_dump())`.
30
-
31
- Attributes:
32
- model_config: Pydantic configuration that allows extra fields.
33
- allow_fields_without_descriptions: Boolean indicating whether to allow fields without descriptions.
34
- """
35
-
36
- model_config = ConfigDict(extra="allow")
37
- allow_fields_without_descriptions: bool = True
38
-
39
- # Private attribute to store field descriptions
40
- _field_descriptions: dict[str, str | None] | None = PrivateAttr(default=None)
41
- _internal_basemetadata_fields: set[str] = PrivateAttr(
42
- default={
43
- "allow_fields_without_descriptions",
44
- "model_config",
45
- "_field_descriptions",
46
- }
47
- )
48
-
49
- @model_validator(mode="after")
50
- def _validate_field_types_and_descriptions(self):
51
- """Validates that all fields have descriptions and proper types.
52
-
53
- Returns:
54
- Self: The validated model instance.
55
-
56
- Raises:
57
- ValueError: If any field is missing a description or has an invalid type.
58
- """
59
- # Validate each field in the model
60
- for field_name, field_info in self.__class__.model_fields.items():
61
- if field_name in self._internal_basemetadata_fields:
62
- continue
63
-
64
- # Check that field has a description
65
- if field_info.description is None:
66
- if not self.allow_fields_without_descriptions:
67
- raise ValueError(
68
- f"Field `{field_name}` needs a description in the definition of `{self.__class__.__name__}`, like `{field_name}: T = Field(description=..., default=...)`. "
69
- "To allow un-described fields, set `allow_fields_without_descriptions = True` on the instance or in your metadata class definition."
70
- )
71
-
72
- # Validate that the metadata is JSON serializable
73
- try:
74
- self.model_dump_json()
75
- except Exception as e:
76
- raise ValueError(
77
- f"Metadata is not JSON serializable: {e}. Traceback: {traceback.format_exc()}"
78
- )
79
-
80
- return self
81
-
82
- def model_post_init(self, __context: Any) -> None:
83
- """Initializes field descriptions from extra data after model initialization.
84
-
85
- Args:
86
- __context: The context provided by Pydantic's post-initialization hook.
87
- """
88
- fd = self.model_extra.pop("_field_descriptions", None) if self.model_extra else None
89
- if fd is not None:
90
- self._field_descriptions = fd
91
-
92
- @model_serializer(mode="wrap")
93
- def _serialize_model(self, handler: SerializerFunctionWrapHandler):
94
- # Call the default serializer
95
- data = handler(self)
96
-
97
- # Dump the field descriptions
98
- if self._field_descriptions is None:
99
- self._field_descriptions = self._compute_field_descriptions()
100
- data["_field_descriptions"] = self._field_descriptions
101
-
102
- return data
103
-
104
- def model_dump(
105
- self, *args: Any, strip_internal_fields: bool = False, **kwargs: Any
106
- ) -> dict[str, Any]:
107
- data = super().model_dump(*args, **kwargs)
108
-
109
- # Remove internal fields if requested
110
- if strip_internal_fields:
111
- for field in self._internal_basemetadata_fields:
112
- if field in data:
113
- data.pop(field)
114
-
115
- return data
116
-
117
- def get(self, key: str, default_value: Any = None) -> Any:
118
- """Gets a value from the metadata by key.
119
-
120
- Args:
121
- key: The key to look up in the metadata.
122
- default_value: Value to return if the key is not found. Defaults to None.
123
-
124
- Returns:
125
- Any: The value associated with the key, or the default value if not found.
126
- """
127
- # Check if the field exists in the model's fields
128
- if key in self.__class__.model_fields or (
129
- self.model_extra is not None and key in self.model_extra
130
- ):
131
- # Field exists, return its value (even if None)
132
- return getattr(self, key)
133
-
134
- logger.warning(f"Field '{key}' not found in {self.__class__.__name__}")
135
- return default_value
136
-
137
- def get_field_description(self, field_name: str) -> str | None:
138
- """Gets the description of a field defined in the model schema.
139
-
140
- Args:
141
- field_name: The name of the field.
142
-
143
- Returns:
144
- str or None: The description string if the field is defined in the model schema
145
- and has a description, otherwise None.
146
- """
147
- if self._field_descriptions is None:
148
- self._field_descriptions = self._compute_field_descriptions()
149
-
150
- if field_name in self._field_descriptions:
151
- return self._field_descriptions[field_name]
152
-
153
- logger.warning(
154
- f"Field description for '{field_name}' not found in {self.__class__.__name__}"
155
- )
156
- return None
157
-
158
- def get_all_field_descriptions(self) -> dict[str, str | None]:
159
- """Gets descriptions for all fields defined in the model schema.
160
-
161
- Returns:
162
- dict: A dictionary mapping field names to their descriptions.
163
- Only includes fields that have descriptions defined in the schema.
164
- """
165
- if self._field_descriptions is None:
166
- self._field_descriptions = self._compute_field_descriptions()
167
- return self._field_descriptions
168
-
169
- def _compute_field_descriptions(self) -> dict[str, str | None]:
170
- """Computes descriptions for all fields in the model.
171
-
172
- Returns:
173
- dict: A dictionary mapping field names to their descriptions.
174
- """
175
- field_descriptions: dict[str, Optional[str]] = {}
176
- for field_name, field_info in self.__class__.model_fields.items():
177
- if field_name not in self._internal_basemetadata_fields:
178
- field_descriptions[field_name] = field_info.description
179
- return field_descriptions
180
-
181
-
182
- class BaseAgentRunMetadata(BaseMetadata):
183
- """Extends BaseMetadata with fields specific to agent evaluation runs.
184
-
185
- Attributes:
186
- scores: Dictionary of evaluation metrics.
187
- """
188
-
189
- scores: dict[str, int | float | bool | None] = Field(
190
- description="A dict of score_key -> score_value. Use one key for each metric you're tracking."
191
- )
192
-
193
-
194
- class InspectAgentRunMetadata(BaseAgentRunMetadata):
195
- """Extends BaseAgentRunMetadata with fields specific to Inspect runs.
196
-
197
- Attributes:
198
- task_id: The ID of the 'benchmark' or 'set of evals' that the transcript belongs to
199
- sample_id: The specific task inside of the `task_id` benchmark that the transcript was run on
200
- epoch_id: Each `sample_id` should be run multiple times due to stochasticity; `epoch_id` is the integer index of a specific run.
201
- model: The model that was used to generate the transcript
202
- scoring_metadata: Additional metadata about the scoring process
203
- additional_metadata: Additional metadata about the transcript
204
- """
205
-
206
- task_id: str = Field(
207
- description="The ID of the 'benchmark' or 'set of evals' that the transcript belongs to"
208
- )
209
-
210
- # Identification of this particular run
211
- sample_id: str = Field(
212
- description="The specific task inside of the `task_id` benchmark that the transcript was run on"
213
- )
214
- epoch_id: int = Field(
215
- description="Each `sample_id` should be run multiple times due to stochasticity; `epoch_id` is the integer index of a specific run."
216
- )
217
-
218
- # Parameters for the run
219
- model: str = Field(description="The model that was used to generate the transcript")
220
-
221
- # Scoring
222
- scoring_metadata: dict[str, Any] | None = Field(
223
- description="Additional metadata about the scoring process"
224
- )
225
-
226
- # Inspect metadata
227
- additional_metadata: dict[str, Any] | None = Field(
228
- description="Additional metadata about the transcript"
229
- )
1
+ # import traceback
2
+ # from typing import Any, Optional
3
+
4
+ # from pydantic import (
5
+ # BaseModel,
6
+ # ConfigDict,
7
+ # Field,
8
+ # PrivateAttr,
9
+ # SerializerFunctionWrapHandler,
10
+ # model_serializer,
11
+ # model_validator,
12
+ # )
13
+
14
+ # from docent._log_util import get_logger
15
+
16
+ # logger = get_logger(__name__)
17
+
18
+ # SINGLETONS = (int, float, str, bool)
19
+
20
+
21
+ # class BaseMetadata(BaseModel):
22
+ # """Provides common functionality for accessing and validating metadata fields.
23
+ # All metadata classes should inherit from this class.
24
+
25
+ # Serialization Behavior:
26
+ # - Field descriptions are highly recommended and stored in serialized versions of the object.
27
+ # - When a subclass of BaseMetadata is uploaded to a server, all extra fields and their descriptions are retained.
28
+ # - To recover the original structure with proper typing upon download, use:
29
+ # `CustomMetadataClass.model_validate(obj.model_dump())`.
30
+
31
+ # Attributes:
32
+ # model_config: Pydantic configuration that allows extra fields.
33
+ # allow_fields_without_descriptions: Boolean indicating whether to allow fields without descriptions.
34
+ # """
35
+
36
+ # model_config = ConfigDict(extra="allow")
37
+ # allow_fields_without_descriptions: bool = True
38
+
39
+ # # Private attribute to store field descriptions
40
+ # _field_descriptions: dict[str, str | None] | None = PrivateAttr(default=None)
41
+ # _internal_basemetadata_fields: set[str] = PrivateAttr(
42
+ # default={
43
+ # "allow_fields_without_descriptions",
44
+ # "model_config",
45
+ # "_field_descriptions",
46
+ # }
47
+ # )
48
+
49
+ # @model_validator(mode="after")
50
+ # def _validate_field_types_and_descriptions(self):
51
+ # """Validates that all fields have descriptions and proper types.
52
+
53
+ # Returns:
54
+ # Self: The validated model instance.
55
+
56
+ # Raises:
57
+ # ValueError: If any field is missing a description or has an invalid type.
58
+ # """
59
+ # # Validate each field in the model
60
+ # for field_name, field_info in self.__class__.model_fields.items():
61
+ # if field_name in self._internal_basemetadata_fields:
62
+ # continue
63
+
64
+ # # Check that field has a description
65
+ # if field_info.description is None:
66
+ # if not self.allow_fields_without_descriptions:
67
+ # raise ValueError(
68
+ # f"Field `{field_name}` needs a description in the definition of `{self.__class__.__name__}`, like `{field_name}: T = Field(description=..., default=...)`. "
69
+ # "To allow un-described fields, set `allow_fields_without_descriptions = True` on the instance or in your metadata class definition."
70
+ # )
71
+
72
+ # # Validate that the metadata is JSON serializable
73
+ # try:
74
+ # self.model_dump_json()
75
+ # except Exception as e:
76
+ # raise ValueError(
77
+ # f"Metadata is not JSON serializable: {e}. Traceback: {traceback.format_exc()}"
78
+ # )
79
+
80
+ # return self
81
+
82
+ # def model_post_init(self, __context: Any) -> None:
83
+ # """Initializes field descriptions from extra data after model initialization.
84
+
85
+ # Args:
86
+ # __context: The context provided by Pydantic's post-initialization hook.
87
+ # """
88
+ # fd = self.model_extra.pop("_field_descriptions", None) if self.model_extra else None
89
+ # if fd is not None:
90
+ # self._field_descriptions = fd
91
+
92
+ # @model_serializer(mode="wrap")
93
+ # def _serialize_model(self, handler: SerializerFunctionWrapHandler):
94
+ # # Call the default serializer
95
+ # data = handler(self)
96
+
97
+ # # Dump the field descriptions
98
+ # if self._field_descriptions is None:
99
+ # self._field_descriptions = self._compute_field_descriptions()
100
+ # data["_field_descriptions"] = self._field_descriptions
101
+
102
+ # return data
103
+
104
+ # def model_dump(
105
+ # self, *args: Any, strip_internal_fields: bool = False, **kwargs: Any
106
+ # ) -> dict[str, Any]:
107
+ # data = super().model_dump(*args, **kwargs)
108
+
109
+ # # Remove internal fields if requested
110
+ # if strip_internal_fields:
111
+ # for field in self._internal_basemetadata_fields:
112
+ # if field in data:
113
+ # data.pop(field)
114
+
115
+ # return data
116
+
117
+ # def get(self, key: str, default_value: Any = None) -> Any:
118
+ # """Gets a value from the metadata by key.
119
+
120
+ # Args:
121
+ # key: The key to look up in the metadata.
122
+ # default_value: Value to return if the key is not found. Defaults to None.
123
+
124
+ # Returns:
125
+ # Any: The value associated with the key, or the default value if not found.
126
+ # """
127
+ # # Check if the field exists in the model's fields
128
+ # if key in self.__class__.model_fields or (
129
+ # self.model_extra is not None and key in self.model_extra
130
+ # ):
131
+ # # Field exists, return its value (even if None)
132
+ # return getattr(self, key)
133
+
134
+ # logger.warning(f"Field '{key}' not found in {self.__class__.__name__}")
135
+ # return default_value
136
+
137
+ # def get_field_description(self, field_name: str) -> str | None:
138
+ # """Gets the description of a field defined in the model schema.
139
+
140
+ # Args:
141
+ # field_name: The name of the field.
142
+
143
+ # Returns:
144
+ # str or None: The description string if the field is defined in the model schema
145
+ # and has a description, otherwise None.
146
+ # """
147
+ # if self._field_descriptions is None:
148
+ # self._field_descriptions = self._compute_field_descriptions()
149
+
150
+ # if field_name in self._field_descriptions:
151
+ # return self._field_descriptions[field_name]
152
+
153
+ # logger.warning(
154
+ # f"Field description for '{field_name}' not found in {self.__class__.__name__}"
155
+ # )
156
+ # return None
157
+
158
+ # def get_all_field_descriptions(self) -> dict[str, str | None]:
159
+ # """Gets descriptions for all fields defined in the model schema.
160
+
161
+ # Returns:
162
+ # dict: A dictionary mapping field names to their descriptions.
163
+ # Only includes fields that have descriptions defined in the schema.
164
+ # """
165
+ # if self._field_descriptions is None:
166
+ # self._field_descriptions = self._compute_field_descriptions()
167
+ # return self._field_descriptions
168
+
169
+ # def _compute_field_descriptions(self) -> dict[str, str | None]:
170
+ # """Computes descriptions for all fields in the model.
171
+
172
+ # Returns:
173
+ # dict: A dictionary mapping field names to their descriptions.
174
+ # """
175
+ # field_descriptions: dict[str, Optional[str]] = {}
176
+ # for field_name, field_info in self.__class__.model_fields.items():
177
+ # if field_name not in self._internal_basemetadata_fields:
178
+ # field_descriptions[field_name] = field_info.description
179
+ # return field_descriptions
180
+
181
+
182
+ # class BaseAgentRunMetadata(BaseMetadata):
183
+ # """Extends BaseMetadata with fields specific to agent evaluation runs.
184
+
185
+ # Attributes:
186
+ # scores: Dictionary of evaluation metrics.
187
+ # """
188
+
189
+ # scores: dict[str, int | float | bool | None] = Field(
190
+ # description="A dict of score_key -> score_value. Use one key for each metric you're tracking."
191
+ # )
192
+
193
+
194
+ # class InspectAgentRunMetadata(BaseAgentRunMetadata):
195
+ # """Extends BaseAgentRunMetadata with fields specific to Inspect runs.
196
+
197
+ # Attributes:
198
+ # task_id: The ID of the 'benchmark' or 'set of evals' that the transcript belongs to
199
+ # sample_id: The specific task inside of the `task_id` benchmark that the transcript was run on
200
+ # epoch_id: Each `sample_id` should be run multiple times due to stochasticity; `epoch_id` is the integer index of a specific run.
201
+ # model: The model that was used to generate the transcript
202
+ # scoring_metadata: Additional metadata about the scoring process
203
+ # additional_metadata: Additional metadata about the transcript
204
+ # """
205
+
206
+ # task_id: str = Field(
207
+ # description="The ID of the 'benchmark' or 'set of evals' that the transcript belongs to"
208
+ # )
209
+
210
+ # # Identification of this particular run
211
+ # sample_id: str = Field(
212
+ # description="The specific task inside of the `task_id` benchmark that the transcript was run on"
213
+ # )
214
+ # epoch_id: int = Field(
215
+ # description="Each `sample_id` should be run multiple times due to stochasticity; `epoch_id` is the integer index of a specific run."
216
+ # )
217
+
218
+ # # Parameters for the run
219
+ # model: str = Field(description="The model that was used to generate the transcript")
220
+
221
+ # # Scoring
222
+ # scoring_metadata: dict[str, Any] | None = Field(
223
+ # description="Additional metadata about the scoring process"
224
+ # )
225
+
226
+ # # Inspect metadata
227
+ # additional_metadata: dict[str, Any] | None = Field(
228
+ # description="Additional metadata about the transcript"
229
+ # )