API Reference¶
Source code in instructor/client.py
Validator
¶
Bases: OpenAISchema
Validate if an attribute is correct and if not, return a new value with an error message
Source code in instructor/dsl/validators.py
llm_validator(statement, client, allow_override=False, model='gpt-3.5-turbo', temperature=0)
¶
Create a validator that uses the LLM to validate an attribute
Usage¶
from instructor import llm_validator
from pydantic import BaseModel, Field, field_validator
class User(BaseModel):
name: str = Annotated[str, llm_validator("The name must be a full name all lowercase")
age: int = Field(description="The age of the person")
try:
user = User(name="Jason Liu", age=20)
except ValidationError as e:
print(e)
1 validation error for User
name
The name is valid but not all lowercase (type=value_error.llm_validator)
Note that there, the error message is written by the LLM, and the error type is value_error.llm_validator
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
statement | str | The statement to validate | required |
model | str | The LLM to use for validation (default: "gpt-3.5-turbo-0613") | 'gpt-3.5-turbo' |
temperature | float | The temperature to use for the LLM (default: 0) | 0 |
openai_client | OpenAI | The OpenAI client to use (default: None) | required |
Source code in instructor/dsl/validators.py
openai_moderation(client)
¶
Validates a message using OpenAI moderation model.
Should only be used for monitoring inputs and outputs of OpenAI APIs Other use cases are disallowed as per: https://platform.openai.com/docs/guides/moderation/overview
Example:
from instructor import OpenAIModeration
class Response(BaseModel):
message: Annotated[str, AfterValidator(OpenAIModeration(openai_client=client))]
Response(message="I hate you")
ValidationError: 1 validation error for Response
message
Value error, `I hate you.` was flagged for ['harassment'] [type=value_error, input_value='I hate you.', input_type=str]
client (OpenAI): The OpenAI client to use, must be sync (default: None)
Source code in instructor/dsl/validators.py
IterableModel(subtask_class, name=None, description=None)
¶
Dynamically create a IterableModel OpenAISchema that can be used to segment multiple tasks given a base class. This creates class that can be used to create a toolkit for a specific task, names and descriptions are automatically generated. However they can be overridden.
Usage¶
from pydantic import BaseModel, Field
from instructor import IterableModel
class User(BaseModel):
name: str = Field(description="The name of the person")
age: int = Field(description="The age of the person")
role: str = Field(description="The role of the person")
MultiUser = IterableModel(User)
Result¶
class MultiUser(OpenAISchema, MultiTaskBase):
tasks: List[User] = Field(
default_factory=list,
repr=False,
description="Correctly segmented list of `User` tasks",
)
@classmethod
def from_streaming_response(cls, completion) -> Generator[User]:
'''
Parse the streaming response from OpenAI and yield a `User` object
for each task in the response
'''
json_chunks = cls.extract_json(completion)
yield from cls.tasks_from_chunks(json_chunks)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
subtask_class | Type[OpenAISchema] | The base class to use for the MultiTask | required |
name | Optional[str] | The name of the MultiTask class, if None then the name of the subtask class is used as | None |
description | Optional[str] | The description of the MultiTask class, if None then the description is set to | None |
Returns:
Name | Type | Description |
---|---|---|
schema | OpenAISchema | A new class that can be used to segment multiple tasks |
Source code in instructor/dsl/iterable.py
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 |
|
Partial
¶
Bases: Generic[T_Model]
Generate a new class which has PartialBase as a base class.
Notes
This will enable partial validation of the model while streaming.
Example
Partial[SomeModel]
Source code in instructor/dsl/partial.py
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 |
|
__class_getitem__(wrapped_class)
¶
Convert model to one that inherits from PartialBase.
We don't make the fields optional at this point, we just wrap them with Partial
so the names of the nested models will be Partial{ModelName}
. We want the output of model_json_schema()
to reflect the name change, but everything else should be the same as the original model. During validation, we'll generate a true partial model to support partially defined fields.
Source code in instructor/dsl/partial.py
__init_subclass__(*args, **kwargs)
¶
Cannot subclass.
Raises:
Type | Description |
---|---|
TypeError | Subclassing not allowed. |
__new__(*args, **kwargs)
¶
Cannot instantiate.
Raises:
Type | Description |
---|---|
TypeError | Direct instantiation not allowed. |
Source code in instructor/dsl/partial.py
PartialBase
¶
Bases: Generic[T_Model]
Source code in instructor/dsl/partial.py
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 |
|
get_partial_model()
cached
classmethod
¶
Return a partial model we can use to validate partial results.
Source code in instructor/dsl/partial.py
MaybeBase
¶
Bases: BaseModel
, Generic[T]
Extract a result from a model, if any, otherwise set the error and message fields.
Source code in instructor/dsl/maybe.py
Maybe(model)
¶
Create a Maybe model for a given Pydantic model. This allows you to return a model that includes fields for result
, error
, and message
for sitatations where the data may not be present in the context.
Usage¶
from pydantic import BaseModel, Field
from instructor import Maybe
class User(BaseModel):
name: str = Field(description="The name of the person")
age: int = Field(description="The age of the person")
role: str = Field(description="The role of the person")
MaybeUser = Maybe(User)
Result¶
class MaybeUser(BaseModel):
result: Optional[User]
error: bool = Field(default=False)
message: Optional[str]
def __bool__(self):
return self.result is not None
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model | Type[BaseModel] | The Pydantic model to wrap with Maybe. | required |
Returns:
Name | Type | Description |
---|---|---|
MaybeModel | Type[BaseModel] | A new Pydantic model that includes fields for |
Source code in instructor/dsl/maybe.py
OpenAISchema
¶
Bases: BaseModel
Source code in instructor/function_calls.py
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 |
|
from_response(completion, validation_context=None, strict=None, mode=Mode.TOOLS)
classmethod
¶
Execute the function from the response of an openai chat completion
Parameters:
Name | Type | Description | Default |
---|---|---|---|
completion | ChatCompletion | The response from an openai chat completion | required |
throw_error | bool | Whether to throw an error if the function call is not detected | required |
context | dict | The context to use for validating the response | required |
strict | bool | Whether to use strict json parsing | None |
mode | Mode | The openai completion mode | TOOLS |
Returns:
Name | Type | Description |
---|---|---|
cls | OpenAISchema | An instance of the class |
Source code in instructor/function_calls.py
openai_schema()
¶
Return the schema in the format of OpenAI's schema as jsonschema
Note
Its important to add a docstring to describe how to best use this class, it will be included in the description attribute and be part of the prompt.
Returns:
Name | Type | Description |
---|---|---|
model_json_schema | dict | A dictionary in the format of OpenAI's schema as jsonschema |