API Reference¶
apatch(client, mode=Mode.FUNCTIONS)
¶
No longer necessary, use patch
instead.
Patch the client.chat.completions.create
method
Enables the following features:
response_model
parameter to parse the response from OpenAI's APImax_retries
parameter to retry the function if the response is not validvalidation_context
parameter to validate the response using the pydantic modelstrict
parameter to use strict json parsing
Source code in instructor/patch.py
dump_message(message)
¶
Dumps a message to a dict, to be returned to the OpenAI API. Workaround for an issue with the OpenAI API, where the tool_calls
field isn't allowed to be present in requests if it isn't used.
Source code in instructor/patch.py
is_async(func)
¶
Returns true if the callable is async, accounting for wrapped callables
patch(client, mode=Mode.FUNCTIONS)
¶
Patch the client.chat.completions.create
method
Enables the following features:
response_model
parameter to parse the response from OpenAI's APImax_retries
parameter to retry the function if the response is not validvalidation_context
parameter to validate the response using the pydantic modelstrict
parameter to use strict json parsing
Source code in instructor/patch.py
process_response(response, *, response_model, stream, validation_context=None, strict=None, mode=Mode.FUNCTIONS)
¶
Processes a OpenAI response with the response model, if available. It can use validation_context
and strict
to validate the response via the pydantic model
Parameters:
Name | Type | Description | Default |
---|---|---|---|
response | ChatCompletion | The response from OpenAI's API | required |
response_model | BaseModel | The response model to use for parsing the response | required |
stream | bool | Whether the response is a stream | required |
validation_context | dict | The validation context to use for validating the response. Defaults to None. | None |
strict | bool | Whether to use strict json parsing. Defaults to None. | None |
Source code in instructor/patch.py
process_response_async(response, *, response_model, stream, validation_context=None, strict=None, mode=Mode.FUNCTIONS)
async
¶
Processes a OpenAI response with the response model, if available. It can use validation_context
and strict
to validate the response via the pydantic model
Parameters:
Name | Type | Description | Default |
---|---|---|---|
response | ChatCompletion | The response from OpenAI's API | required |
response_model | BaseModel | The response model to use for parsing the response | required |
stream | bool | Whether the response is a stream | required |
validation_context | dict | The validation context to use for validating the response. Defaults to None. | None |
strict | bool | Whether to use strict json parsing. Defaults to None. | None |
Source code in instructor/patch.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, allow_override=False, model='gpt-3.5-turbo', temperature=0, openai_client=None)
¶
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) | None |
Source code in instructor/dsl/validators.py
openai_moderation(client=None)
¶
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
CitationMixin
¶
Bases: BaseModel
Helpful mixing that can use validation_context={"context": context}
in from_response
to find the span of the substring_phrase in the context.
Usage¶
from pydantic import BaseModel, Field
from instructor import CitationMixin
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")
context = "Betty was a student. Jason was a student. Jason is 20 years old"
user = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{
"role": "user",
"content": "Extract jason from {context}",
},
response_model=User,
validation_context={"context": context},
]
)
for quote in user.substring_quotes:
assert quote in context
print(user.model_dump())
Result¶
{
"name": "Jason Liu",
"age": 20,
"role": "student",
"substring_quotes": [
"Jason was a student",
"Jason is 20 years old",
]
}
Source code in instructor/dsl/citation.py
validate_sources(info)
¶
For each substring_phrase, find the span of the substring_phrase in the context. If the span is not found, remove the substring_phrase from the list.
Source code in instructor/dsl/citation.py
MultiTask(subtask_class, name=None, description=None)
¶
Dynamically create a MultiTask 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 MultiTask
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 = MultiTask(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/multitask.py
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 |
|
MaybeBase
¶
Bases: BaseModel
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
Mode
¶
Bases: Enum
The mode to use for patching the client
Source code in instructor/function_calls.py
OpenAISchema
¶
Bases: BaseModel
Augments a Pydantic model with OpenAI's schema for function calling
This class augments a Pydantic model with OpenAI's schema for function calling. The schema is generated from the model's signature and docstring. The schema can be used to validate the response from OpenAI's API and extract the function call.
Usage¶
from instructor import OpenAISchema
class User(OpenAISchema):
name: str
age: int
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{
"content": "Jason is 20 years old",
"role": "user"
}],
functions=[User.openai_schema],
function_call={"name": User.openai_schema["name"]},
)
user = User.from_response(completion)
print(user.model_dump())
Result¶
Source code in instructor/function_calls.py
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 |
|
openai_schema
classmethod
property
¶
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 |
from_response(completion, validation_context=None, strict=None, mode=Mode.FUNCTIONS, stream_multitask=False)
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 |
validation_context | dict | The validation context to use for validating the response | None |
strict | bool | Whether to use strict json parsing | None |
mode | Mode | The openai completion mode | FUNCTIONS |
stream_multitask | bool | Whether to stream a multitask response | False |
Returns:
Name | Type | Description |
---|---|---|
cls | OpenAISchema | An instance of the class |
Source code in instructor/function_calls.py
from_response_async(completion, validation_context=None, strict=None, mode=Mode.FUNCTIONS, stream_multitask=False)
async
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 |
validation_context | dict | The validation context to use for validating the response | None |
strict | bool | Whether to use strict json parsing | None |
mode | Mode | The openai completion mode | FUNCTIONS |
stream_multitask | bool | Whether to stream a multitask response | False |
Returns:
Name | Type | Description |
---|---|---|
cls | OpenAISchema | An instance of the class |