Instructor is a Python framework for extracting structured outputs from Large Language Models (LLMs). It uses Pydantic models to define the expected output structure and ensures type-safe, validated responses.
Type-Safe Structured Outputs: Instructor leverages Pydantic models to define expected output schemas, ensuring type safety and automatic validation of LLM responses. This eliminates the need for manual parsing and reduces errors in production applications.
Automatic Validation and Error Handling: Built-in validation mechanisms automatically retry failed requests and provide detailed error messages when LLM outputs don’t match the expected schema. This makes applications more robust and reliable in production environments.
Support for Complex Data Structures: Instructor supports nested models, lists, enums, and other complex Pydantic types, enabling extraction of sophisticated data structures from natural language. It also supports streaming responses for real-time applications and partial extraction scenarios.
Before integrating Instructor with TrueFoundry, ensure you have:
TrueFoundry Account: Create a TrueFoundry account with at least one model provider and generate a Personal Access Token by following the instructions in Generating Tokens. For a quick setup guide, see our Gateway Quick Start
Instructor Installation: Install Instructor using pip: pip install instructor
OpenAI Library: Install the OpenAI Python library: pip install openai
Pydantic: Install Pydantic for data validation: pip install pydantic
Step 2: Configure Instructor with TrueFoundry Gateway
Get your TrueFoundry Gateway API key, base URL, and model name from the unified code snippet in your TrueFoundry playground:
Here’s how to configure Instructor to use TrueFoundry’s AI Gateway:
Copy
Ask AI
import instructorfrom pydantic import BaseModelfrom openai import OpenAI# Configure OpenAI client to use TrueFoundry Gatewayclient = OpenAI( api_key="your-truefoundry-api-key", # Your TrueFoundry Personal Access Token base_url="your-truefoundry-base-url", # Your TrueFoundry Gateway URL)# Patch the client with Instructorinstructor_client = instructor.from_openai(client)# Define your Pydantic model for structured outputclass User(BaseModel): name: str age: int email: str# Extract structured datauser_info = instructor_client.chat.completions.create( model="openai-main/gpt-4o", # Your TrueFoundry model ID response_model=User, messages=[ {"role": "user", "content": "Extract user information: John Doe is 30 years old and his email is john@example.com"} ],)print(f"Name: {user_info.name}")print(f"Age: {user_info.age}")print(f"Email: {user_info.email}")