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
- Installation
- Configuring Your API Key via Environment Variable
- Usage
- Class Reference
- Environment Variables
- Available Models
- License
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:
- Set the
OPENROUTER_API_KEYenvironment variable - 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.
-
Create or Copy: In your project's main directory, create a file named
.env. If your project includes a.env-sampleor.env.examplefile, you can copy it to.env. -
Add Your Key: Open the
.envfile and add the following line, replacingyour_actual_api_keywith the key you generated on OpenRouter Keys:OPENROUTER_API_KEY=your_actual_api_key
-
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
.envfiles 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.
-
Get Your Key: Copy your API key from OpenRouter Keys.
-
Run the Command: Execute the command specific to your terminal, replacing
your_actual_api_keywith 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'
-
-
Run Your Code: Now you can run your Python script or the
openrouter-agentCLI 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:freegoogle/gemini-2.0-flash-exp:freegoogle/gemini-flash-1.5-8b-expmistralai/mistral-small-3.1-24b-instruct:free
Check the OpenRouter documentation for a complete list of available models.
License
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
11fdee4449a1701035d1c2d00d2f61ac599f3853e8a7cdacddc58680755ea18f
|
|
| MD5 |
a23a73b1596f9237f7cfc20821bdb16a
|
|
| BLAKE2b-256 |
c0848bc2d428838ba3995b8d179757d8b6a9f2af2e8b674a2fe63a4a90389783
|
File details
Details for the file openrouter_agent-0.1.3-py3-none-any.whl.
File metadata
- Download URL: openrouter_agent-0.1.3-py3-none-any.whl
- Upload date:
- Size: 12.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.22
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7dc09c04c5020749d1961c31d1fd4513f9ba8eb9bc5e98ab8cec12c442b739a7
|
|
| MD5 |
2c7119f3e0b740806ffa9d0eecf59fdb
|
|
| BLAKE2b-256 |
3c2fe52a460f2b7d994a8989b6a038e51597c309f9909d05b8fb79ca98f0f7d1
|