Prerequisites
- A SambaCloud account
- A SambaNova API key
- Python 3.10 or higher
- Pydantic v2. Instructor requires
pydantic>=2.8, so Pydantic v1 syntax such asclass Configand.dict()does not work in these examples - A model that supports the mode you choose. See Choose a mode
- Familiarity with Pydantic is helpful but not required
Instructor’s package metadata claims Python 3.9 support, but it does not work on 3.9. On 3.9 the install succeeds and
instructor.from_openai() then fails with TypeError: Unable to evaluate type annotation 'str | Path', because Instructor’s own modules use | union syntax that Pydantic evaluates at runtime. macOS ships 3.9 and exposes it as python3 rather than python. Check with python3 --version and install a supported version with pyenv, uv, or brew install python@3.12 if needed.Installation
Create and activate a virtual environment, then install Instructor:openai and pydantic, so no extra is required.
Then set your API key. The examples on this page read it from the SAMBANOVA_API_KEY environment variable.
The examples on this page were verified against
instructor 1.15.4, openai 2.48.0, and pydantic 2.13.4. Instructor moved some import paths in 1.11, so if you pin an older release, check the Instructor documentation for the equivalent names.Basic usage
The following code demonstrates how to use the SambaCloud API with Instructor to generate structured output from theMeta-Llama-3.3-70B-Instruct model. A User schema is defined using Pydantic, requiring the model to return a response with a name (string) and age (integer). Instructor handles the response validation and parsing, resulting in a structured Python object.
Choose a mode
instructor.from_openai() accepts a mode argument that controls how Instructor asks the model for structured data. The example above does not pass one, so it uses the default, Mode.TOOLS. The mode you pick must match what your chosen model supports, and picking the wrong one is the most common cause of failures on this page.
Meta-Llama-3.3-70B-Instruct, used throughout this page, supports function calling, so the default Mode.TOOLS works without any extra configuration. For the full list of SambaCloud models that support function calling, JSON schema, and JSON mode, see Function calling and JSON mode. For the current model IDs and context lengths, see SambaCloud models.
To pick a mode explicitly, import Mode and pass it:
Async usage
This code also uses SambaCloud API with Instructor to enforce structured output. The result is fetched asynchronously and printed, outputtingUser(name='Ivan', age=28).
asyncio.run() fails with RuntimeError: asyncio.run() cannot be called from a running event loop inside Jupyter or any notebook, because the notebook already runs an event loop. Use user = await get_user() in a notebook cell instead.Extract a nested schema
Real extraction tasks rarely fit a two-field model. The example below pulls a support ticket out of a raw email, and shows the parts that make Instructor reliable in production:Field(description=...)tells the model what each field means. This is the single most effective way to raise extraction accuracy.- An
Enumconstrains a field to a fixed set of values. Optional[str]with a default lets the model omit a value it cannot find, instead of inventing one.- A
field_validatorenforces a rule Pydantic types cannot express. When it raises, Instructor sends the error back to the model and retries.
Handle validation failures
When the model returns something that does not satisfy your schema, Instructor does not hand you the broken output. It appends the validation error to the conversation and asks the model again, up tomax_retries times. max_retries defaults to 3 on client.chat.completions.create().
If every attempt fails, Instructor raises InstructorRetryException. Catch it to inspect what the model actually produced instead of guessing:
Import exceptions from
instructor.core. The older instructor.exceptions path still works but emits a DeprecationWarning as of Instructor 1.11.- Add or sharpen
Field(description=...)on the fields that failed. Ambiguous field names are the most common cause. - Loosen the schema. Make a field
Optionalif the source text genuinely may not contain it. Forcing the model to fill a field it cannot find guarantees retries. - Raise
max_retries. Useful when failures are intermittent rather than structural. - Switch models. A larger model handles deeply nested schemas more reliably. See SambaCloud models.
- Switch modes. If the model does not support function calling,
Mode.TOOLSnever succeeds no matter how many times it retries. See Choose a mode.
Next steps
- Explore an example notebook explaining how to create an email classification tool.
- Compare Instructor against the native SambaCloud approach in Function calling and JSON mode.
- Review the available model IDs in SambaCloud models.
Troubleshooting
InstructorRetryException: max retries exceeded
InstructorRetryException: max retries exceeded
The model’s output failed Pydantic validation on every attempt. Instructor retries automatically (
max_retries defaults to 3) and raises this once the final attempt fails, so the underlying validation error appears further down the traceback. Add Field(description=...) to your schema so the model knows what each field expects, raise max_retries, or try a more capable model. See Handle validation failures for how to inspect each failed attempt.The model answers in prose instead of returning an object
The model answers in prose instead of returning an object
The mode does not match the model.
instructor.from_openai() defaults to Mode.TOOLS, which requires the model to support function calling. If it does not, the model replies conversationally, validation fails every time, and you get InstructorRetryException. Switch to Mode.JSON or Mode.MD_JSON, or choose a model that supports function calling. See Choose a mode.KeyError: SAMBANOVA_API_KEY
KeyError: SAMBANOVA_API_KEY
Export the key before running:
export SAMBANOVA_API_KEY="your-key". Verify with echo $SAMBANOVA_API_KEY.ModuleNotFoundError: No module named 'instructor'
ModuleNotFoundError: No module named 'instructor'
Install with:
pip install instructor. If it was already installed, the virtual environment is not active: run source .venv/bin/activate and confirm the prompt shows (.venv).TypeError: Unable to evaluate type annotation 'str | Path'
TypeError: Unable to evaluate type annotation 'str | Path'
You are on Python 3.9. Instructor installs on 3.9, but its own modules use
| union syntax that requires 3.10, and Pydantic evaluates those annotations at runtime. import instructor succeeds, so the failure appears at instructor.from_openai() rather than at install time. Recreate the environment with Python 3.10 or higher.ValidationError: Input should be 'low', 'medium' or 'high'
ValidationError: Input should be 'low', 'medium' or 'high'
The model returned a value outside your
Enum. Add a Field(description=...) that spells out the allowed values and when to use each one. Instructor retries automatically, so this only surfaces as an error if every attempt fails.
