Integration API
The integration module provides adapters for popular AI frameworks.
LangGraph
LangGraph integration for Lambda-Reflexive Synthesis agents.
Provides drop-in replacement for standard ReAct agents with active inference dynamics.
- Usage:
from lrs.integration.langgraph import create_lrs_agent from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(model=”claude-sonnet-4-20250514”) tools = […] # Your tools
agent = create_lrs_agent(llm, tools) result = agent.invoke({“messages”: [{“role”: “user”, “content”: “Task”}]})
- class lrs.integration.langgraph.LRSState[source]
Bases:
TypedDictComplete state for LRS agent.
TypedDict with total=False allows optional fields for incremental updates.
- messages: Any]], <built-in function add>]
- policy_evaluations: List[PolicyEvaluation]
- tool_history: Any]], <built-in function add>]
- class lrs.integration.langgraph.LRSGraphBuilder(llm, registry: ToolRegistry, preferences: Dict[str, float] | None = None, precision_config: Dict[str, PrecisionParameters] | None = None, use_llm_proposals: bool = True)[source]
Bases:
objectConstructs a LangGraph with active inference dynamics.
- Architecture:
propose_policies → evaluate_G → select_policy → execute_tool → update_precision → [decision gate] → {continue | replan | end}
- llm
Language model for policy proposal generation
- registry
ToolRegistry with available tools
- precision_manager
HierarchicalPrecision tracker
- preferences
Goal preferences for pragmatic value calculation
- __init__(llm, registry: ToolRegistry, preferences: Dict[str, float] | None = None, precision_config: Dict[str, PrecisionParameters] | None = None, use_llm_proposals: bool = True)[source]
Initialize graph builder.
- Parameters:
llm – Language model (must have .invoke() or .generate() method)
registry – Tool registry with available tools
preferences – Goal preferences for G calculation. Example: {‘data_retrieved’: 3.0, ‘error’: -5.0}
precision_config – Optional custom precision parameters per level
use_llm_proposals – Whether to use LLM for policy generation (for backward compatibility)
- lrs.integration.langgraph.create_lrs_agent(llm, tools: List[ToolLens], preferences: Dict[str, float] | None = None, **kwargs) StateGraph[source]
Create an LRS-powered agent as drop-in replacement for create_react_agent.
- Parameters:
llm – Language model (Anthropic, OpenAI, etc.)
tools – List of ToolLens objects or LangChain tools
preferences – Goal preferences for pragmatic value calculation
**kwargs – Additional configuration (precision_threshold, etc.)
- Returns:
Compiled StateGraph with active inference dynamics
Examples
>>> from lrs import create_lrs_agent >>> from langchain_anthropic import ChatAnthropic >>> >>> llm = ChatAnthropic(model="claude-sonnet-4-20250514") >>> tools = [ShellTool(), PythonREPLTool()] >>> >>> agent = create_lrs_agent(llm, tools, preferences={'success': 5.0}) >>> >>> result = agent.invoke({ ... "messages": [{"role": "user", "content": "List files in /tmp"}] ... })
- lrs.integration.langgraph.create_monitored_lrs_agent(llm, tools: List[ToolLens], tracker: LRSStateTracker, **kwargs) StateGraph[source]
Create LRS agent with integrated monitoring.
Automatically streams state updates to dashboard tracker.
- Parameters:
llm – Language model
tools – Tool lenses
tracker – LRSStateTracker instance for monitoring
**kwargs – Additional configuration
- Returns:
Compiled StateGraph with monitoring hooks
Classes
- class lrs.integration.langgraph.LRSGraphBuilder(llm, registry: ToolRegistry, preferences: Dict[str, float] | None = None, precision_config: Dict[str, PrecisionParameters] | None = None, use_llm_proposals: bool = True)[source]
Bases:
objectConstructs a LangGraph with active inference dynamics.
- Architecture:
propose_policies → evaluate_G → select_policy → execute_tool → update_precision → [decision gate] → {continue | replan | end}
- llm
Language model for policy proposal generation
- registry
ToolRegistry with available tools
- precision_manager
HierarchicalPrecision tracker
- preferences
Goal preferences for pragmatic value calculation
Builder for LangGraph-based LRS agents.
Methods:
- build() StateGraph[source]
Construct the complete LRS graph.
- Returns:
Compiled StateGraph ready for execution
Example:
from lrs.integration.langgraph import LRSGraphBuilder from langchain_anthropic import ChatAnthropic llm = ChatAnthropic(model="claude-sonnet-4-20250514") builder = LRSGraphBuilder( llm=llm, registry=registry, preferences={'success': 5.0, 'error': -3.0} ) graph = builder.build() # Execute result = graph.invoke({ 'messages': [{'role': 'user', 'content': 'Task'}], 'max_iterations': 10 })
- __init__(llm, registry: ToolRegistry, preferences: Dict[str, float] | None = None, precision_config: Dict[str, PrecisionParameters] | None = None, use_llm_proposals: bool = True)[source]
Initialize graph builder.
- Parameters:
llm – Language model (must have .invoke() or .generate() method)
registry – Tool registry with available tools
preferences – Goal preferences for G calculation. Example: {‘data_retrieved’: 3.0, ‘error’: -5.0}
precision_config – Optional custom precision parameters per level
use_llm_proposals – Whether to use LLM for policy generation (for backward compatibility)
TypedDicts
- class lrs.integration.langgraph.LRSState[source]
Bases:
TypedDictComplete state for LRS agent.
TypedDict with total=False allows optional fields for incremental updates.
State schema for LangGraph agents.
- messages: Any]], <built-in function add>]
- policy_evaluations: List[PolicyEvaluation]
- tool_history: Any]], <built-in function add>]
Functions
- lrs.integration.langgraph.create_lrs_agent(llm, tools: List[ToolLens], preferences: Dict[str, float] | None = None, **kwargs) StateGraph[source]
Create an LRS-powered agent as drop-in replacement for create_react_agent.
- Parameters:
llm – Language model (Anthropic, OpenAI, etc.)
tools – List of ToolLens objects or LangChain tools
preferences – Goal preferences for pragmatic value calculation
**kwargs – Additional configuration (precision_threshold, etc.)
- Returns:
Compiled StateGraph with active inference dynamics
Examples
>>> from lrs import create_lrs_agent >>> from langchain_anthropic import ChatAnthropic >>> >>> llm = ChatAnthropic(model="claude-sonnet-4-20250514") >>> tools = [ShellTool(), PythonREPLTool()] >>> >>> agent = create_lrs_agent(llm, tools, preferences={'success': 5.0}) >>> >>> result = agent.invoke({ ... "messages": [{"role": "user", "content": "List files in /tmp"}] ... })
Convenience function to create a complete LRS agent.
- Parameters:
llm – Language model for policy generation
tools – List of ToolLens objects
preferences – Reward structure (optional)
tracker – LRSStateTracker for monitoring (optional)
use_llm_proposals – Use LLM for proposals vs exhaustive search
- Returns:
Compiled LangGraph agent
LangChain Adapter
LangChain integration for LRS-Agents.
- class lrs.integration.langchain_adapter.LangChainToolLens(tool: BaseTool, timeout: float = 30.0, error_fn: Callable | None = None)[source]
Bases:
ToolLensWraps a LangChain tool as a ToolLens.
Provides timeout handling, prediction error calculation, and statistics tracking for any LangChain tool.
- Parameters:
tool – LangChain BaseTool to wrap
timeout – Maximum execution time in seconds (default: 30.0)
error_fn – Custom function to calculate prediction error
Example
>>> from langchain.tools import Tool >>> lc_tool = Tool(name="search", func=lambda q: f"Results for {q}") >>> lrs_tool = LangChainToolLens(lc_tool, timeout=10.0) >>> result = lrs_tool.get({"query": "test"})
- lrs.integration.langchain_adapter.wrap_langchain_tool(tool: BaseTool, timeout: float = 30.0, error_fn: Callable | None = None) LangChainToolLens[source]
Convenience function to wrap a LangChain tool.
- Parameters:
tool – LangChain BaseTool to wrap
timeout – Maximum execution time in seconds
error_fn – Optional custom error calculation function
- Returns:
Wrapped tool ready for LRS use
- Return type:
Example
>>> from langchain_community.tools import DuckDuckGoSearchRun >>> search = wrap_langchain_tool(DuckDuckGoSearchRun(), timeout=10.0)
Classes
- class lrs.integration.langchain_adapter.LangChainToolLens(tool: BaseTool, timeout: float = 30.0, error_fn: Callable | None = None)[source]
Bases:
ToolLensWraps a LangChain tool as a ToolLens.
Provides timeout handling, prediction error calculation, and statistics tracking for any LangChain tool.
- Parameters:
tool – LangChain BaseTool to wrap
timeout – Maximum execution time in seconds (default: 30.0)
error_fn – Custom function to calculate prediction error
Example
>>> from langchain.tools import Tool >>> lc_tool = Tool(name="search", func=lambda q: f"Results for {q}") >>> lrs_tool = LangChainToolLens(lc_tool, timeout=10.0) >>> result = lrs_tool.get({"query": "test"})
Wraps LangChain BaseTool as ToolLens.
Methods:
Example:
from langchain.tools import Tool from lrs.integration.langchain_adapter import wrap_langchain_tool lc_tool = Tool( name="search", func=lambda q: f"Results for {q}", description="Search tool" ) lrs_tool = wrap_langchain_tool(lc_tool, timeout=10.0) result = lrs_tool.get({'query': 'test'})
Functions
- lrs.integration.langchain_adapter.wrap_langchain_tool(tool: BaseTool, timeout: float = 30.0, error_fn: Callable | None = None) LangChainToolLens[source]
Convenience function to wrap a LangChain tool.
- Parameters:
tool – LangChain BaseTool to wrap
timeout – Maximum execution time in seconds
error_fn – Optional custom error calculation function
- Returns:
Wrapped tool ready for LRS use
- Return type:
Example
>>> from langchain_community.tools import DuckDuckGoSearchRun >>> search = wrap_langchain_tool(DuckDuckGoSearchRun(), timeout=10.0)
Convenience wrapper for LangChain tools.
OpenAI Assistants
OpenAI Assistants API integration for LRS-Agents.
Allows LRS agents to use OpenAI Assistants as policy generators while maintaining Active Inference dynamics for selection and adaptation.
- class lrs.integration.openai_assistants.OpenAIAssistantLens(client: OpenAI, assistant_id: str, thread_id: str | None = None, temperature: float = 0.7, max_wait: int = 30)[source]
Bases:
ToolLensWraps OpenAI Assistant as a ToolLens for LRS integration.
The assistant generates policy proposals, while LRS evaluates them via Expected Free Energy and tracks precision.
Examples
>>> from openai import OpenAI >>> >>> client = OpenAI(api_key="...") >>> assistant = client.beta.assistants.create( ... name="Policy Generator", ... instructions="Generate diverse policy proposals", ... model="gpt-4-turbo-preview" ... ) >>> >>> lens = OpenAIAssistantLens(client, assistant.id) >>> result = lens.get({"query": "Fetch data from API"})
- __init__(client: OpenAI, assistant_id: str, thread_id: str | None = None, temperature: float = 0.7, max_wait: int = 30)[source]
Initialize OpenAI Assistant wrapper.
- Parameters:
client – OpenAI client instance
assistant_id – ID of the assistant to use
thread_id – Optional existing thread ID (creates new if None)
temperature – Sampling temperature (will be adapted by precision)
max_wait – Maximum seconds to wait for assistant response
- get(state: dict) ExecutionResult[source]
Query OpenAI Assistant for policy proposals.
- Parameters:
state – Must contain ‘query’ and optionally ‘precision’
- Returns:
ExecutionResult with proposals or error
- class lrs.integration.openai_assistants.OpenAIAssistantPolicyGenerator(client: OpenAI, model: str = 'gpt-4-turbo-preview', assistant_id: str | None = None)[source]
Bases:
objectHigh-level interface for using OpenAI Assistants as policy generators.
Examples
>>> from openai import OpenAI >>> >>> client = OpenAI() >>> generator = OpenAIAssistantPolicyGenerator( ... client=client, ... model="gpt-4-turbo-preview" ... ) >>> >>> proposals = generator.generate_proposals( ... state={'goal': 'Fetch data'}, ... precision=0.3, ... tool_registry=registry ... )
- lrs.integration.openai_assistants.create_openai_lrs_agent(client: OpenAI, tools: List[ToolLens], model: str = 'gpt-4-turbo-preview', **kwargs) Any[source]
Create LRS agent using OpenAI Assistant for policy generation.
Examples
>>> from openai import OpenAI >>> >>> client = OpenAI(api_key="...") >>> tools = [ShellTool(), PythonTool()] >>> >>> agent = create_openai_lrs_agent(client, tools) >>> result = agent.invoke({ ... "messages": [{"role": "user", "content": "Task"}] ... })
Classes
- class lrs.integration.openai_assistants.OpenAIAssistantLens(client: OpenAI, assistant_id: str, thread_id: str | None = None, temperature: float = 0.7, max_wait: int = 30)[source]
Bases:
ToolLensWraps OpenAI Assistant as a ToolLens for LRS integration.
The assistant generates policy proposals, while LRS evaluates them via Expected Free Energy and tracks precision.
Examples
>>> from openai import OpenAI >>> >>> client = OpenAI(api_key="...") >>> assistant = client.beta.assistants.create( ... name="Policy Generator", ... instructions="Generate diverse policy proposals", ... model="gpt-4-turbo-preview" ... ) >>> >>> lens = OpenAIAssistantLens(client, assistant.id) >>> result = lens.get({"query": "Fetch data from API"})
Wraps OpenAI Assistant as ToolLens for policy generation.
- __init__(client: OpenAI, assistant_id: str, thread_id: str | None = None, temperature: float = 0.7, max_wait: int = 30)[source]
Initialize OpenAI Assistant wrapper.
- Parameters:
client – OpenAI client instance
assistant_id – ID of the assistant to use
thread_id – Optional existing thread ID (creates new if None)
temperature – Sampling temperature (will be adapted by precision)
max_wait – Maximum seconds to wait for assistant response
- get(state: dict) ExecutionResult[source]
Query OpenAI Assistant for policy proposals.
- Parameters:
state – Must contain ‘query’ and optionally ‘precision’
- Returns:
ExecutionResult with proposals or error
- class lrs.integration.openai_assistants.OpenAIAssistantPolicyGenerator(client: OpenAI, model: str = 'gpt-4-turbo-preview', assistant_id: str | None = None)[source]
Bases:
objectHigh-level interface for using OpenAI Assistants as policy generators.
Examples
>>> from openai import OpenAI >>> >>> client = OpenAI() >>> generator = OpenAIAssistantPolicyGenerator( ... client=client, ... model="gpt-4-turbo-preview" ... ) >>> >>> proposals = generator.generate_proposals( ... state={'goal': 'Fetch data'}, ... precision=0.3, ... tool_registry=registry ... )
High-level interface for OpenAI Assistants-based policy generation.
Example:
from openai import OpenAI from lrs.integration.openai_assistants import OpenAIAssistantPolicyGenerator client = OpenAI(api_key="sk-...") generator = OpenAIAssistantPolicyGenerator( client=client, model="gpt-4-turbo-preview" ) proposals = generator.generate_proposals( state={'goal': 'Research topic'}, precision=0.5 )
Functions
- lrs.integration.openai_assistants.create_openai_lrs_agent(client: OpenAI, tools: List[ToolLens], model: str = 'gpt-4-turbo-preview', **kwargs) Any[source]
Create LRS agent using OpenAI Assistant for policy generation.
Examples
>>> from openai import OpenAI >>> >>> client = OpenAI(api_key="...") >>> tools = [ShellTool(), PythonTool()] >>> >>> agent = create_openai_lrs_agent(client, tools) >>> result = agent.invoke({ ... "messages": [{"role": "user", "content": "Task"}] ... })
Create complete LRS agent powered by OpenAI Assistants.
AutoGPT Adapter
AutoGPT integration for LRS-Agents.
Replaces AutoGPT’s command execution loop with LRS Active Inference dynamics.
- class lrs.integration.autogpt_adapter.AutoGPTCommand(command_name: str, command_func: Callable, description: str)[source]
Bases:
ToolLensWraps AutoGPT command as ToolLens.
AutoGPT commands are functions that agents can execute. This wrapper adds prediction error tracking.
- __init__(command_name: str, command_func: Callable, description: str)[source]
Initialize AutoGPT command wrapper.
- Parameters:
command_name – Name of the command
command_func – Function to execute
description – Human-readable description
- get(state: dict) ExecutionResult[source]
Execute AutoGPT command
- class lrs.integration.autogpt_adapter.LRSAutoGPTAgent(name: str, role: str, commands: Dict[str, Callable], llm: Any, goals: List[str] | None = None)[source]
Bases:
objectAutoGPT agent powered by LRS Active Inference.
Replaces AutoGPT’s standard execution loop with: - Precision tracking - Expected Free Energy calculation - Automatic adaptation on failures
Examples
>>> def browse_website(url: str) -> str: ... return requests.get(url).text >>> >>> def write_file(filename: str, content: str) -> dict: ... with open(filename, 'w') as f: ... f.write(content) ... return {'status': 'success'} >>> >>> agent = LRSAutoGPTAgent( ... name="ResearchAgent", ... role="Research assistant", ... commands={ ... 'browse': browse_website, ... 'write': write_file ... } ... ) >>> >>> result = agent.run("Research AI safety and write report")
- __init__(name: str, role: str, commands: Dict[str, Callable], llm: Any, goals: List[str] | None = None)[source]
Initialize LRS AutoGPT agent.
- Parameters:
name – Agent name
role – Agent role description
commands – Dictionary of {name: function} commands
llm – Language model for policy generation
goals – Optional list of goals
- lrs.integration.autogpt_adapter.convert_autogpt_to_lrs(autogpt_config: Dict, llm: Any) LRSAutoGPTAgent[source]
Convert AutoGPT configuration to LRS agent.
- Parameters:
autogpt_config – AutoGPT agent configuration Must contain: ‘name’, ‘role’, ‘commands’
llm – Language model
- Returns:
LRS-powered AutoGPT agent
Examples
>>> config = { ... 'name': 'FileOrganizer', ... 'role': 'File organization assistant', ... 'commands': { ... 'list_files': lambda path: os.listdir(path), ... 'move_file': lambda src, dst: shutil.move(src, dst) ... }, ... 'goals': ['Organize files by type'] ... } >>> >>> agent = convert_autogpt_to_lrs(config, llm)
Classes
- class lrs.integration.autogpt_adapter.AutoGPTCommand(command_name: str, command_func: Callable, description: str)[source]
Bases:
ToolLensWraps AutoGPT command as ToolLens.
AutoGPT commands are functions that agents can execute. This wrapper adds prediction error tracking.
Wraps AutoGPT command function as ToolLens.
- __init__(command_name: str, command_func: Callable, description: str)[source]
Initialize AutoGPT command wrapper.
- Parameters:
command_name – Name of the command
command_func – Function to execute
description – Human-readable description
- get(state: dict) ExecutionResult[source]
Execute AutoGPT command
- class lrs.integration.autogpt_adapter.LRSAutoGPTAgent(name: str, role: str, commands: Dict[str, Callable], llm: Any, goals: List[str] | None = None)[source]
Bases:
objectAutoGPT agent powered by LRS Active Inference.
Replaces AutoGPT’s standard execution loop with: - Precision tracking - Expected Free Energy calculation - Automatic adaptation on failures
Examples
>>> def browse_website(url: str) -> str: ... return requests.get(url).text >>> >>> def write_file(filename: str, content: str) -> dict: ... with open(filename, 'w') as f: ... f.write(content) ... return {'status': 'success'} >>> >>> agent = LRSAutoGPTAgent( ... name="ResearchAgent", ... role="Research assistant", ... commands={ ... 'browse': browse_website, ... 'write': write_file ... } ... ) >>> >>> result = agent.run("Research AI safety and write report")
LRS-powered AutoGPT agent with automatic adaptation.
Methods:
- run(task: str, max_iterations: int = 25) Dict[source]
Execute task using LRS dynamics.
- Parameters:
task – Task description
max_iterations – Maximum execution steps
- Returns:
Execution results with precision trajectory
Example:
from lrs.integration.autogpt_adapter import LRSAutoGPTAgent def search_web(query: str) -> dict: # Implementation return {'results': [...]} agent = LRSAutoGPTAgent( name="ResearchAgent", role="Research assistant", commands={'search_web': search_web}, llm=llm, goals=["Research topic", "Write report"] ) result = agent.run(task="Research AI trends")
- __init__(name: str, role: str, commands: Dict[str, Callable], llm: Any, goals: List[str] | None = None)[source]
Initialize LRS AutoGPT agent.
- Parameters:
name – Agent name
role – Agent role description
commands – Dictionary of {name: function} commands
llm – Language model for policy generation
goals – Optional list of goals
Functions
- lrs.integration.autogpt_adapter.convert_autogpt_to_lrs(autogpt_config: Dict, llm: Any) LRSAutoGPTAgent[source]
Convert AutoGPT configuration to LRS agent.
- Parameters:
autogpt_config – AutoGPT agent configuration Must contain: ‘name’, ‘role’, ‘commands’
llm – Language model
- Returns:
LRS-powered AutoGPT agent
Examples
>>> config = { ... 'name': 'FileOrganizer', ... 'role': 'File organization assistant', ... 'commands': { ... 'list_files': lambda path: os.listdir(path), ... 'move_file': lambda src, dst: shutil.move(src, dst) ... }, ... 'goals': ['Organize files by type'] ... } >>> >>> agent = convert_autogpt_to_lrs(config, llm)
Convert AutoGPT configuration to LRS-compatible format.