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="explanation_agent",
    system_prompt="You are a helpful assistant that explains complex topics in simple terms.",
    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_sync("Explain quantum computing in simple terms.")
print(result.data)

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 free options include:

Note: You must use a model that supports tools to use the cli application, the following free models all do.

  • openrouter/quasar-alpha (default)
  • google/gemini-2.5-pro-exp-03-25:free
  • google/gemini-2.0-flash-exp:free
  • google/gemini-flash-1.5-8b-exp
  • mistralai/mistral-small-3.1-24b-instruct:free

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.3.tar.gz (12.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.3-py3-none-any.whl (12.7 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for openrouter_agent-0.1.3.tar.gz
Algorithm Hash digest
SHA256 11fdee4449a1701035d1c2d00d2f61ac599f3853e8a7cdacddc58680755ea18f
MD5 a23a73b1596f9237f7cfc20821bdb16a
BLAKE2b-256 c0848bc2d428838ba3995b8d179757d8b6a9f2af2e8b674a2fe63a4a90389783

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for openrouter_agent-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 7dc09c04c5020749d1961c31d1fd4513f9ba8eb9bc5e98ab8cec12c442b739a7
MD5 2c7119f3e0b740806ffa9d0eecf59fdb
BLAKE2b-256 3c2fe52a460f2b7d994a8989b6a038e51597c309f9909d05b8fb79ca98f0f7d1

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