Skip to main content
A weather information bot built with PydanticAI that uses DuckDuckGo search to provide real-time weather forecasts. Demonstrates PydanticAI’s integration with Nebius AI and external tools.

Features

  • Real-time weather information using web search
  • DuckDuckGo search tool integration
  • Type-safe agent configuration
  • Custom model provider setup
  • Simple command-line interface

Prerequisites

Installation

1

Clone the repository

git clone https://github.com/Arindam200/awesome-ai-apps.git
cd starter_ai_agents/pydantic_starter
2

Install dependencies

pip install -r requirements.txt
3

Configure environment

Create a .env file and add your Nebius API key:
NEBIUS_API_KEY=your_api_key_here

Implementation

Model Configuration

Set up PydanticAI with a custom OpenAI-compatible provider:
main.py
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider
from pydantic_ai.common_tools.duckduckgo import duckduckgo_search_tool
import os
from dotenv import load_dotenv

load_dotenv()

# Set up the model with the user-provided API key
model = OpenAIModel(
    model_name='meta-llama/Meta-Llama-3.1-70B-Instruct',
    provider=OpenAIProvider(
        base_url='https://api.tokenfactory.nebius.com/v1',
        api_key=os.environ['NEBIUS_API_KEY']
    )
)

Agent Setup

Create the agent with search capabilities:
main.py
# Create the agent with a weather-focused prompt
agent = Agent(
    model=model,
    tools=[duckduckgo_search_tool()],
    system_prompt="You are a weather assistant. Use DuckDuckGo to find the current weather forecast for the requested city."
)

Running the Agent

main.py
city = "Kolkata"  # Change this to any city you like!

# Run the agent
result = agent.run_sync(f"What is the weather forecast for {city} today?")

# Display the result
print(f"Weather forecast for {city}:")
print(result.data)

Usage

Run the weather bot:
python main.py

Customize the City

Modify the city variable to check weather for different locations:
city = "New York"  # Any city worldwide
result = agent.run_sync(f"What is the weather forecast for {city} today?")

Example Queries

  • “What is the weather forecast for New York today?”
  • “What’s the temperature in London right now?”
  • “Will it rain in Tokyo tomorrow?”
  • “What’s the weather like in Sydney?”
  • “Show me the forecast for Paris”

Technical Details

Architecture

PydanticAI

Type-safe agent framework

Nebius AI

Meta-Llama-3.1-70B-Instruct model

DuckDuckGo

Web search tool for real-time data

OpenAI Provider

Compatible API integration

Model Provider

PydanticAI uses OpenAI-compatible providers:
OpenAIProvider(
    base_url='https://api.tokenfactory.nebius.com/v1',  # Nebius endpoint
    api_key=os.environ['NEBIUS_API_KEY']                # Your API key
)

Tool Integration

The agent uses PydanticAI’s built-in DuckDuckGo search tool:
from pydantic_ai.common_tools.duckduckgo import duckduckgo_search_tool

agent = Agent(
    model=model,
    tools=[duckduckgo_search_tool()],  # Add search capability
    system_prompt="..."
)

Extending the Agent

Add Custom Tools

from pydantic_ai import tool

@tool
def get_temperature_unit(country: str) -> str:
    """Get the preferred temperature unit for a country"""
    celsius_countries = ['uk', 'france', 'germany', 'india']
    return 'Celsius' if country.lower() in celsius_countries else 'Fahrenheit'

agent = Agent(
    model=model,
    tools=[duckduckgo_search_tool(), get_temperature_unit],
    system_prompt="You are a weather assistant."
)

Add Structured Output

from pydantic import BaseModel

class WeatherForecast(BaseModel):
    city: str
    temperature: float
    conditions: str
    humidity: int
    wind_speed: float

agent = Agent(
    model=model,
    tools=[duckduckgo_search_tool()],
    system_prompt="Extract weather information in structured format.",
    result_type=WeatherForecast
)

result = agent.run_sync(f"What is the weather in {city}?")
forecast = result.data  # Type: WeatherForecast

Make it Interactive

def main():
    print("Weather Bot - Ask me about weather in any city!")
    print("Type 'quit' to exit\n")
    
    while True:
        user_input = input("You: ").strip()
        
        if user_input.lower() == 'quit':
            print("Goodbye!")
            break
        
        if not user_input:
            continue
        
        result = agent.run_sync(user_input)
        print(f"\nBot: {result.data}\n")

if __name__ == "__main__":
    main()

Use Different Models

# Use a different Nebius model
model = OpenAIModel(
    model_name='Qwen/Qwen3-30B-A3B',  # Faster, smaller model
    provider=OpenAIProvider(
        base_url='https://api.tokenfactory.nebius.com/v1',
        api_key=os.environ['NEBIUS_API_KEY']
    )
)

Best Practices

  • Use larger models (70B+) for complex reasoning
  • Use smaller models (8B-30B) for faster responses
  • Test different models for your use case
  • Consider cost vs. performance tradeoffs
  • Be specific about the agent’s role
  • Mention available tools explicitly
  • Define expected output format
  • Include examples if needed
  • Use built-in tools when available
  • Keep custom tools focused and simple
  • Provide clear tool descriptions
  • Handle errors gracefully

Error Handling

try:
    result = agent.run_sync(f"What is the weather in {city}?")
    print(f"Weather: {result.data}")
except Exception as e:
    print(f"Error getting weather: {e}")
    print("Please check your API key and internet connection.")

Environment Variables

VariableDescriptionRequired
NEBIUS_API_KEYYour Nebius API keyYes

Next Steps

Advanced Agents

Build more complex PydanticAI agents

Structured Output

Work with structured data

Build docs developers (and LLMs) love