Skip to main content

Overview

The Microchain Agent is an autonomous trading agent built on the Microchain framework, which enables function-calling capabilities for LLMs. This agent can perform complex multi-step operations including market research, trading, and learning from experience.

Base Class: DeployableMicrochainAgentAbstract

Abstract base class for all Microchain-based agents.
class DeployableMicrochainAgentAbstract(DeployableAgent, metaclass=abc.ABCMeta):
    model = SupportedModel.gpt_4o
    max_iterations: int | None = 50
    import_actions_from_memory = 0
    import_actions_from_memory_from: DatetimeUTC | None = None
    sleep_between_iterations = 0
    allow_stop: bool = True
    identifier: AgentIdentifier
    functions_config: FunctionsConfig
    initial_system_prompt: str

Configuration Properties

model
SupportedModel
default:"SupportedModel.gpt_4o"
The LLM model to use for the agent
max_iterations
int | None
default:"50"
Maximum number of iterations per run. Set to None for unlimited iterations.
import_actions_from_memory
int
default:"0"
Number of past actions to import from memory on initialization
import_actions_from_memory_from
DatetimeUTC | None
default:"None"
Only import memories after this timestamp
sleep_between_iterations
int
default:"0"
Seconds to sleep between iterations
allow_stop
bool
default:"True"
Whether the agent can use the Stop function to end execution
identifier
AgentIdentifier
Unique identifier for the agent
functions_config
FunctionsConfig
Configuration specifying which function categories to enable
initial_system_prompt
str
The system prompt that defines the agent’s behavior

Core Components

long_term_memory
LongTermMemoryTableHandler
Stores agent’s execution history and learnings
prompt_handler
PromptTableHandler
Manages system prompt versioning and updates
prompt_inject_handler
PromptInjectHandler
Handles dynamic prompt injection for special features
agent
Agent
The Microchain Agent instance
goal_manager
GoalManager | None
Optional goal management system for autonomous behavior

Methods

load

def load(self) -> None
Initializes the agent’s components including memory, prompt handlers, and the Microchain agent.

run

def run(self, market_type: MarketType) -> None
Main execution loop for the agent. Runs iterations until stopping condition is met.

before_iteration_callback

def before_iteration_callback(self) -> CallbackReturn
Hook called before each iteration. Return CallbackReturn.STOP to halt execution.

after_iteration_callback

def after_iteration_callback(self) -> CallbackReturn
Hook called after each iteration. Return CallbackReturn.STOP to halt execution.

Production Agent: DeployableMicrochainAgent

Standard Microchain agent with full trading capabilities.
class DeployableMicrochainAgent(DeployableMicrochainAgentAbstract):
    identifier = MICROCHAIN_AGENT_OMEN
    functions_config = TRADING_AGENT_SYSTEM_PROMPT_CONFIG.functions_config
    initial_system_prompt = TRADING_AGENT_SYSTEM_PROMPT_CONFIG.system_prompt

Usage

from prediction_market_agent.agents.microchain_agent.deploy import (
    DeployableMicrochainAgent
)
from prediction_market_agent_tooling.markets.markets import MarketType

agent = DeployableMicrochainAgent(
    enable_langfuse=True,
    place_trades=True,
)

agent.deploy(
    market_type=MarketType.OMEN,
)

Learning Variants

Agents with “just born” system prompts that can modify their own behavior.

DeployableMicrochainModifiableSystemPromptAgent0/1/2

Agents that start with minimal knowledge and learn through experience.
class DeployableMicrochainModifiableSystemPromptAgent0(
    DeployableMicrochainModifiableSystemPromptAgentAbstract
):
    identifier = MICROCHAIN_AGENT_OMEN_LEARNING_0
functions_config
FunctionsConfig
Uses JUST_BORN_SYSTEM_PROMPT_CONFIG with learning functions enabled
initial_system_prompt
str
Minimal “just born” prompt allowing the agent to discover its capabilities

DeployableMicrochainModifiableSystemPromptAgent3

Llama 3.1 variant with reduced iterations.
class DeployableMicrochainModifiableSystemPromptAgent3(
    DeployableMicrochainModifiableSystemPromptAgentAbstract
):
    identifier = MICROCHAIN_AGENT_OMEN_LEARNING_3
    model = SupportedModel.llama_31_instruct
    max_iterations = 10  # Limited by API token constraints

Goal-Managed Agent

DeployableMicrochainWithGoalManagerAgent0

Agent with autonomous goal setting and evaluation.
class DeployableMicrochainWithGoalManagerAgent0(DeployableMicrochainAgent):
    identifier = MICROCHAIN_AGENT_OMEN_WITH_GOAL_MANAGER
    model = SupportedModel.gpt_4o
    functions_config = TRADING_AGENT_SYSTEM_PROMPT_MINIMAL_CONFIG.functions_config
    initial_system_prompt = TRADING_AGENT_SYSTEM_PROMPT_MINIMAL_CONFIG.system_prompt

Goal Manager Configuration

