Add an Example File
Creates a standalone runnable example in examples/.
Before Starting
Ask the user:
- Topic / use case (e.g. "medical record extraction", "product review analysis")
- Extraction method —
extract_with_model, stepwise_extract_with_model, extract_and_jsonify, extract_from_data, or render_output
- Provider/model — e.g.
openai/gpt-4o, moonshot/kimi-k2-0905-preview, ollama/llama3.1:8b
Two Example Styles
Provider example (e.g. moonshot_example.py, grok_example.py)
Shows extract_and_jsonify with a specific provider. Two sections:
- Default instruction with the provider's primary model
- Custom instruction with the same or a different model
Use-case example (e.g. medical_record_example.py, resume_cv_example.py)
Shows extraction for a specific domain using Pydantic models.
Conventions
- File:
examples/{descriptive_name}_example.py
- Standalone — no test framework imports
- Always print extracted result and usage metadata (prompt_tokens, completion_tokens, total_tokens, cost, model_name)
- Realistic sample text, not lorem ipsum
- Under 100 lines when possible
Provider Example Template
"""
Example: Using extract_and_jsonify with {Provider}.
This script demonstrates:
1. Initializing the {Provider} driver manually (ignoring AI_PROVIDER).
2. Extracting structured information from text using a JSON schema.
3. Overriding the {Provider} model per call with `model_name`.
4. Running both a default extraction and a custom-instruction extraction.
Setup:
export {PROVIDER}_API_KEY="your-key-here"
# or add to .env file
"""
import json
from prompture import extract_and_jsonify
# 1. Define the raw text
text = "Maria is 32 years old and works as a software developer in New York. She loves hiking and photography."
# 2. Define the JSON schema
json_schema = {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "integer"},
"profession": {"type": "string"},
"city": {"type": "string"},
"hobbies": {"type": "array", "items": {"type": "string"}},
},
}
# === FIRST EXAMPLE: Default instruction with {Model} ===
print("Extracting information into JSON with default instruction...")
result = extract_and_jsonify(
text=text,
json_schema=json_schema,
model_name="{provider}/{model}", # explicitly select model
)
json_output = result["json_string"]
json_object = result["json_object"]
usage = result["usage"]
print("\nRaw JSON output from model:")
print(json_output)
print("\nSuccessfully parsed JSON:")
print(json.dumps(json_object, indent=2))
print("\n=== TOKEN USAGE STATISTICS ===")
print(f"Prompt tokens: {usage['prompt_tokens']}")
print(f"Completion tokens: {usage['completion_tokens']}")
print(f"Total tokens: {usage['total_tokens']}")
print(f"Cost: ${usage['cost']:.6f}")
print(f"Model used: {usage['model_name']}")
# === SECOND EXAMPLE: Custom instruction with {Alt Model} ===
print("\n\n=== SECOND EXAMPLE - CUSTOM INSTRUCTION & DIFFERENT MODEL ===")
print("Extracting information with custom instruction...")
custom_result = extract_and_jsonify(
text=text,
json_schema=json_schema,
instruction_template="Parse the biographical details from this text:",
model_name="{provider}/{alt_model}", # override model here
)
custom_json_output = custom_result["json_string"]
custom_json_object = custom_result["json_object"]
custom_usage = custom_result["usage"]
print("\nRaw JSON output with custom instruction:")
print(custom_json_output)
print("\nSuccessfully parsed JSON (custom instruction):")
print(json.dumps(custom_json_object, indent=2))
print("\n=== TOKEN USAGE STATISTICS (Custom Template) ===")
print(f"Prompt tokens: {custom_usage['prompt_tokens']}")
print(f"Completion tokens: {custom_usage['completion_tokens']}")
print(f"Total tokens: {custom_usage['total_tokens']}")
print(f"Cost: ${custom_usage['cost']:.6f}")
print(f"Model used: {custom_usage['model_name']}")
Use-Case Example Template
"""
Example: {Title}
This example demonstrates:
1. {Feature 1}
2. {Feature 2}
Requirements:
pip install prompture
# Set up provider credentials in .env
"""
import json
from pydantic import BaseModel, Field
from prompture import extract_with_model
# 1. Define the output model
class MyModel(BaseModel):
field1: str = Field(description="...")
field2: int = Field(description="...")
# 2. Input text
text = """
Realistic sample text here.
"""
# 3. Extract
MODEL = "openai/gpt-4o-mini"
result = extract_with_model(
model_cls=MyModel,
text=text,
model_name=MODEL,
)
# 4. Results
print("Extracted model:")
print(result["model"])
print()
print("Usage metadata:")
print(json.dumps(result["usage"], indent=2))
Rules
- Import only from
prompture public API
- Include docstring header listing features and setup requirements
- If provider-specific, mention the env var in the docstring
- Check available models for the provider:
python -c "from prompture.model_rates import get_all_provider_models; print(get_all_provider_models('{models_dev_name}')[:10])"
1---2name: add-example3description: Create a new Prompture usage example script. Follows project conventions for file naming, section structure, docstrings, and output formatting. Use when demonstrating extraction use cases or provider integrations.4---56# Add an Example File78Creates a standalone runnable example in `examples/`.910## Before Starting1112Ask the user:13- **Topic / use case** (e.g. "medical record extraction", "product review analysis")14- **Extraction method** — `extract_with_model`, `stepwise_extract_with_model`, `extract_and_jsonify`, `extract_from_data`, or `render_output`15- **Provider/model** — e.g. `openai/gpt-4o`, `moonshot/kimi-k2-0905-preview`, `ollama/llama3.1:8b`1617## Two Example Styles1819### Provider example (e.g. `moonshot_example.py`, `grok_example.py`)2021Shows `extract_and_jsonify` with a specific provider. Two sections:221. Default instruction with the provider's primary model232. Custom instruction with the same or a different model2425### Use-case example (e.g. `medical_record_example.py`, `resume_cv_example.py`)2627Shows extraction for a specific domain using Pydantic models.2829## Conventions3031- File: `examples/{descriptive_name}_example.py`32- Standalone — no test framework imports33- Always print extracted result and usage metadata (prompt_tokens, completion_tokens, total_tokens, cost, model_name)34- Realistic sample text, not lorem ipsum35- Under 100 lines when possible3637## Provider Example Template3839```python40"""41Example: Using extract_and_jsonify with {Provider}.4243This script demonstrates:441. Initializing the {Provider} driver manually (ignoring AI_PROVIDER).452. Extracting structured information from text using a JSON schema.463. Overriding the {Provider} model per call with `model_name`.474. Running both a default extraction and a custom-instruction extraction.4849Setup:50 export {PROVIDER}_API_KEY="your-key-here"51 # or add to .env file52"""5354import json5556from prompture import extract_and_jsonify5758# 1. Define the raw text59text = "Maria is 32 years old and works as a software developer in New York. She loves hiking and photography."6061# 2. Define the JSON schema62json_schema = {63 "type": "object",64 "properties": {65 "name": {"type": "string"},66 "age": {"type": "integer"},67 "profession": {"type": "string"},68 "city": {"type": "string"},69 "hobbies": {"type": "array", "items": {"type": "string"}},70 },71}7273# === FIRST EXAMPLE: Default instruction with {Model} ===74print("Extracting information into JSON with default instruction...")7576result = extract_and_jsonify(77 text=text,78 json_schema=json_schema,79 model_name="{provider}/{model}", # explicitly select model80)8182json_output = result["json_string"]83json_object = result["json_object"]84usage = result["usage"]8586print("\nRaw JSON output from model:")87print(json_output)8889print("\nSuccessfully parsed JSON:")90print(json.dumps(json_object, indent=2))9192print("\n=== TOKEN USAGE STATISTICS ===")93print(f"Prompt tokens: {usage['prompt_tokens']}")94print(f"Completion tokens: {usage['completion_tokens']}")95print(f"Total tokens: {usage['total_tokens']}")96print(f"Cost: ${usage['cost']:.6f}")97print(f"Model used: {usage['model_name']}")9899100# === SECOND EXAMPLE: Custom instruction with {Alt Model} ===101print("\n\n=== SECOND EXAMPLE - CUSTOM INSTRUCTION & DIFFERENT MODEL ===")102print("Extracting information with custom instruction...")103104custom_result = extract_and_jsonify(105 text=text,106 json_schema=json_schema,107 instruction_template="Parse the biographical details from this text:",108 model_name="{provider}/{alt_model}", # override model here109)110111custom_json_output = custom_result["json_string"]112custom_json_object = custom_result["json_object"]113custom_usage = custom_result["usage"]114115print("\nRaw JSON output with custom instruction:")116print(custom_json_output)117118print("\nSuccessfully parsed JSON (custom instruction):")119print(json.dumps(custom_json_object, indent=2))120121print("\n=== TOKEN USAGE STATISTICS (Custom Template) ===")122print(f"Prompt tokens: {custom_usage['prompt_tokens']}")123print(f"Completion tokens: {custom_usage['completion_tokens']}")124print(f"Total tokens: {custom_usage['total_tokens']}")125print(f"Cost: ${custom_usage['cost']:.6f}")126print(f"Model used: {custom_usage['model_name']}")127```128129## Use-Case Example Template130131```python132"""133Example: {Title}134135This example demonstrates:1361. {Feature 1}1372. {Feature 2}138139Requirements:140 pip install prompture141 # Set up provider credentials in .env142"""143144import json145146from pydantic import BaseModel, Field147148from prompture import extract_with_model149150# 1. Define the output model151class MyModel(BaseModel):152 field1: str = Field(description="...")153 field2: int = Field(description="...")154155# 2. Input text156text = """157Realistic sample text here.158"""159160# 3. Extract161MODEL = "openai/gpt-4o-mini"162163result = extract_with_model(164 model_cls=MyModel,165 text=text,166 model_name=MODEL,167)168169# 4. Results170print("Extracted model:")171print(result["model"])172print()173print("Usage metadata:")174print(json.dumps(result["usage"], indent=2))175```176177## Rules178179- Import only from `prompture` public API180- Include docstring header listing features and setup requirements181- If provider-specific, mention the env var in the docstring182- Check available models for the provider: `python -c "from prompture.model_rates import get_all_provider_models; print(get_all_provider_models('{models_dev_name}')[:10])"`