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. With TrueFoundry AI Gateway integration, you can make your Instructor pipelines production-ready with enhanced monitoring, cost tracking, and access controls.
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}")