Skip to main content

This package provides integration between Pydantic AI and OpenRouter, allowing you to use any model available on OpenRouter with the Pydantic AI framework. The implementation leverages the OpenAI-compatible API provided by OpenRouter.

Project description

OpenRouter Agent for Pydantic AI

A Python library that extends the Pydantic AI framework to support OpenRouter models.

Table of Contents

Overview

This package provides integration between Pydantic AI and OpenRouter, allowing you to use any model available on OpenRouter with the Pydantic AI framework. The implementation leverages the OpenAI-compatible API provided by OpenRouter.

Installation

# Install from the repository in editable mode to make changes
pip install -e .

# Or you can install through PyPi
pip install openrouter-agent

You'll also need to set up your OpenRouter API key. You can either:

  1. Set the OPENROUTER_API_KEY environment variable
  2. Pass the API key directly when initializing the agent

Configuring Your API Key via Environment Variable

Using an environment variable (OPENROUTER_API_KEY) is the recommended way to provide your API key securely. Here’s how you can set it:

Method 1: Using a .env File (Recommended for Projects)

This method keeps your key associated with your project without hardcoding it.

  1. Create or Copy: In your project's main directory, create a file named .env. If your project includes a .env-sample or .env.example file, you can copy it to .env.

  2. Add Your Key: Open the .env file and add the following line, replacing your_actual_api_key with the key you generated on OpenRouter Keys:

    OPENROUTER_API_KEY=your_actual_api_key
    
  3. Load the Variable: For your Python code to access this variable, you usually need a library like python-dotenv. Install it (pip install python-dotenv) and load it early in your script:

    from dotenv import load_dotenv
    load_dotenv()
    # Now os.getenv("OPENROUTER_API_KEY") or libraries that check env vars will find it.
    

    (Note: Some frameworks or tools might load .env files automatically.)

Method 2: Setting Temporarily in Your Terminal Session

This is useful for quick tests but needs to be done every time you open a new terminal session.

  1. Get Your Key: Copy your API key from OpenRouter Keys.

  2. Run the Command: Execute the command specific to your terminal, replacing your_actual_api_key with your key:

    • Linux, macOS, Git Bash (or other sh-like shells):

      export OPENROUTER_API_KEY='your_actual_api_key'
      
    • Windows Command Prompt (cmd.exe):

      set OPENROUTER_API_KEY=your_actual_api_key
      
    • Windows PowerShell:

      $env:OPENROUTER_API_KEY = 'your_actual_api_key'
      
  3. Run Your Code: Now you can run your Python script or the openrouter-agent CLI command from the same terminal window.

Important: Avoid committing your .env file (if it contains secrets) to version control like Git. Add .env to your .gitignore file.

Usage

Command Line Interface

The package includes a command-line interface (CLI) that allows you to generate and execute shell commands:

# Install the package with CLI support
pip install .

# Generate a command without executing it (copies to clipboard)
openrouter-agent query "show me all .txt files in the current directory"

# Generate and execute a command
openrouter-agent execute "show me all .txt files in the current directory"

Or run directly with Python:

# Generate a command without executing it (copies to clipboard)
python src/cli.py query "show me all .txt files in the current directory"

# Generate and execute a command
python src/cli.py execute "show me all .txt files in the current directory"

Python API Example

from openrouter_agent import Agent

# Initialize with default settings (uses openrouter/quasar-alpha model)
agent = Agent()

# Run a simple completion
result = agent.run("What is the capital of France?")
print(result)

You can also import the specific classes if needed:

from openrouter_agent import OpenRouterAgent, OpenRouterModel

Custom Configuration

from openrouter_agent import Agent

# Initialize with custom settings
agent = Agent(
    agent_name="my-custom-agent",
    openrouter_model_name="anthropic/claude-3-opus-20240229",
    temp=0.7,
    max_result_retries=5,
    openrouter_api_key="your-api-key-here"  # Or use environment variable
)

# Use the agent
result = agent.run("Explain quantum computing in simple terms.")
print(result)

Class Reference

OpenRouterModel

The OpenRouterModel class inherits from OpenAIModel and configures it to work with OpenRouter:

OpenRouterModel(
    openrouter_model_name: str = "openrouter/quasar-alpha",
    openrouter_url: str = "https://openrouter.ai/api/v1",
    openrouter_api_key: Optional[str] = os.getenv("OPENROUTER_API_KEY")
)

OpenRouterAgent

The OpenRouterAgent class inherits from Pydantic AI's Agent class and uses OpenRouterModel for completions:

OpenRouterAgent(
    agent_name: str = uuid.uuid4().hex,  # Auto-generates a UUID if not provided
    openrouter_model_name: str = "openrouter/quasar-alpha",
    temp: float = 0.1,
    max_result_retries: int = 10,
    openrouter_url: str = "https://openrouter.ai/api/v1",
    openrouter_api_key: Optional[str] = os.getenv("OPENROUTER_API_KEY"),
    instrument: bool = True,
    **kwargs: Any  # Additional arguments passed to the Agent constructor
)

Environment Variables

  • OPENROUTER_API_KEY: Your OpenRouter API key

Available Models

You can use any model available on OpenRouter by specifying its identifier in the openrouter_model_name parameter. Some popular options include:

  • openrouter/quasar-alpha (default)
  • anthropic/claude-3-opus-20240229
  • anthropic/claude-3-sonnet-20240229
  • meta-llama/llama-3-70b-instruct

Check the OpenRouter documentation for a complete list of available models.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

openrouter_agent-0.1.0.tar.gz (11.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

openrouter_agent-0.1.0-py3-none-any.whl (11.5 kB view details)

Uploaded Python 3

File details

Details for the file openrouter_agent-0.1.0.tar.gz.

File metadata

  • Download URL: openrouter_agent-0.1.0.tar.gz
  • Upload date:
  • Size: 11.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.9.21

File hashes

Hashes for openrouter_agent-0.1.0.tar.gz
Algorithm Hash digest
SHA256 66b2434f569f5c0a0b092e588667333dda5e607ca128c107b9504aba07bf0262
MD5 fd68c49ac0ad0bfce542ed89bfdfc8b1
BLAKE2b-256 498383b8ca68cb6ba884fcff6673900d3c35cf840f14f44476752bab4e5d5a2e

See more details on using hashes here.

File details

Details for the file openrouter_agent-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for openrouter_agent-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5fa30edccea59c6fee0e51e19275680d6274ef47ac7853098184e9a343607b46
MD5 dd407913b8c508bbe62ebc674001ddfd
BLAKE2b-256 7f8ec7adcacc767985ddec5348ec38bc1c25ce238689c1af54ab92030e946eb6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page