API Reference

This section contains the complete API reference for python-agents.

Client

LLM client with tool calling capabilities.

This module provides the LLMClient class, which wraps the OpenAI API to provide a simple interface for interacting with Large Language Models. It supports automatic tool calling, where Python functions are converted to tool schemas and executed when the LLM requests them.

class python_agents.client.LLMClient(model_name=None, base_url='https://openrouter.ai/api/v1')[source]

Bases: object

Client for interacting with Large Language Models with tool calling support.

LLMClient provides a high-level interface for calling LLMs through the OpenAI API. It automatically handles tool registration, schema generation from Python functions, and tool execution when requested by the LLM. By default, it uses OpenRouter as the API endpoint, but can be configured for any OpenAI-compatible service.

model_name

Default model to use for LLM calls (e.g., “openai/gpt-4”).

Type:

str

client

Underlying async OpenAI client.

Type:

AsyncOpenAI

tools

Dictionary mapping tool names to their functions and schemas.

Type:

dict

Example

Basic usage without tools:

client = LLMClient("openai/gpt-4.1-mini")
response = await client.invoke("What is 2+2?")
print(response.message.content)

Using tools with automatic function calling:

def calculator(operation: str, a: int, b: int) -> int:
    '''Perform arithmetic operations.

    Args:
        operation: The operation ('+', '-', '*', '/')
        a: First number
        b: Second number

    Returns:
        Result of the operation
    '''
    if operation == "+":
        return a + b
    # ... more operations

client = LLMClient("openai/gpt-4-turbo")
client.add_tool(calculator)
response = await client.invoke("What is 15 + 27?")
# LLM will automatically call calculator tool
__init__(model_name=None, base_url='https://openrouter.ai/api/v1')[source]

Initialize the LLM client.

Parameters:
  • model_name (str, optional) – Default model name to use for requests. Can be overridden per request. Format depends on the API provider (e.g., “openai/gpt-4-turbo” for OpenRouter). Defaults to None.

  • base_url (str, optional) – Base URL for the OpenAI-compatible API. Defaults to “https://openrouter.ai/api/v1”.

Note

Requires OPENAI_API_KEY environment variable to be set for authentication. When using OpenRouter, this should be your OpenRouter API key.

add_tool(func)[source]

Register a Python function as a tool that the LLM can call.

The function is automatically converted to an OpenAI function schema using introspection of the function signature, type hints, and docstring. The LLM can then request to call this tool during conversation.

Parameters:

func (callable) – A Python function to register as a tool. The function should have: - Type hints for all parameters - A clear docstring describing what it does - A descriptive name All parameters must be JSON-serializable types (str, int, float, bool).

Example:

def get_weather(location: str, units: str = "celsius") -> str:
    '''Get the weather for a location.

    Args:
        location: City name
        units: Temperature units (celsius or fahrenheit)
    '''
    # Implementation
    return f"Weather in {location}: 20°{units[0].upper()}"

client.add_tool(get_weather)

Note

The function will be called synchronously when the LLM requests it, and the result will be stringified before being returned to the LLM.

async invoke(query, model_name=None, verbose=False)[source]

Send a query to the LLM and handle any tool calls.

This is the main method for interacting with the LLM. It accepts various input formats, calls the LLM, automatically executes any requested tool calls, and returns the final response. The method handles one round of tool calling - if the LLM requests tools, they are all executed, and then a final LLM call is made with the tool results.

Parameters:
  • query (list[Message] | Message | str) – The input to send to the LLM. Can be: - str: Converted to a single user message - Message: Single message to send - list[Message]: Full conversation history

  • model_name (str, optional) – Model to use for this request. Overrides the default model_name set during initialization. Defaults to None.

  • verbose (bool, optional) – If True, prints response content to stdout when no tools are called. Defaults to False.

Returns:

The LLM’s response containing the message content.

Access the text response via response.message.content.

Return type:

ChatCompletionChoice

Raises:
  • ValueError – If query is not a str, Message, or list[Message].

  • RuntimeError – If the LLM requests an unregistered tool.

Example:

# String query
response = await client.invoke("Hello!")

# With message history
messages = [
    Message(role="system", content="You are helpful"),
    Message(role="user", content="Hi")
]
response = await client.invoke(messages)

# Override model
response = await client.invoke("Quick question", model_name="openai/gpt-3.5-turbo")

Note

This method only handles ONE round of tool calling. For multi-step reasoning with multiple tool call rounds, use ReactAgent instead.

Agents

class python_agents.agents.ReactAgent(client, max_iterations=10)[source]

Bases: object

__init__(client, max_iterations=10)[source]
async run(task, verbose=False)[source]

Tools

python_agents.tools.create_tool_schema(func)[source]

Add a custom Python function as a tool

Parameters:

func – A Python function to add as a tool

python_agents.tools.convert_tool_format(tool)[source]

Convert MCP tool format to OpenAI tool format

Message

class python_agents.message.Message[source]

Bases: TypedDict

role: str
content: str
tool_call_id: str = None
name: str = None
tool_calls: list[Any] = None

Memory

Memory management for conversation history in agents.

This module provides abstract and concrete implementations for storing and managing conversation history (messages) in AI agents. Memory classes handle message storage, retrieval, and manipulation for maintaining context across agent interactions.

class python_agents.memory.BaseMemory[source]

Bases: ABC

Abstract base class for memory implementations.

BaseMemory defines the interface that all memory implementations must follow. It provides methods for adding messages, clearing history, and managing system messages. Subclasses must implement all abstract methods to provide specific storage strategies.

abstractmethod add_message(message)[source]

Add a message to the conversation history.

Parameters:

message (Message) – The message to add to memory. Should contain role, content, and optionally tool call information.

abstractmethod clear()[source]

Clear all messages from memory.

Removes all stored messages, resetting the conversation history to empty state.

abstractmethod insert_system_message(message)[source]

Insert or replace a system message at the beginning of conversation history.

System messages provide instructions or context to the LLM and should always appear first in the message list. This method either inserts a new system message or replaces an existing one.

Parameters:

message (Message) – The system message to insert. Should have role=”system”.

class python_agents.memory.SimpleMemory[source]

Bases: BaseMemory

Simple in-memory storage for conversation history.

SimpleMemory provides a basic list-based implementation of conversation history storage. Messages are stored in chronological order in a Python list, with no size limits or special processing. This implementation is suitable for most use cases where conversation history fits in memory.

messages

List of messages in chronological order.

Type:

list[Message]

Example

Basic usage with message storage:

memory = SimpleMemory()
memory.add_message(Message(role="user", content="Hello"))
memory.add_message(Message(role="assistant", content="Hi there!"))
print(len(memory.messages))  # 2
memory.clear()
print(len(memory.messages))  # 0
__init__()[source]

Initialize an empty SimpleMemory instance.

add_message(message)[source]

Add a message to the end of the conversation history.

Messages are appended in the order they are added, maintaining chronological order.

Parameters:

message (Message) – The message to add. Can be user, assistant, system, or tool message.

insert_system_message(message)[source]

Insert or replace the system message at the beginning of the conversation.

This method ensures the system message is always first in the message list. If a system message already exists at position 0, it is replaced. Otherwise, the new system message is inserted at the beginning.

Parameters:

message (Message) – The system message to insert. Should have role=”system”.

Note

System messages provide instructions or context to the LLM and must appear before any user or assistant messages to be effective.

clear()[source]

Clear all messages from memory.

Resets the conversation history to an empty state by clearing the messages list.

Utilities

python_agents.utils.pretty_print(data)[source]