97e91a83f3
Ruff / Ruff (push) Has been cancelled
Test / Core Tests (push) Has been cancelled
Test / Offline Coverage Tests (Python 3.10) (push) Has been cancelled
Test / Offline Coverage Tests (Python 3.11) (push) Has been cancelled
Test / Offline Coverage Tests (Python 3.12) (push) Has been cancelled
Test / Offline Coverage Tests (Python 3.13) (push) Has been cancelled
Test / Offline Coverage Tests (Python 3.9) (push) Has been cancelled
Test / Full Coverage (Python 3.11) (push) Has been cancelled
Test / Core Provider Tests (OpenAI) (push) Has been cancelled
Test / Core Provider Tests (Anthropic) (push) Has been cancelled
Test / Core Provider Tests (Google) (push) Has been cancelled
Test / Core Provider Tests (Other) (push) Has been cancelled
Test / Anthropic Tests (push) Has been cancelled
Test / Gemini Tests (push) Has been cancelled
Test / Google GenAI Tests (push) Has been cancelled
Test / Vertex AI Tests (push) Has been cancelled
Test / OpenAI Tests (push) Has been cancelled
Test / Writer Tests (push) Has been cancelled
Test / Auto Client Tests (push) Has been cancelled
ty / type-check (push) Has been cancelled
1.4 KiB
1.4 KiB
title, description
| title | description |
|---|---|
| Working with Decimal Types in Instructor | Learn how to use Python Decimal types for precise financial calculations and numeric data extraction with Instructor. |
See Also
- Types - Working with different data types
- Fields - Customizing field validation
- Field Validation - Field-level validation patterns
- Validation - Core validation concepts
Using Decimals
Extract precise decimal values for financial calculations using Python's Decimal type.
from decimal import Decimal
from pydantic import BaseModel, field_validator
import instructor
class Receipt(BaseModel):
item: str
price: Decimal
@field_validator('price', mode='before')
@classmethod
def parse_price(cls, v):
if isinstance(v, str):
return Decimal(v)
return v
client = instructor.from_provider("openai/gpt-4.1-mini")
receipt = client.create(
messages=[{"role": "user", "content": "Coffee costs $4.99"}],
response_model=Receipt,
)
print(f"Item: {receipt.item}")
print(f"Price: {receipt.price}") # Decimal('4.99')
print(f"Type: {type(receipt.price)}") # <class 'decimal.Decimal'>
The field_validator ensures string values from LLM responses are properly converted to Decimal objects for precise financial calculations.