How to Use the Provider Lookup Function in ai-agent-book: A Complete Guide
The provider lookup function in agentbook/providers/registry.py converts user-supplied provider names or aliases into fully-specified Provider dataclasses containing API endpoints, default models, and credential configuration.
The bojieli/ai-agent-book repository provides a unified interface for interacting with multiple LLM backends through its provider lookup function. This mechanism centralizes provider configuration, allowing developers to resolve ambiguous names like "moonshot" into canonical specifications with base URLs and authentication details. Understanding how to leverage this lookup system is essential for building robust AI agent applications that seamlessly switch between OpenAI-compatible providers.
Understanding the Provider Lookup Architecture
The provider lookup system consists of two core components: the registry module that handles name resolution and the models module that defines the data structures.
The Registry Implementation
Located in agentbook/providers/registry.py, the registry maintains a PROVIDERS dictionary mapping canonical provider names to Provider instances. The lookup() function defined at lines 57-75 serves as the primary entry point for resolving provider strings.
The Provider Dataclass Structure
The Provider dataclass defined in agentbook/providers/models.py (lines 16-50) encapsulates four critical fields:
- name: The canonical identifier for the provider
- base_url: The default API endpoint (overridable via environment variables)
- default_model: The model used when callers omit specific model parameters
- key_vars: An ordered list of environment variable names that may contain the API key
How the Provider Lookup Function Works
The lookup process follows a strict three-stage pipeline that ensures consistent resolution across the codebase.
Step 1: Canonicalization
Before dictionary lookup, the input string undergoes normalization through the canonical_provider() function (lines 41-55). This process lowercases the input, strips whitespace, and resolves any registered aliases to their canonical forms. For example, the alias "moonshot" automatically resolves to the canonical name "kimi".
Step 2: Dictionary Resolution
The canonicalized name serves as a key into the PROVIDERS dictionary. The lookup() function retrieves the corresponding Provider instance, which contains all connection parameters required to instantiate an OpenAI-compatible backend.
Step 3: Error Handling
If the canonicalized name does not exist in PROVIDERS, the function raises a ValueError (lines 70-74) listing all supported provider names. This centralized error handling eliminates duplicate validation logic across the repository's chapter examples.
Practical Implementation Examples
Below are concrete patterns for interacting with the provider lookup function in production code.
Basic Provider Resolution
To resolve a provider name to its specification, import the lookup function and pass the provider identifier:
from agentbook.providers.registry import lookup
# Resolve the provider (accepts aliases like "moonshot" → "kimi")
provider = lookup("moonshot")
print(provider.name) # → "kimi"
print(provider.base_url) # → "https://api.moonshot.cn/v1"
print(provider.default_model) # → "kimi-k3"
This example demonstrates how the lookup function handles the "moonshot" to "kimi" alias mapping defined in the registry.
Retrieving API Keys Safely
The Provider dataclass provides a helper method api_key() (lines 51-63 in models.py) that securely reads credentials from environment variables:
from agentbook.providers.registry import lookup
import os
provider = lookup("openai")
api_key = provider.api_key() # Reads the first non-empty env var in key_vars
print("Key present?", bool(api_key))
This approach checks the ordered list of environment variables defined in key_vars and returns the first non-empty value, supporting multiple credential sources.
Integration with Backend Resolution
Higher-level code typically combines lookup with backend instantiation through resolve_backend() in agentbook/providers/resolution.py:
from agentbook.providers.registry import lookup
from agentbook.providers.resolution import resolve_backend
# Resolve a backend for the "together" aggregator, overriding the model.
backend = resolve_backend("together", model="gpt-4o", api_key="my-together-key")
print(backend.base_url) # → "https://api.together.xyz/v1"
print(backend.model) # → "openai/gpt-4o" (namespaced automatically)
print(backend.using_openrouter) # → False
The resolver internally calls lookup() to fetch the provider specification before constructing the concrete Backend instance.
Handling Invalid Providers
Implement error handling to catch unsupported provider names:
from agentbook.providers.registry import lookup
try:
lookup("unknown-provider")
except ValueError as exc:
print(exc) # → "Unsupported provider: 'unknown-provider'. Supported: ..."
The exception message programmatically lists all valid providers by computing the union of canonical names and aliases.
Extending the Provider Registry
Adding support for new providers requires only inserting a new entry into the PROVIDERS dictionary in agentbook/providers/registry.py. The lookup() function automatically recognizes new names and aliases without modification. Use the supported_providers() helper to retrieve the current list of valid options for CLI argument validation or UI dropdowns.
Summary
- The provider lookup function at
agentbook/providers/registry.pylines 57-75 converts arbitrary provider names into canonicalProviderdataclasses. - Canonicalization (lines 41-55) normalizes input and resolves aliases before dictionary lookup.
- The
Providerdataclass inagentbook/providers/models.pyencapsulates base URLs, default models, and credential environment variables. - Error handling raises descriptive
ValueErrorexceptions listing all supported providers when lookup fails. - Higher-level resolution in
agentbook/providers/resolution.pyconsumes the lookup results to instantiate concrete backend connections.
Frequently Asked Questions
What file contains the provider lookup function implementation?
The primary implementation resides in agentbook/providers/registry.py, specifically the lookup() function defined at lines 57-75. This module also contains the PROVIDERS dictionary and alias mapping logic at lines 41-55.
How does the lookup function handle provider aliases?
The function calls canonical_provider() (lines 41-55) to normalize input strings and resolve aliases to canonical names. For example, passing "moonshot" returns the "kimi" provider configuration because the registry maps that alias to the canonical entry.
What information does the Provider dataclass contain?
According to the definition in agentbook/providers/models.py lines 16-50, the Provider dataclass contains the canonical name, base URL for API requests, default model identifier, and an ordered list of environment variable names (key_vars) that may store the API key.
How do I retrieve the API key after looking up a provider?
Call the api_key() method on the returned Provider instance. This method checks the environment variables listed in key_vars (defined in models.py lines 51-63) and returns the first non-empty value, or None if no credentials are found.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →