The provided files don't directly address using Formatron with the specified schema FieldsExtraction(BaseModel): Investment: Union[float, str, Dict]. However, they offer highly relevant examples that demonstrate how to define schemas and use Formatron's FormatterBuilder and create_formatter_filter to structure LLM output as JSON. We can adapt these examples to achieve the desired outcome.
python
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from exllamav2 import ExLlamaV2, ExLlamaV2Config, ExLlamaV2Cache, ExLlamaV2Tokenizer
from exllamav2.generator import ExLlamaV2DynamicGenerator
from formatron.schemas.pydantic import ClassSchema
from formatron.integrations.exllamav2 import create_formatter_filter
from formatron.formatter import FormatterBuilder
from pydantic import BaseModel
from typing import Union, Dict
# Define your Pydantic model using BaseModel, not ClassSchema
class FieldsExtraction(BaseModel):
Investment: Union[float, str, Dict]
def create_investment_json_formatter():
f = FormatterBuilder()
# Use the correct model type (FieldsExtraction) and capture name
f.append_line(f"{f.json(FieldsExtraction, capture_name='investment_json')}")
return f
# ... (Load your model, tokenizer, and generator as in the examples)
formatter = create_investment_json_formatter()
# Example prompt
prompt = "The investment amount is $10000. Another investment is 'pending'. The final investment is {'amount': 5000, 'currency': 'USD'}."
filters = [[create_formatter_filter(model, tokenizer, formatter)]]
outputs = generator.generate(
prompt = [prompt], # Prompt should be a list even for single generation
filters = filters,
max_new_tokens = 300, # Adjust as needed
add_bos = True,
stop_conditions = [tokenizer.eos_token_id],
completion_only = True
)
# Process and parse the JSON output
import json
try:
# Extract the JSON string, handling potential variations in formatting
json_string = outputs[0]
json_start = json_string.find('{')
if json_start != -1:
json_string = json_string[json_start:]
parsed_investment = FieldsExtraction.model_validate_json(json_string)
print(parsed_investment) # or print(parsed_investment.model_dump_json(indent=4)) for pretty printing.
else:
print("No valid JSON found in the output.")
except json.JSONDecodeError:
print("Invalid JSON output:")
print(outputs[0])
Key changes and explanations:
BaseModel, not ClassSchema: Use pydantic.BaseModel to define the FieldsExtraction schema, as ClassSchema is specific to Formatron's internal representation.
Correct Model in Formatter: Ensure f.json() uses FieldsExtraction and the capture name matches the field in the schema (e.g., "investment_json").
Prompt as List: Even for single generations, the prompt argument to generator.generate should be a list.
JSON Parsing: The LLM output may require cleaning and parsing. The example code now includes error handling and extraction of the JSON string from the output. Using FieldsExtraction.model_validate_json conveniently parses the JSON string directly into the Pydantic model while automatically handling data type validation as defined in the schema.
Example Prompt: The included example prompt provides diverse investment formats (float, string, dict) to demonstrate the flexibility of the Union type in your schema. Replace this with your actual prompt.
By adapting the example code in this way, you can effectively utilize Formatron to constrain LLM output and parse it into a JSON structure conforming to your specific FieldsExtraction schema. Remember to install the necessary libraries (exllamav2, formatron, pydantic). Also, adjust max_new_tokens based on the expected length of the JSON output. The error handling helps address potential issues with the LLM not producing valid JSON.