Article
llmapi-integrationpythonmulti-llmautomation
Pi-AI: Unified LLM API
Integrate diverse Large Language Models (LLMs) effortlessly with Pi-AI's unified API. This Action Pack shows you how to install Pi-AI, configure providers with automatic model discovery, and seamlessly switch between models using a consistent API.
beginner5 min3 steps
The play
- Install Pi-AIInstall the `pi-ai` Python package using pip. This provides the core library for unified LLM interaction.
- Initialize LLMClient with Provider ConfigurationsInstantiate the `LLMClient`, providing your API keys for the desired LLM providers. Pi-AI automatically discovers available models and their optimal configurations.
- Interact with LLMs and Switch ModelsUse the `client.chat.completions.create` method to interact with any configured LLM. Easily switch models and providers by changing the `model` parameter, leveraging the consistent API structure.
Starter code
from pi_ai import LLMClient
# Replace with your actual API keys
OPENAI_API_KEY = "YOUR_OPENAI_KEY"
ANTHROPIC_API_KEY = "YOUR_ANTHROPIC_KEY"
client = LLMClient(
provider_config={
"openai": {"api_key": OPENAI_API_KEY},
"anthropic": {"api_key": ANTHROPIC_API_KEY}
}
)
# Example 1: Use an OpenAI model
response_gpt = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the capital of France?"}
]
)
print(f"OpenAI Response: {response_gpt.choices[0].message.content}")
# Example 2: Use an Anthropic model
response_claude = client.chat.completions.create(
model="claude-3-opus-20240229",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Tell me a fun fact about Paris."}
]
)
print(f"Anthropic Response: {response_claude.choices[0].message.content}")