xiaohongshu
xiaohongshu
instructor
Structured outputs with Instructor. Extract typed data from LLMs using Pydantic models and validation. Use for data extraction, structured generation, and type-safe LLM responses.
Full skill instructions
Expert guidance for structured LLM outputs with Pydantic validation.
Use this skill when:
pip install instructor
import instructor
from pydantic import BaseModel
from openai import OpenAI
# Patch OpenAI client
client = instructor.from_openai(OpenAI())
class User(BaseModel):
name: str
age: int
# Extract structured data
user = client.chat.completions.create(
model="gpt-4o",
response_model=User,
messages=[
{"role": "user", "content": "John is 25 years old"}
]
)
print(user) # User(name='John', age=25)
from pydantic import BaseModel, Field
from typing import Optional, List
from enum import Enum
class Priority(str, Enum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
class Task(BaseModel):
title: str = Field(description="Task title")
description: str = Field(description="Detailed description")
priority: Priority = Field(description="Task priority level")
due_date: Optional[str] = Field(None, description="Due date in YYYY-MM-DD format")
tags: List[str] = Field(default_factory=list, description="Related tags")
task = client.chat.completions.create(
model="gpt-4o",
response_model=Task,
messages=[
{"role": "user", "content": "Create a task for reviewing the Q4 report, high priority, due next Friday"}
]
)
from pydantic import BaseModel
from typing import List
class Address(BaseModel):
street: str
city: str
country: str
postal_code: str
class Person(BaseModel):
name: str
email: str
address: Address
phone_numbers: List[str]
person = client.chat.completions.create(
model="gpt-4o",
response_model=Person,
messages=[
{"role": "user", "content": """
Extract: John Smith, [email protected], lives at 123 Main St,
New York, USA 10001. Phone: 555-1234, 555-5678
"""}
]
)
from pydantic import BaseModel, field_validator
from typing import List
class SearchQuery(BaseModel):
query: str
filters: List[str]
@field_validator('query')
@classmethod
def query_not_empty(cls, v):
if not v.strip():
raise ValueError("Query cannot be empty")
return v.strip()
@field_validator('filters')
@classmethod
def validate_filters(cls, v):
valid = ["date", "author", "category"]
for f in v:
if f not in valid:
raise ValueError(f"Invalid filter: {f}")
return v
from pydantic import BaseModel, model_validator
class DateRange(BaseModel):
start_date: str
end_date: str
@model_validator(mode='after')
def validate_dates(self):
if self.start_date > self.end_date:
raise ValueError("Start date must be before end date")
return self
from instructor import from_openai
from tenacity import retry, stop_after_attempt
client = from_openai(
OpenAI(),
mode=instructor.Mode.TOOLS
)
# Automatic retries on validation failure
user = client.chat.completions.create(
model="gpt-4o",
response_model=User,
max_retries=3,
messages=[{"role": "user", "content": "Extract user info"}]
)
from instructor import from_openai, Partial
from pydantic import BaseModel
from typing import List
class Report(BaseModel):
title: str
sections: List[str]
summary: str
client = from_openai(OpenAI())
# Stream partial results
for partial in client.chat.completions.create_partial(
model="gpt-4o",
response_model=Report,
messages=[{"role": "user", "content": "Write a report on AI trends"}],
):
print(partial) # Partial[Report] with available fields
from instructor import from_openai
from pydantic import BaseModel
from typing import Iterable
class Product(BaseModel):
name: str
price: float
category: str
client = from_openai(OpenAI())
products: Iterable[Product] = client.chat.completions.create_iterable(
model="gpt-4o",
response_model=Product,
messages=[
{"role": "user", "content": """
Extract products:
- iPhone 15 Pro: $999, Electronics
- Nike Air Max: $150, Footwear
- MacBook Pro: $2499, Electronics
"""}
]
)
for product in products:
print(product)
import instructor
from anthropic import Anthropic
client = instructor.from_anthropic(Anthropic())
user = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
response_model=User,
messages=[{"role": "user", "content": "John is 25"}]
)
import instructor
from openai import OpenAI
client = instructor.from_openai(
OpenAI(base_url="http://localhost:11434/v1", api_key="ollama"),
mode=instructor.Mode.JSON
)
user = client.chat.completions.create(
model="llama3.1",
response_model=User,
messages=[{"role": "user", "content": "John is 25"}]
)
import instructor
import litellm
client = instructor.from_litellm(litellm.completion)
user = client(
model="gpt-4o",
response_model=User,
messages=[{"role": "user", "content": "John is 25"}]
)
from pydantic import BaseModel, Field
class Reasoning(BaseModel):
chain_of_thought: str = Field(
description="Step by step reasoning before the answer"
)
answer: str = Field(description="Final answer")
result = client.chat.completions.create(
model="gpt-4o",
response_model=Reasoning,
messages=[
{"role": "user", "content": "What is 25 * 47?"}
]
)
print(result.chain_of_thought)
print(result.answer)
from enum import Enum, auto
class Sentiment(str, Enum):
POSITIVE = "positive"
NEGATIVE = "negative"
NEUTRAL = "neutral"
class SentimentAnalysis(BaseModel):
text: str
sentiment: Sentiment
confidence: float = Field(ge=0, le=1)
analysis = client.chat.completions.create(
model="gpt-4o",
response_model=SentimentAnalysis,
messages=[
{"role": "user", "content": "Analyze: 'I love this product!'"}
]
)
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience