from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.openai import OpenAIProvider
import os
import json
from dotenv import load_dotenv
load_dotenv()
api_key = os.environ.get("GRAVIXLAYER_API_KEY")
# Create the model with OpenAIProvider
model = OpenAIChatModel(
"meta-llama/llama-3.1-8b-instruct",
provider=OpenAIProvider(
base_url="https://api.gravixlayer.com/v1/inference",
api_key=api_key
)
)
# No structured output - just get plain text and parse it yourself
agent = Agent(model=model)
result = agent.run_sync(
'Extract name and age from: John Doe, 34 years old. '
'Return ONLY a JSON object with "name" and "age" fields, nothing else.'
)
# Try to parse as JSON
try:
# Sometimes models wrap JSON in markdown code blocks
output_text = result.output.strip()
if output_text.startswith('```'):
# Remove markdown code block markers
output_text = output_text.split('```')[1]
if output_text.startswith('json'):
output_text = output_text[4:]
output_text = output_text.strip()
data = json.loads(output_text)
print("Parsed data:", data)
print(f"Name: {data['name']}, Age: {data['age']}")
except json.JSONDecodeError as e:
print(f"Failed to parse JSON: {e}")
print("You may need to adjust the prompt or parse the response differently")