def build_goal_manager(self, agent: Agent) -> GoalManager:
    return GoalManager(
        agent_id=self.identifier,
        high_level_description="You are a trader agent in prediction markets, aiming to maximise your long-term profit.",
        agent_capabilities=f"You have the following capabilities:\n{get_functions_summary_list(agent.engine)}",
        retry_limit=1,
        goal_history_limit=10,
    )

Supported Models

class SupportedModel(str, Enum):
    gpt_4o = "gpt-4o-2024-08-06"
    gpt_4o_mini = "gpt-4o-mini-2024-07-18"
    gpt_4_turbo = "gpt-4-turbo"
    llama_31_instruct = "meta/meta-llama-3.1-405b-instruct"
    deepseek_chat = "deepseek/deepseek-chat"
    deepseek_r1 = "deepseek/deepseek-r1"
    gemini_20_flash = "google/gemini-2.0-flash-001"

Function Categories

The agent can be configured with various function categories:
common_functions
bool
Basic utility functions
include_agent_functions
bool
Agent self-modification capabilities
include_universal_functions
bool
API calls, code execution, web search
include_job_functions
bool
Task scheduling and automation
include_learning_functions
bool
Memory and learning capabilities
include_trading_functions
bool
Market analysis and trading operations
include_sending_functions
bool
Fund transfer capabilities
include_twitter_functions
bool
Social media integration
include_nft_functions
bool
NFT operations
balance_functions
bool
Balance checking and management

Building Custom Agents

Custom Function Configuration

from prediction_market_agent.agents.microchain_agent.deploy import (
    DeployableMicrochainAgentAbstract
)
from prediction_market_agent.agents.microchain_agent.prompts import (
    FunctionsConfig
)
from prediction_market_agent.agents.identifiers import AgentIdentifier

class MyCustomMicrochainAgent(DeployableMicrochainAgentAbstract):
    identifier = "my-custom-agent"
    model = SupportedModel.gpt_4o_mini
    max_iterations = 30
    
    functions_config = FunctionsConfig(
        common_functions=True,
        include_trading_functions=True,
        include_universal_functions=True,
        # Disable other function categories
        include_agent_functions=False,
        include_learning_functions=False,
    )
    
    initial_system_prompt = """
    You are a focused trading agent.
    Your goal is to find and trade on profitable prediction markets.
    Use web search to research markets before trading.
    """

agent = MyCustomMicrochainAgent()
agent.deploy_local(market_type=MarketType.OMEN)

Importing Past Memory

from prediction_market_agent_tooling.tools.datetime_utc import DatetimeUTC

class MemoryImportingAgent(DeployableMicrochainAgent):
    import_actions_from_memory = 20  # Import last 20 actions
    import_actions_from_memory_from = DatetimeUTC(2024, 1, 1)  # From 2024 onwards

agent = MemoryImportingAgent()
agent.deploy_local(market_type=MarketType.OMEN)

Custom Callbacks

class CallbackAgent(DeployableMicrochainAgent):
    def before_iteration_callback(self) -> CallbackReturn:
        # Check some condition
        if should_stop():
            logger.info("Stopping agent due to custom condition")
            return CallbackReturn.STOP
        return CallbackReturn.CONTINUE
    
    def after_iteration_callback(self) -> CallbackReturn:
        # Log metrics after each iteration
        log_agent_metrics(self.agent)
        return CallbackReturn.CONTINUE

Helper Functions

build_agent

def build_agent(
    keys: APIKeys,
    market_type: MarketType,
    model: SupportedModel,
    unformatted_system_prompt: str,
    functions_config: FunctionsConfig,
    enable_langfuse: bool,
    long_term_memory: LongTermMemoryTableHandler | None = None,
    max_tokens: int = 8196,
    allow_stop: bool = True,
    bootstrap: str | None = None,
    raise_on_error: bool = True,
) -> Agent
Builds a Microchain agent with specified configuration.

save_agent_history

def save_agent_history(
    long_term_memory: LongTermMemoryTableHandler,
    agent: Agent,
    initial_system_prompt: str,
    save_last_n: int | None = None,
) -> None
Saves agent’s execution history to long-term memory.

get_functions_summary_list

def get_functions_summary_list(engine: Engine) -> str
Generates a formatted list of available functions for the agent.

Advanced Features

Smart Contract Integration

def build_functions_from_smart_contract(
    keys: APIKeys,
    contract_address: ChecksumAddress,
    contract_name: str
) -> list[Function]
Automatically generates Microchain functions from smart contract ABIs.

System Prompt Versioning

The agent automatically saves and restores system prompts:
def get_unformatted_system_prompt(
    unformatted_prompt: str,
    prompt_table_handler: PromptTableHandler | None
) -> str

Required API Keys

OPENAI_API_KEY
str
Required for GPT models
REPLICATE_API_KEY
str
Required for Llama models
OPENROUTER_API_KEY
str
Required for DeepSeek and Gemini models
TAVILY_API_KEY
str
Required if search functions are enabled

Source Location

prediction_market_agent/agents/microchain_agent/deploy.py
prediction_market_agent/agents/microchain_agent/microchain_agent.py

Build docs developers (and LLMs) love