API Reference¶
Complete API reference for Pico-Agent, auto-generated from source code docstrings.
Module Overview¶
| Module | Description |
|---|---|
pico_agent | Package exports and public API |
pico_agent.config | Agent configuration settings |
pico_agent.decorators | @agent, @tool decorators |
pico_agent.interfaces | Core interfaces and protocols |
pico_agent.exceptions | Exception hierarchy |
pico_agent.bootstrap | Bootstrap and initialization |
pico_agent.providers | LLM provider integrations |
pico_agent.messages | Message types and handling |
pico_agent.tools | Tool registration and execution |
pico_agent.router | Agent routing logic |
pico_agent.registry | Agent and tool registry |
pico_agent.lifecycle | Agent lifecycle management |
pico_agent.tracing | Observability and tracing |
pico_agent.scheduler | Task scheduling |
pico_agent¶
pico_agent ¶
Pico-Agent: Protocol-based AI agent framework with dependency injection.
Public API exports for the pico-agent library. All classes, functions, and constants listed in __all__ are considered stable public API.
AgentCapability ¶
Abstract capability labels mapped to concrete models by ModelRouter.
Use these constants in the @agent decorator to declare what kind of model an agent needs. The ModelRouter translates these labels into provider-specific model names at runtime, allowing you to swap models globally without touching agent definitions.
Attributes:
| Name | Type | Description |
|---|---|---|
FAST | Optimised for low latency (default model: | |
SMART | Balanced quality and cost (default model: | |
REASONING | Advanced reasoning tasks (default model: | |
VISION | Vision / multimodal support (default model: | |
CODING | Code generation (default model: |
Example
from pico_agent import agent, AgentCapability @agent(name="fast_bot", capability=AgentCapability.FAST) ... class FastBot(Protocol): ... def run(self, q: str) -> str: ...
Source code in src/pico_agent/config.py
AgentConfig dataclass ¶
Complete configuration for a single agent.
Instances are created automatically by the @agent decorator and stored in LocalAgentRegistry. The AgentConfigService merges local, remote (central), and runtime overrides to produce the final effective config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique agent identifier (required). | required |
system_prompt | str | System-level prompt sent to the LLM. | '' |
user_prompt_template | str | Template for the user message. Use | '{input}' |
description | str | Human-readable description; used as | '' |
capability | str |
| SMART |
enabled | bool | Whether the agent is active. Disabled agents raise | True |
agent_type | AgentType | Execution strategy ( | ONE_SHOT |
max_iterations | int | Maximum ReAct loop iterations (only relevant for | 5 |
tools | List[str] | List of tool names to attach to this agent. | list() |
agents | List[str] | List of child agent names that will be wrapped as | list() |
tags | List[str] | Tags used for dynamic tool lookup via | list() |
tracing_enabled | bool | Whether | True |
temperature | float | LLM sampling temperature (0.0 -- 2.0). | 0.7 |
max_tokens | Optional[int] | Maximum tokens in the LLM response, or | None |
llm_profile | Optional[str] | Named API-key / base-URL profile in | None |
workflow_config | Dict[str, Any] | Extra parameters for | dict() |
Source code in src/pico_agent/config.py
AgentType ¶
Bases: str, Enum
Execution strategy for an agent.
Determines how the agent processes requests and interacts with tools.
Attributes:
| Name | Type | Description |
|---|---|---|
ONE_SHOT | Single LLM call with no tool loop (default). | |
REACT | Iterative ReAct tool loop via LangGraph, up to | |
WORKFLOW | Custom workflow execution (e.g., map-reduce). |
Source code in src/pico_agent/config.py
LLMConfig dataclass ¶
Centralised API-key and base-URL store for all LLM providers.
AgentLocator registers a default (empty) LLMConfig singleton via @provides. To populate it with your credentials, use @configure on a component method that receives LLMConfig as a parameter. Do not register your own LLMConfig with @factory + @provides -- that would conflict with the singleton already provided by AgentInfrastructureFactory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_keys | Dict[str, str] | Mapping of provider name (or profile name) to API key. Standard keys: | dict() |
base_urls | Dict[str, str] | Mapping of provider name (or profile name) to base URL override. | dict() |
Example
from pico_ioc import component, configure from pico_agent import LLMConfig @component ... class AppConfig: ... @configure ... def setup(self, llm: LLMConfig): ... llm.api_keys["openai"] = "sk-..."
Source code in src/pico_agent/config.py
AgentConfigurationError ¶
Bases: AgentError
Raised for missing or invalid agent / provider configuration.
Common causes include missing API keys in LLMConfig or unknown provider names.
AgentDisabledError ¶
Bases: AgentError
Raised when an agent is invoked but its configuration has enabled=False.
The error message follows the pattern:
``Agent '<name>' is disabled via configuration.``
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_name | str | The name of the disabled agent. | required |
Source code in src/pico_agent/exceptions.py
AgentError ¶
AgentLifecycleError ¶
Bases: AgentError
Raised when an operation violates the agent system lifecycle.
For example, attempting to use the system before it has reached the READY phase.
ExperimentRegistry ¶
Singleton registry for A/B experiments on agents.
Register experiments mapping a public name to weighted variants. When AgentLocator resolves an agent name, it passes through resolve_variant() to select the appropriate variant.
Example
registry = container.get(ExperimentRegistry) registry.register_experiment("summarizer", { ... "summarizer_v1": 0.8, ... "summarizer_v2": 0.2, ... })
Source code in src/pico_agent/experiments.py
register_experiment(public_name, variants) ¶
Register an A/B experiment.
Weights are normalised so they sum to 1.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
public_name | str | The public agent name that triggers variant selection. | required |
variants | Dict[str, float] | Mapping of variant agent names to their relative weights. | required |
Source code in src/pico_agent/experiments.py
resolve_variant(name) ¶
Resolve a public name to a variant using weighted random selection.
If no experiment is registered for name, the name itself is returned unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The public agent name. | required |
Returns:
| Type | Description |
|---|---|
str | The selected variant name, or name if no experiment exists. |
Source code in src/pico_agent/experiments.py
LLM ¶
Bases: Protocol
Protocol for a language-model adapter used by agent proxies.
LangChainAdapter is the built-in implementation.
Source code in src/pico_agent/interfaces.py
invoke(messages, tools) ¶
Send messages to the LLM and return the text response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages | List[Dict[str, str]] | List of message dicts with | required |
tools | List[Any] | LangChain-compatible tool instances bound to the model. | required |
Returns:
| Type | Description |
|---|---|
str | The LLM's text response. |
Source code in src/pico_agent/interfaces.py
invoke_structured(messages, tools, output_schema) ¶
Send messages and parse the response into a structured schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages | List[Dict[str, str]] | List of message dicts. | required |
tools | List[Any] | LangChain-compatible tool instances. | required |
output_schema | Type[Any] | A | required |
Returns:
| Type | Description |
|---|---|
Any | An instance of output_schema. |
Source code in src/pico_agent/interfaces.py
invoke_agent_loop(messages, tools, max_iterations, output_schema=None) ¶
Run a ReAct-style tool loop via LangGraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages | List[Dict[str, str]] | List of message dicts. | required |
tools | List[Any] | LangChain-compatible tool instances. | required |
max_iterations | int | Maximum number of reasoning iterations. | required |
output_schema | Optional[Type[Any]] | Optional Pydantic model for structured final output. | None |
Returns:
| Type | Description |
|---|---|
Any | The final text response, or an instance of output_schema if |
Any | provided. |
Source code in src/pico_agent/interfaces.py
CentralConfigClient ¶
Bases: Protocol
Protocol for retrieving and persisting agent configuration remotely.
The default implementation (NoOpCentralClient) returns None for all lookups, meaning only local and runtime config is used. Provide a custom implementation (e.g., backed by a database or API) to enable central configuration management.
Source code in src/pico_agent/interfaces.py
get_agent_config(name) ¶
Fetch the remote configuration for an agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The agent's unique identifier. | required |
Returns:
| Type | Description |
|---|---|
Optional[Any] | An |
upsert_agent_config(config) ¶
Create or update the remote configuration for an agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Any | The | required |
LLMFactory ¶
Bases: Protocol
Protocol for creating LLM instances from model parameters.
LangChainLLMFactory is the built-in implementation that supports OpenAI, Azure, Anthropic, Google, DeepSeek, and Qwen.
Source code in src/pico_agent/interfaces.py
create(model_name, temperature, max_tokens, llm_profile=None) ¶
Create an LLM instance for the given model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name | str | Model identifier, optionally prefixed with a provider (e.g., | required |
temperature | float | Sampling temperature (0.0 -- 2.0). | required |
max_tokens | Optional[int] | Maximum response tokens, or | required |
llm_profile | Optional[str] | Named profile in | None |
Returns:
| Type | Description |
|---|---|
LLM | A configured |
Source code in src/pico_agent/interfaces.py
AgentSystem ¶
Lifecycle coordinator that publishes phase transitions via EventBus.
Transitions are published as LifecycleEvent instances. The system moves through: INITIALIZING -> READY -> RUNNING -> SHUTTING_DOWN -> STOPPED.
Source code in src/pico_agent/lifecycle.py
phase property ¶
The current lifecycle phase.
LifecycleEvent dataclass ¶
Bases: Event
Event published when the system transitions between lifecycle phases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase | LifecyclePhase | The new | required |
detail | str | Optional human-readable detail string. | '' |
Source code in src/pico_agent/lifecycle.py
LifecyclePhase ¶
Bases: str, Enum
Phases of the pico-agent system lifecycle.
Attributes:
| Name | Type | Description |
|---|---|---|
INITIALIZING | Container is being built. | |
SCANNING | Agents and tools are being discovered. | |
READY | Container is fully configured. | |
RUNNING | System is accepting requests. | |
SHUTTING_DOWN | Graceful shutdown in progress. | |
STOPPED | System has stopped. |
Source code in src/pico_agent/lifecycle.py
AgentLocator ¶
Primary entry point for obtaining agent proxies.
Resolves agent names (or Protocol classes) to DynamicAgentProxy (for code-defined agents) or VirtualAgentRunner (for YAML-defined / runtime agents). Supports A/B experiment resolution via ExperimentRegistry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
container | PicoContainer | The pico-ioc container. | required |
config_service | AgentConfigService | Service for resolving agent configurations. | required |
tool_registry | ToolRegistry | Registry for tool lookup. | required |
llm_factory | LLMFactory | Factory for creating LLM instances. | required |
local_registry | LocalAgentRegistry | Registry of locally discovered agents. | required |
model_router | ModelRouter | Capability-to-model router. | required |
experiment_registry | ExperimentRegistry | A/B experiment variant selector. | required |
scheduler | PlatformScheduler | Concurrency scheduler for async operations. | required |
Source code in src/pico_agent/locator.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | |
get_agent(name_or_protocol) ¶
Retrieve an agent proxy by name or Protocol class.
Resolution order:
- If name_or_protocol is a type, look up the agent name from its
AGENT_META_KEYmetadata or fromLocalAgentRegistry. - If a string, pass through
ExperimentRegistry.resolve_variant()for A/B testing support. - If a matching Protocol exists locally, create a
DynamicAgentProxy. - Otherwise, attempt to create a
VirtualAgentRunnerfrom config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name_or_protocol | Any | Either an agent name string or a Protocol class. | required |
Returns:
| Type | Description |
|---|---|
Optional[Any] | A |
Optional[Any] | no agent could be resolved. |
Source code in src/pico_agent/locator.py
create_proxy(protocol) ¶
Create a DynamicAgentProxy directly from a Protocol class.
Convenience method that extracts the agent name from the Protocol's AGENT_META_KEY metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
protocol | Type | A Protocol class decorated with | required |
Returns:
| Type | Description |
|---|---|
Any | A |
Source code in src/pico_agent/locator.py
AgentConfigService ¶
Merges central, local, and runtime configuration for agents.
Configuration priority (highest wins): central > local > runtime. Central config (from CentralConfigClient) takes precedence over the local config discovered by AgentScanner. Runtime overrides set via update_agent_config() are applied on top of whichever base config is found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
central_client | CentralConfigClient | Remote configuration client. | required |
local_registry | LocalAgentRegistry | Registry populated by | required |
Source code in src/pico_agent/registry.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | |
get_config(name) ¶
Return the effective AgentConfig for the named agent.
Merges remote, local, and runtime sources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Agent identifier. | required |
Returns:
| Type | Description |
|---|---|
AgentConfig | The merged |
Raises:
| Type | Description |
|---|---|
ValueError | If no configuration exists for the given name. Message: |
Source code in src/pico_agent/registry.py
update_agent_config(name, **kwargs) ¶
Apply runtime overrides to an agent's configuration.
Overrides are merged on each get_config() call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Agent identifier. | required |
**kwargs | Fields of | {} |
Source code in src/pico_agent/registry.py
reset_agent_config(name) ¶
Remove all runtime overrides for an agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Agent identifier. | required |
ToolRegistry ¶
Central registry that stores tool classes/instances and supports tag-based lookup.
Tools are registered by ToolScanner during auto-discovery or manually via register(). At execution time, DynamicAgentProxy and VirtualAgentRunner query this registry to resolve tool dependencies.
Source code in src/pico_agent/registry.py
register(name, tool_cls_or_instance, tags=None) ¶
Register a tool by name with optional tags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique tool identifier. | required |
tool_cls_or_instance | Any | The tool class or an already-instantiated tool object. | required |
tags | Optional[List[str]] | Optional list of tags for dynamic tool lookup. Tools tagged | None |
Source code in src/pico_agent/registry.py
get_tool(name) ¶
Retrieve a tool by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The tool identifier. | required |
Returns:
| Type | Description |
|---|---|
Optional[Any] | The tool class or instance, or |
get_tool_names_by_tag(tag) ¶
Return all tool names associated with the given tag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tag | str | The tag to search for. | required |
Returns:
| Type | Description |
|---|---|
List[str] | List of matching tool names (may be empty). |
Source code in src/pico_agent/registry.py
get_dynamic_tools(agent_tags) ¶
Collect tool instances matching any of the given tags, plus "global" tools.
Duplicates are excluded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_tags | List[str] | Tags from the agent's | required |
Returns:
| Type | Description |
|---|---|
List[Any] | De-duplicated list of tool instances. |
Source code in src/pico_agent/registry.py
AgentScanner ¶
Bases: _ScannerBase
Discovers @agent-decorated Protocol classes and registers them.
Walks Python modules to find classes that carry the IS_AGENT_INTERFACE flag, extracts the AgentConfig from AGENT_META_KEY, and stores both the Protocol class and its config in LocalAgentRegistry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry | LocalAgentRegistry | The | required |
Source code in src/pico_agent/scanner.py
scan_module(module) ¶
Inspect a module for @agent-decorated classes.
Each discovered class is registered in the LocalAgentRegistry. Modules are scanned at most once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module | Any | A Python module object. | required |
Source code in src/pico_agent/scanner.py
ToolScanner ¶
Bases: _ScannerBase
Discovers @tool-decorated classes and registers them.
Walks Python modules to find classes that carry TOOL_META_KEY, extracts the ToolConfig, and stores the class in ToolRegistry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry | ToolRegistry | The | required |
Source code in src/pico_agent/scanner.py
scan_module(module) ¶
Inspect a module for @tool-decorated classes.
Each discovered class is registered in the ToolRegistry. Modules are scanned at most once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module | Any | A Python module object. | required |
Source code in src/pico_agent/scanner.py
TraceRun dataclass ¶
A single trace record for an agent, tool, or LLM invocation.
Attributes:
| Name | Type | Description |
|---|---|---|
id | str | Unique run identifier (UUID). |
name | str | Human-readable name (e.g., agent name or |
run_type | str | Category string -- |
inputs | Dict[str, Any] | Input data (e.g., messages, arguments). |
parent_id | Optional[str] | ID of the parent run, or |
start_time | float | Unix timestamp when the run started. |
end_time | Optional[float] | Unix timestamp when the run ended (set by |
outputs | Optional[Dict[str, Any]] | Output data (set by |
error | Optional[str] | Error message if the run failed (set by |
extra | Dict[str, Any] | Arbitrary metadata (e.g., |
Source code in src/pico_agent/tracing.py
TraceService ¶
Singleton service that collects hierarchical trace runs.
Traces are stored in memory and can be retrieved via get_traces(). On container shutdown (@cleanup), all traces are flushed.
Source code in src/pico_agent/tracing.py
start_run(name, run_type, inputs, extra=None) ¶
Begin a new trace run.
Automatically sets the parent ID from run_context and updates the context var to the new run ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Human-readable run name. | required |
run_type | str | Category ( | required |
inputs | Dict[str, Any] | Input data to record. | required |
extra | Dict[str, Any] | Optional metadata dict. | None |
Returns:
| Type | Description |
|---|---|
str | The unique run ID (UUID string). |
Source code in src/pico_agent/tracing.py
end_run(run_id, outputs=None, error=None) ¶
Complete a trace run, recording outputs or an error.
Restores run_context to the parent run's ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run_id | str | The ID returned by | required |
outputs | Any | Output data -- can be a string, dict, Pydantic model, or any object (converted via | None |
error | Exception | Exception instance if the run failed. | None |
Source code in src/pico_agent/tracing.py
get_traces() ¶
Return all recorded traces as a list of dictionaries.
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]] | List of dicts, each representing a |
AgentValidator ¶
Validates AgentConfig instances for correctness.
Checks performed:
namemust not be empty.capabilitymust be defined.temperaturemust be between 0.0 and 2.0 (warning if > 1.0).system_promptshould not be empty (warning).
Source code in src/pico_agent/validation.py
validate(config) ¶
Validate an agent configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | AgentConfig | The | required |
Returns:
| Type | Description |
|---|---|
ValidationReport | A |
ValidationReport | found, and a list of |
Source code in src/pico_agent/validation.py
Severity ¶
Bases: str, Enum
Severity level for a validation issue.
Attributes:
| Name | Type | Description |
|---|---|---|
WARNING | Non-fatal issue (e.g., empty system prompt). | |
ERROR | Fatal issue that prevents the agent from running. |
Source code in src/pico_agent/validation.py
ValidationIssue dataclass ¶
A single validation finding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field | str | The | required |
message | str | Human-readable description of the problem. | required |
severity | Severity |
| required |
Source code in src/pico_agent/validation.py
ValidationReport dataclass ¶
Result of validating an AgentConfig.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
valid | bool |
| required |
issues | List[ValidationIssue] | List of | list() |
Source code in src/pico_agent/validation.py
has_errors property ¶
Return True if any issue has Severity.ERROR.
VirtualAgent ¶
Bases: Protocol
Protocol for virtual agents (config-only, no Protocol class).
Both VirtualAgentRunner and dynamically created agents conform to this interface.
Source code in src/pico_agent/virtual.py
run(input) ¶
Execute the agent synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input | str | The user message. | required |
Returns:
| Type | Description |
|---|---|
str | The agent's text response. |
arun(input) async ¶
Execute the agent asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input | str | The user message. | required |
Returns:
| Type | Description |
|---|---|
str | The agent's text response. |
run_structured(input, schema) ¶
Execute the agent and parse the response into a Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input | str | The user message. | required |
schema | Type[T] | A | required |
Returns:
| Type | Description |
|---|---|
T | An instance of schema. |
Source code in src/pico_agent/virtual.py
run_with_args(args) ¶
Execute the agent with a dictionary of arguments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args | Dict[str, Any] | Key-value pairs used to fill prompt templates. | required |
Returns:
| Type | Description |
|---|---|
str | The agent's text response. |
VirtualAgentManager ¶
Creates and manages virtual agents programmatically at runtime.
Virtual agents are config-only agents that do not require a Protocol class. Use create_agent() to define a new agent with inline parameters, or get_agent() to retrieve an existing one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_service | AgentConfigService | Service for storing runtime agent configurations. | required |
tool_registry | ToolRegistry | Registry for tool lookup. | required |
llm_factory | LLMFactory | Factory for creating LLM instances. | required |
model_router | ModelRouter | Capability-to-model router. | required |
container | PicoContainer | The pico-ioc container. | required |
scheduler | PlatformScheduler | Concurrency scheduler for async operations. | required |
Example
manager = container.get(VirtualAgentManager) agent = manager.create_agent( ... "greeter", ... system_prompt="You greet users warmly.", ... capability="fast", ... ) result = agent.run("Hello!")
Source code in src/pico_agent/virtual.py
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 | |
create_agent(name, **kwargs) ¶
Create a new virtual agent and register its configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique agent identifier. | required |
**kwargs | Any | {} |
Returns:
| Type | Description |
|---|---|
VirtualAgent | A |
VirtualAgent | protocol. |
Source code in src/pico_agent/virtual.py
get_agent(name) ¶
Retrieve (or re-create) a virtual agent by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The agent identifier previously used with | required |
Returns:
| Type | Description |
|---|---|
VirtualAgent | A |
Raises:
| Type | Description |
|---|---|
ValueError | If no configuration exists for the given name. |
Source code in src/pico_agent/virtual.py
DynamicTool ¶
A tool created at runtime from a plain callable.
Exposes name, description, args_schema, and __call__ to satisfy the LangChain tool interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique tool identifier. | required |
description | str | Human-readable description for the LLM. | required |
func | Callable[..., str] | The callable that implements the tool logic. | required |
args_schema | Type[BaseModel] | Optional Pydantic model for the tool's arguments. If | None |
Source code in src/pico_agent/virtual_tools.py
VirtualToolManager ¶
Creates and registers DynamicTool instances at runtime.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool_registry | ToolRegistry | The | required |
Example
manager = container.get(VirtualToolManager) tool = manager.create_tool( ... name="echo", ... description="Echoes the input back", ... func=lambda text: text, ... )
Source code in src/pico_agent/virtual_tools.py
create_tool(name, description, func, schema=None) ¶
Create a DynamicTool and register it in the ToolRegistry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique tool identifier. | required |
description | str | Human-readable description for the LLM. | required |
func | Callable | The callable that implements the tool logic. | required |
schema | Optional[Type[BaseModel]] | Optional Pydantic model for the tool's arguments. | None |
Returns:
| Type | Description |
|---|---|
DynamicTool | The created |
Source code in src/pico_agent/virtual_tools.py
create_proto_tool(name, description, handler) ¶
Create a tool that accepts a list of dictionaries as its payload.
Convenience wrapper around create_tool() for handlers that process structured batch data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique tool identifier. | required |
description | str | Human-readable description for the LLM. | required |
handler | Callable[[List[Dict[str, Any]]], str] | A callable that receives | required |
Returns:
| Type | Description |
|---|---|
| The created |
Source code in src/pico_agent/virtual_tools.py
init(*args, **kwargs) ¶
Initialise a pico-ioc container with pico-agent infrastructure.
Wraps pico_ioc.init() and:
- Prepends the
pico_agentmodule to the module list. - Loads plugin modules from the
pico_agent.pluginsentry point group (disable withPICO_AGENT_AUTO_PLUGINS=false). - Harvests
PICO_SCANNERSfrom all modules and adds them as custom scanners.
All positional and keyword arguments are forwarded to pico_ioc.init().
Returns:
| Type | Description |
|---|---|
PicoContainer | A fully configured |
Example
from pico_agent import init container = init(modules=["myapp"])
Source code in src/pico_agent/bootstrap.py
agent(name, capability=AgentCapability.SMART, system_prompt='', description='', user_prompt_template='{input}', agent_type=AgentType.ONE_SHOT, max_iterations=5, tools=None, agents=None, tags=None, tracing_enabled=True, temperature=0.7, llm_profile=None) ¶
Declare a Protocol class as a pico-agent.
Attaches an AgentConfig instance (AGENT_META_KEY) and the IS_AGENT_INTERFACE flag to the decorated class so that AgentScanner can discover and register it automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique agent identifier (required). | required |
capability | str |
| SMART |
system_prompt | str | System-level prompt sent to the LLM. | '' |
description | str | Human-readable description. If empty, falls back to the first line of the class docstring. | '' |
user_prompt_template | str | Template for the user message. Placeholders (e.g., | '{input}' |
agent_type | AgentType | Execution strategy -- | ONE_SHOT |
max_iterations | int | Maximum ReAct loop iterations ( | 5 |
tools | Optional[List[str]] | Tool names to attach to this agent. | None |
agents | Optional[List[str]] | Child agent names wrapped as | None |
tags | Optional[List[str]] | Tags for dynamic tool lookup via | None |
tracing_enabled | bool | Whether | True |
temperature | float | LLM sampling temperature (0.0 -- 2.0). | 0.7 |
llm_profile | Optional[str] | Named profile in | None |
Returns:
| Type | Description |
|---|---|
Callable[[Type], Type] | A class decorator that sets agent metadata on the target class. |
Example
from typing import Protocol from pico_agent import agent, AgentCapability, AgentType @agent( ... name="summarizer", ... capability=AgentCapability.SMART, ... system_prompt="Summarize the following text.", ... agent_type=AgentType.ONE_SHOT, ... ) ... class Summarizer(Protocol): ... def summarize(self, text: str) -> str: ...
Source code in src/pico_agent/decorators.py
tool(name, description) ¶
Declare a class as a pico-agent tool.
Attaches a ToolConfig instance (TOOL_META_KEY) to the decorated class so that ToolScanner can discover and register it. The class must implement one of __call__, run, execute, or invoke.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique tool identifier shown to the LLM. | required |
description | str | Human-readable description the LLM uses to decide when to invoke this tool. | required |
Returns:
| Type | Description |
|---|---|
Callable[[Type], Type] | A class decorator that sets tool metadata on the target class. |
Example
from pico_ioc import component from pico_agent import tool @tool(name="calculator", description="Evaluate math expressions") ... @component ... class Calculator: ... def run(self, expression: str) -> str: ... return str(eval(expression))
Source code in src/pico_agent/decorators.py
configure_logging(level=logging.INFO, handler=None) ¶
Configure logging for the pico_agent library.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level | int | Logging level (default: INFO) | INFO |
handler | Optional[Handler] | Custom handler. If None, uses StreamHandler to stderr. | None |
Source code in src/pico_agent/logging.py
get_logger(name) ¶
Get a logger with the pico_agent namespace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Logger name. If not prefixed with 'pico_agent', it will be added. | required |
Returns:
| Type | Description |
|---|---|
Logger | A configured Logger instance. |
Source code in src/pico_agent/logging.py
Configuration¶
pico_agent.config ¶
Configuration dataclasses and enumerations for pico-agent.
Defines the core configuration types used throughout the framework: AgentType, AgentCapability, AgentConfig, ToolConfig, and LLMConfig.
AgentType ¶
Bases: str, Enum
Execution strategy for an agent.
Determines how the agent processes requests and interacts with tools.
Attributes:
| Name | Type | Description |
|---|---|---|
ONE_SHOT | Single LLM call with no tool loop (default). | |
REACT | Iterative ReAct tool loop via LangGraph, up to | |
WORKFLOW | Custom workflow execution (e.g., map-reduce). |
Source code in src/pico_agent/config.py
AgentCapability ¶
Abstract capability labels mapped to concrete models by ModelRouter.
Use these constants in the @agent decorator to declare what kind of model an agent needs. The ModelRouter translates these labels into provider-specific model names at runtime, allowing you to swap models globally without touching agent definitions.
Attributes:
| Name | Type | Description |
|---|---|---|
FAST | Optimised for low latency (default model: | |
SMART | Balanced quality and cost (default model: | |
REASONING | Advanced reasoning tasks (default model: | |
VISION | Vision / multimodal support (default model: | |
CODING | Code generation (default model: |
Example
from pico_agent import agent, AgentCapability @agent(name="fast_bot", capability=AgentCapability.FAST) ... class FastBot(Protocol): ... def run(self, q: str) -> str: ...
Source code in src/pico_agent/config.py
AgentConfig dataclass ¶
Complete configuration for a single agent.
Instances are created automatically by the @agent decorator and stored in LocalAgentRegistry. The AgentConfigService merges local, remote (central), and runtime overrides to produce the final effective config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique agent identifier (required). | required |
system_prompt | str | System-level prompt sent to the LLM. | '' |
user_prompt_template | str | Template for the user message. Use | '{input}' |
description | str | Human-readable description; used as | '' |
capability | str |
| SMART |
enabled | bool | Whether the agent is active. Disabled agents raise | True |
agent_type | AgentType | Execution strategy ( | ONE_SHOT |
max_iterations | int | Maximum ReAct loop iterations (only relevant for | 5 |
tools | List[str] | List of tool names to attach to this agent. | list() |
agents | List[str] | List of child agent names that will be wrapped as | list() |
tags | List[str] | Tags used for dynamic tool lookup via | list() |
tracing_enabled | bool | Whether | True |
temperature | float | LLM sampling temperature (0.0 -- 2.0). | 0.7 |
max_tokens | Optional[int] | Maximum tokens in the LLM response, or | None |
llm_profile | Optional[str] | Named API-key / base-URL profile in | None |
workflow_config | Dict[str, Any] | Extra parameters for | dict() |
Source code in src/pico_agent/config.py
ToolConfig dataclass ¶
Metadata for a tool, created by the @tool decorator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique tool identifier shown to the LLM for tool selection. | required |
description | str | Human-readable description the LLM uses to decide when to invoke this tool. | required |
Source code in src/pico_agent/config.py
LLMConfig dataclass ¶
Centralised API-key and base-URL store for all LLM providers.
AgentLocator registers a default (empty) LLMConfig singleton via @provides. To populate it with your credentials, use @configure on a component method that receives LLMConfig as a parameter. Do not register your own LLMConfig with @factory + @provides -- that would conflict with the singleton already provided by AgentInfrastructureFactory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_keys | Dict[str, str] | Mapping of provider name (or profile name) to API key. Standard keys: | dict() |
base_urls | Dict[str, str] | Mapping of provider name (or profile name) to base URL override. | dict() |
Example
from pico_ioc import component, configure from pico_agent import LLMConfig @component ... class AppConfig: ... @configure ... def setup(self, llm: LLMConfig): ... llm.api_keys["openai"] = "sk-..."
Source code in src/pico_agent/config.py
Decorators¶
pico_agent.decorators ¶
Decorators for declaring agents and tools.
Provides the @agent and @tool class decorators that attach metadata used by AgentScanner and ToolScanner for automatic discovery.
AGENT_META_KEY = '_pico_agent_meta' module-attribute ¶
str: Attribute name where AgentConfig metadata is stored on a decorated class.
TOOL_META_KEY = '_pico_tool_meta' module-attribute ¶
str: Attribute name where ToolConfig metadata is stored on a decorated class.
IS_AGENT_INTERFACE = '_pico_is_agent_interface' module-attribute ¶
str: Boolean flag attribute set on classes decorated with @agent.
agent(name, capability=AgentCapability.SMART, system_prompt='', description='', user_prompt_template='{input}', agent_type=AgentType.ONE_SHOT, max_iterations=5, tools=None, agents=None, tags=None, tracing_enabled=True, temperature=0.7, llm_profile=None) ¶
Declare a Protocol class as a pico-agent.
Attaches an AgentConfig instance (AGENT_META_KEY) and the IS_AGENT_INTERFACE flag to the decorated class so that AgentScanner can discover and register it automatically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique agent identifier (required). | required |
capability | str |
| SMART |
system_prompt | str | System-level prompt sent to the LLM. | '' |
description | str | Human-readable description. If empty, falls back to the first line of the class docstring. | '' |
user_prompt_template | str | Template for the user message. Placeholders (e.g., | '{input}' |
agent_type | AgentType | Execution strategy -- | ONE_SHOT |
max_iterations | int | Maximum ReAct loop iterations ( | 5 |
tools | Optional[List[str]] | Tool names to attach to this agent. | None |
agents | Optional[List[str]] | Child agent names wrapped as | None |
tags | Optional[List[str]] | Tags for dynamic tool lookup via | None |
tracing_enabled | bool | Whether | True |
temperature | float | LLM sampling temperature (0.0 -- 2.0). | 0.7 |
llm_profile | Optional[str] | Named profile in | None |
Returns:
| Type | Description |
|---|---|
Callable[[Type], Type] | A class decorator that sets agent metadata on the target class. |
Example
from typing import Protocol from pico_agent import agent, AgentCapability, AgentType @agent( ... name="summarizer", ... capability=AgentCapability.SMART, ... system_prompt="Summarize the following text.", ... agent_type=AgentType.ONE_SHOT, ... ) ... class Summarizer(Protocol): ... def summarize(self, text: str) -> str: ...
Source code in src/pico_agent/decorators.py
tool(name, description) ¶
Declare a class as a pico-agent tool.
Attaches a ToolConfig instance (TOOL_META_KEY) to the decorated class so that ToolScanner can discover and register it. The class must implement one of __call__, run, execute, or invoke.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique tool identifier shown to the LLM. | required |
description | str | Human-readable description the LLM uses to decide when to invoke this tool. | required |
Returns:
| Type | Description |
|---|---|
Callable[[Type], Type] | A class decorator that sets tool metadata on the target class. |
Example
from pico_ioc import component from pico_agent import tool @tool(name="calculator", description="Evaluate math expressions") ... @component ... class Calculator: ... def run(self, expression: str) -> str: ... return str(eval(expression))
Source code in src/pico_agent/decorators.py
Interfaces¶
pico_agent.interfaces ¶
Protocol interfaces that define the contracts for agents, LLMs, and configuration clients.
All core abstractions are expressed as typing.Protocol classes so that any conforming implementation can be used without explicit inheritance.
Agent ¶
Bases: Protocol
Standard interface for an agent produced by pico-agent.
Agent Protocol classes decorated with @agent do not need to inherit from this Protocol; it exists as a reference contract.
Source code in src/pico_agent/interfaces.py
run(input) ¶
Execute the agent synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input | str | The user message / task description. | required |
Returns:
| Type | Description |
|---|---|
str | The agent's text response. |
arun(input) async ¶
Execute the agent asynchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input | str | The user message / task description. | required |
Returns:
| Type | Description |
|---|---|
str | The agent's text response. |
run_structured(input, schema) ¶
Execute the agent and parse the response into a Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input | str | The user message / task description. | required |
schema | Type[T] | A | required |
Returns:
| Type | Description |
|---|---|
T | An instance of schema populated from the LLM response. |
Source code in src/pico_agent/interfaces.py
arun_structured(input, schema) async ¶
Async variant of run_structured.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input | str | The user message / task description. | required |
schema | Type[T] | A | required |
Returns:
| Type | Description |
|---|---|
T | An instance of schema populated from the LLM response. |
Source code in src/pico_agent/interfaces.py
CentralConfigClient ¶
Bases: Protocol
Protocol for retrieving and persisting agent configuration remotely.
The default implementation (NoOpCentralClient) returns None for all lookups, meaning only local and runtime config is used. Provide a custom implementation (e.g., backed by a database or API) to enable central configuration management.
Source code in src/pico_agent/interfaces.py
get_agent_config(name) ¶
Fetch the remote configuration for an agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The agent's unique identifier. | required |
Returns:
| Type | Description |
|---|---|
Optional[Any] | An |
upsert_agent_config(config) ¶
Create or update the remote configuration for an agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | Any | The | required |
LLM ¶
Bases: Protocol
Protocol for a language-model adapter used by agent proxies.
LangChainAdapter is the built-in implementation.
Source code in src/pico_agent/interfaces.py
invoke(messages, tools) ¶
Send messages to the LLM and return the text response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages | List[Dict[str, str]] | List of message dicts with | required |
tools | List[Any] | LangChain-compatible tool instances bound to the model. | required |
Returns:
| Type | Description |
|---|---|
str | The LLM's text response. |
Source code in src/pico_agent/interfaces.py
invoke_structured(messages, tools, output_schema) ¶
Send messages and parse the response into a structured schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages | List[Dict[str, str]] | List of message dicts. | required |
tools | List[Any] | LangChain-compatible tool instances. | required |
output_schema | Type[Any] | A | required |
Returns:
| Type | Description |
|---|---|
Any | An instance of output_schema. |
Source code in src/pico_agent/interfaces.py
invoke_agent_loop(messages, tools, max_iterations, output_schema=None) ¶
Run a ReAct-style tool loop via LangGraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages | List[Dict[str, str]] | List of message dicts. | required |
tools | List[Any] | LangChain-compatible tool instances. | required |
max_iterations | int | Maximum number of reasoning iterations. | required |
output_schema | Optional[Type[Any]] | Optional Pydantic model for structured final output. | None |
Returns:
| Type | Description |
|---|---|
Any | The final text response, or an instance of output_schema if |
Any | provided. |
Source code in src/pico_agent/interfaces.py
LLMFactory ¶
Bases: Protocol
Protocol for creating LLM instances from model parameters.
LangChainLLMFactory is the built-in implementation that supports OpenAI, Azure, Anthropic, Google, DeepSeek, and Qwen.
Source code in src/pico_agent/interfaces.py
create(model_name, temperature, max_tokens, llm_profile=None) ¶
Create an LLM instance for the given model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name | str | Model identifier, optionally prefixed with a provider (e.g., | required |
temperature | float | Sampling temperature (0.0 -- 2.0). | required |
max_tokens | Optional[int] | Maximum response tokens, or | required |
llm_profile | Optional[str] | Named profile in | None |
Returns:
| Type | Description |
|---|---|
LLM | A configured |
Source code in src/pico_agent/interfaces.py
Exceptions¶
pico_agent.exceptions ¶
Exception hierarchy for pico-agent.
All pico-agent exceptions inherit from AgentError, making it easy to catch any framework error with a single except AgentError clause.
AgentError ¶
AgentDisabledError ¶
Bases: AgentError
Raised when an agent is invoked but its configuration has enabled=False.
The error message follows the pattern:
``Agent '<name>' is disabled via configuration.``
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_name | str | The name of the disabled agent. | required |
Source code in src/pico_agent/exceptions.py
AgentConfigurationError ¶
Bases: AgentError
Raised for missing or invalid agent / provider configuration.
Common causes include missing API keys in LLMConfig or unknown provider names.
AgentLifecycleError ¶
Bases: AgentError
Raised when an operation violates the agent system lifecycle.
For example, attempting to use the system before it has reached the READY phase.
Bootstrap¶
pico_agent.bootstrap ¶
Bootstrap helper that wraps pico_ioc.init() with pico-agent defaults.
The init() function automatically prepends the pico_agent module, loads plugin modules from the pico_agent.plugins entry point group, and harvests any PICO_SCANNERS declarations from user modules.
init(*args, **kwargs) ¶
Initialise a pico-ioc container with pico-agent infrastructure.
Wraps pico_ioc.init() and:
- Prepends the
pico_agentmodule to the module list. - Loads plugin modules from the
pico_agent.pluginsentry point group (disable withPICO_AGENT_AUTO_PLUGINS=false). - Harvests
PICO_SCANNERSfrom all modules and adds them as custom scanners.
All positional and keyword arguments are forwarded to pico_ioc.init().
Returns:
| Type | Description |
|---|---|
PicoContainer | A fully configured |
Example
from pico_agent import init container = init(modules=["myapp"])
Source code in src/pico_agent/bootstrap.py
Providers¶
pico_agent.providers ¶
LangChain-based LLM adapter and multi-provider factory.
LangChainAdapter implements the LLM protocol by delegating to a LangChain BaseChatModel. LangChainLLMFactory implements the LLMFactory protocol and creates adapters for OpenAI, Azure, Anthropic, Google/Gemini, DeepSeek, and Qwen providers.
LangChainAdapter ¶
Bases: LLM
Adapts a LangChain BaseChatModel to the pico-agent LLM protocol.
Handles message conversion, tool binding, structured output, and the ReAct agent loop via LangGraph. Optionally records traces through TraceService.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chat_model | BaseChatModel | A LangChain chat model instance. | required |
tracer | Any | Optional | None |
model_name | str | Human-readable model identifier used in trace names. | '' |
Source code in src/pico_agent/providers.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
invoke(messages, tools) ¶
Send messages to the LLM and return the text response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages | List[Dict[str, str]] | List of message dicts with | required |
tools | List[Any] | LangChain-compatible tool instances to bind. | required |
Returns:
| Type | Description |
|---|---|
str | The model's text response. |
Source code in src/pico_agent/providers.py
invoke_structured(messages, tools, output_schema) ¶
Send messages and parse the response into a Pydantic model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages | List[Dict[str, str]] | List of message dicts. | required |
tools | List[Any] | LangChain-compatible tool instances. | required |
output_schema | Type[Any] | A | required |
Returns:
| Type | Description |
|---|---|
Any | An instance of output_schema populated from the LLM response. |
Source code in src/pico_agent/providers.py
invoke_agent_loop(messages, tools, max_iterations, output_schema=None) ¶
Run a ReAct-style tool loop via LangGraph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages | List[Dict[str, str]] | List of message dicts. | required |
tools | List[Any] | LangChain-compatible tool instances. | required |
max_iterations | int | Maximum reasoning iterations ( | required |
output_schema | Optional[Type[Any]] | Optional Pydantic model for structured final output. | None |
Returns:
| Type | Description |
|---|---|
Any | The final text response, or an output_schema instance if provided. |
Source code in src/pico_agent/providers.py
LangChainLLMFactory ¶
Bases: LLMFactory
Multi-provider LLM factory backed by LangChain chat model classes.
Supports OpenAI, Azure, Anthropic (Claude), Google (Gemini), DeepSeek, and Qwen. Provider detection is automatic based on the model name, or explicit via the "provider:model" syntax (e.g., "openai:gpt-5-mini").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | LLMConfig |
| required |
container | Any | Optional | None |
Raises:
| Type | Description |
|---|---|
AgentConfigurationError | If the required API key is missing. |
ImportError | If the required LangChain provider package is not installed. |
ValueError | If the provider name is unknown. |
Source code in src/pico_agent/providers.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | |
create(model_name, temperature, max_tokens, llm_profile=None) ¶
Create a LangChainAdapter for the given model.
The provider is detected from the model name or specified explicitly using the "provider:model" syntax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name | str | Model identifier, optionally prefixed with provider (e.g., | required |
temperature | float | Sampling temperature. | required |
max_tokens | Optional[int] | Maximum response tokens, or | required |
llm_profile | Optional[str] | Named profile for API-key / base-URL selection. | None |
Returns:
| Type | Description |
|---|---|
LLM | A configured |
Raises:
| Type | Description |
|---|---|
AgentConfigurationError | If the API key for the detected provider is missing. Message pattern: |
ImportError | If the LangChain package for the provider is not installed. Message pattern: |
ValueError | If the provider name is not recognised. Message: |
Source code in src/pico_agent/providers.py
create_chat_model(provider, model_name, profile) ¶
Create a LangChain BaseChatModel for the specified provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider | str | Provider key ( | required |
model_name | str | The provider-specific model name. | required |
profile | Optional[str] | Optional named profile for API key / base URL. | required |
Returns:
| Type | Description |
|---|---|
BaseChatModel | A configured |
Raises:
| Type | Description |
|---|---|
ValueError | If provider is not recognised. |
Source code in src/pico_agent/providers.py
Messages¶
pico_agent.messages ¶
Shared message builder for agent execution.
Converts AgentConfig system / user prompt templates and an input context dictionary into the [{"role": ..., "content": ...}] message list expected by the LLM protocol.
build_messages(config, context) ¶
Build an LLM message list from agent config and input context.
Template placeholders in config.system_prompt and config.user_prompt_template are filled using context keys. If a placeholder cannot be resolved, the raw template is used as-is.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config | AgentConfig | The agent's | required |
context | Dict[str, Any] | Mapping of parameter names to their string values, typically derived from the method signature of the invoked agent method. | required |
Returns:
| Type | Description |
|---|---|
List[Dict[str, str]] | A list of message dicts with |
List[Dict[str, str]] | starting with an optional |
List[Dict[str, str]] |
|
Source code in src/pico_agent/messages.py
Tools¶
pico_agent.tools ¶
Tool wrappers for pico-agent.
ToolWrapper adapts pico-agent @tool-decorated classes to the LangChain tool interface. AgentAsTool wraps child agents so they can be invoked as tools by a parent agent during a ReAct loop.
ToolWrapper ¶
Adapts a pico-agent @tool-decorated instance to the LangChain tool interface.
Exposes name, description, args_schema, and __call__ so the instance can be passed directly to LangChain tool-binding APIs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
instance | Any | An instance of a | required |
config | ToolConfig | The | required |
Raises:
| Type | Description |
|---|---|
ValueError | If the instance does not implement |
Source code in src/pico_agent/tools.py
AgentAsTool ¶
Wraps a DynamicAgentProxy as a LangChain-compatible tool.
This allows a parent agent to invoke a child agent through the LLM's tool-calling mechanism. The tool's args_schema is derived from the child agent's Protocol method signature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_proxy | Any | A | required |
method_name | str | The protocol method to invoke (default: | 'invoke' |
description | str | Optional description override. If empty, the child agent's | '' |
Source code in src/pico_agent/tools.py
Router¶
pico_agent.router ¶
Capability-to-model routing.
ModelRouter translates abstract AgentCapability labels into concrete provider-specific model names, enabling global model changes without modifying individual agent definitions.
ModelRouter ¶
Maps AgentCapability labels to concrete LLM model names.
Default mappings:
============================== ======================== Capability Default model ============================== ======================== AgentCapability.FAST gpt-5-mini AgentCapability.SMART gpt-5.1 AgentCapability.REASONING gemini-3-pro AgentCapability.VISION gpt-4o AgentCapability.CODING claude-3-5-sonnet ============================== ========================
Use update_mapping() to change a mapping at runtime.
Source code in src/pico_agent/router.py
resolve_model(capability, runtime_override=None) ¶
Resolve a capability label to a model name.
If a runtime_override is provided it takes precedence over the capability mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
capability | str | An | required |
runtime_override | Optional[str] | Explicit model name that bypasses the mapping. | None |
Returns:
| Type | Description |
|---|---|
str | The model name string. |
Source code in src/pico_agent/router.py
update_mapping(capability, model) ¶
Change the model associated with a capability.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
capability | str | The | required |
model | str | The new model name. | required |
Source code in src/pico_agent/router.py
Registry¶
pico_agent.registry ¶
Registries for tools and agent configurations.
Provides ToolRegistry (tool storage with tag-based lookup), LocalAgentRegistry (stores configs discovered by AgentScanner), and AgentConfigService (merges central, local, and runtime config).
ToolRegistry ¶
Central registry that stores tool classes/instances and supports tag-based lookup.
Tools are registered by ToolScanner during auto-discovery or manually via register(). At execution time, DynamicAgentProxy and VirtualAgentRunner query this registry to resolve tool dependencies.
Source code in src/pico_agent/registry.py
register(name, tool_cls_or_instance, tags=None) ¶
Register a tool by name with optional tags.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique tool identifier. | required |
tool_cls_or_instance | Any | The tool class or an already-instantiated tool object. | required |
tags | Optional[List[str]] | Optional list of tags for dynamic tool lookup. Tools tagged | None |
Source code in src/pico_agent/registry.py
get_tool(name) ¶
Retrieve a tool by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The tool identifier. | required |
Returns:
| Type | Description |
|---|---|
Optional[Any] | The tool class or instance, or |
get_tool_names_by_tag(tag) ¶
Return all tool names associated with the given tag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tag | str | The tag to search for. | required |
Returns:
| Type | Description |
|---|---|
List[str] | List of matching tool names (may be empty). |
Source code in src/pico_agent/registry.py
get_dynamic_tools(agent_tags) ¶
Collect tool instances matching any of the given tags, plus "global" tools.
Duplicates are excluded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_tags | List[str] | Tags from the agent's | required |
Returns:
| Type | Description |
|---|---|
List[Any] | De-duplicated list of tool instances. |
Source code in src/pico_agent/registry.py
LocalAgentRegistry ¶
In-memory store of agent Protocol classes and their AgentConfig metadata.
Populated by AgentScanner during auto-discovery.
Source code in src/pico_agent/registry.py
register(name, protocol, config) ¶
Register an agent protocol and its configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Unique agent identifier. | required |
protocol | Type | The Protocol class decorated with | required |
config | AgentConfig | The | required |
Source code in src/pico_agent/registry.py
get_config(name) ¶
Retrieve the locally registered AgentConfig.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Agent identifier. | required |
Returns:
| Type | Description |
|---|---|
Optional[AgentConfig] | The |
Source code in src/pico_agent/registry.py
get_protocol(name) ¶
Retrieve the Protocol class for an agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Agent identifier. | required |
Returns:
| Type | Description |
|---|---|
Optional[Type] | The Protocol class, or |
Source code in src/pico_agent/registry.py
AgentConfigService ¶
Merges central, local, and runtime configuration for agents.
Configuration priority (highest wins): central > local > runtime. Central config (from CentralConfigClient) takes precedence over the local config discovered by AgentScanner. Runtime overrides set via update_agent_config() are applied on top of whichever base config is found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
central_client | CentralConfigClient | Remote configuration client. | required |
local_registry | LocalAgentRegistry | Registry populated by | required |
Source code in src/pico_agent/registry.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 | |
get_config(name) ¶
Return the effective AgentConfig for the named agent.
Merges remote, local, and runtime sources.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Agent identifier. | required |
Returns:
| Type | Description |
|---|---|
AgentConfig | The merged |
Raises:
| Type | Description |
|---|---|
ValueError | If no configuration exists for the given name. Message: |
Source code in src/pico_agent/registry.py
update_agent_config(name, **kwargs) ¶
Apply runtime overrides to an agent's configuration.
Overrides are merged on each get_config() call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Agent identifier. | required |
**kwargs | Fields of | {} |
Source code in src/pico_agent/registry.py
reset_agent_config(name) ¶
Remove all runtime overrides for an agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Agent identifier. | required |
Lifecycle¶
pico_agent.lifecycle ¶
Agent system lifecycle management.
AgentSystem tracks the framework's lifecycle phases and publishes LifecycleEvent notifications via pico-ioc's EventBus.
LifecyclePhase ¶
Bases: str, Enum
Phases of the pico-agent system lifecycle.
Attributes:
| Name | Type | Description |
|---|---|---|
INITIALIZING | Container is being built. | |
SCANNING | Agents and tools are being discovered. | |
READY | Container is fully configured. | |
RUNNING | System is accepting requests. | |
SHUTTING_DOWN | Graceful shutdown in progress. | |
STOPPED | System has stopped. |
Source code in src/pico_agent/lifecycle.py
LifecycleEvent dataclass ¶
Bases: Event
Event published when the system transitions between lifecycle phases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase | LifecyclePhase | The new | required |
detail | str | Optional human-readable detail string. | '' |
Source code in src/pico_agent/lifecycle.py
AgentSystem ¶
Lifecycle coordinator that publishes phase transitions via EventBus.
Transitions are published as LifecycleEvent instances. The system moves through: INITIALIZING -> READY -> RUNNING -> SHUTTING_DOWN -> STOPPED.
Source code in src/pico_agent/lifecycle.py
phase property ¶
The current lifecycle phase.
Tracing¶
pico_agent.tracing ¶
Observability tracing for agent, tool, and LLM invocations.
TraceService collects hierarchical TraceRun records. Parent-child relationships are maintained automatically via the run_context ContextVar. Traces are recorded by DynamicAgentProxy and LangChainAdapter.
run_context = ContextVar('run_context', default=None) module-attribute ¶
ContextVar tracking the current trace run ID for parent-child hierarchy.
This is used for trace hierarchy only -- it is not used for DI scoping.
TraceRun dataclass ¶
A single trace record for an agent, tool, or LLM invocation.
Attributes:
| Name | Type | Description |
|---|---|---|
id | str | Unique run identifier (UUID). |
name | str | Human-readable name (e.g., agent name or |
run_type | str | Category string -- |
inputs | Dict[str, Any] | Input data (e.g., messages, arguments). |
parent_id | Optional[str] | ID of the parent run, or |
start_time | float | Unix timestamp when the run started. |
end_time | Optional[float] | Unix timestamp when the run ended (set by |
outputs | Optional[Dict[str, Any]] | Output data (set by |
error | Optional[str] | Error message if the run failed (set by |
extra | Dict[str, Any] | Arbitrary metadata (e.g., |
Source code in src/pico_agent/tracing.py
TraceService ¶
Singleton service that collects hierarchical trace runs.
Traces are stored in memory and can be retrieved via get_traces(). On container shutdown (@cleanup), all traces are flushed.
Source code in src/pico_agent/tracing.py
start_run(name, run_type, inputs, extra=None) ¶
Begin a new trace run.
Automatically sets the parent ID from run_context and updates the context var to the new run ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Human-readable run name. | required |
run_type | str | Category ( | required |
inputs | Dict[str, Any] | Input data to record. | required |
extra | Dict[str, Any] | Optional metadata dict. | None |
Returns:
| Type | Description |
|---|---|
str | The unique run ID (UUID string). |
Source code in src/pico_agent/tracing.py
end_run(run_id, outputs=None, error=None) ¶
Complete a trace run, recording outputs or an error.
Restores run_context to the parent run's ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run_id | str | The ID returned by | required |
outputs | Any | Output data -- can be a string, dict, Pydantic model, or any object (converted via | None |
error | Exception | Exception instance if the run failed. | None |
Source code in src/pico_agent/tracing.py
get_traces() ¶
Return all recorded traces as a list of dictionaries.
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]] | List of dicts, each representing a |
Scheduler¶
pico_agent.scheduler ¶
Concurrency scheduler for async agent operations.
PlatformScheduler uses an asyncio.Semaphore to limit the number of concurrent LLM calls, preventing resource exhaustion during map-reduce workflows and parallel agent invocations.
PlatformScheduler ¶
Asyncio-based concurrency limiter for parallel agent operations.
The concurrency limit is read from the PICO_AGENT_MAX_CONCURRENCY environment variable (default: 10).
Example
async with scheduler.semaphore: ... result = await some_llm_call()