Page cover

LangChain Integration

JuliaOS provides seamless integration with LangChain, allowing you to use JuliaOS agents and swarms with LangChain's tools, chains, and agents.

Overview

The LangChain integration includes:

  • Agent Adapters: Convert JuliaOS agents to LangChain agents

  • Tools: Use JuliaOS functionality as LangChain tools

  • Chains: Create LangChain chains that use JuliaOS functionality

Installation

pip install -e /path/to/JuliaOS/packages/python-wrapper[langchain]

Agent Adapters

JuliaOS provides adapters that convert JuliaOS agents to LangChain agents:

Trading Agent Adapter

import asyncio
import os
from dotenv import load_dotenv

from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor
from langchain.chains import LLMChain
from langchain.prompts import ChatPromptTemplate

from juliaos import JuliaOS
from juliaos.agents import AgentType
from juliaos.langchain import JuliaOSTradingAgentAdapter

async def trading_agent_adapter_example():
    # Load environment variables
    load_dotenv()

    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create a trading agent
    agent = await juliaos_client.agents.create_agent(
        name="LangChainTradingAgent",
        agent_type=AgentType.TRADING,
        config={
            "parameters": {
                "risk_tolerance": 0.5,
                "max_position_size": 1000.0,
                "take_profit": 0.05,
                "stop_loss": 0.03,
                "trading_pairs": ["ETH/USDC", "BTC/USDC"],
                "strategies": ["momentum", "mean_reversion"]
            }
        }
    )

    # Start the agent
    await agent.start()

    # Create a LangChain adapter for the agent
    llm = ChatOpenAI(temperature=0.7)
    agent_adapter = JuliaOSTradingAgentAdapter(agent)
    
    # Create a LangChain agent
    langchain_agent = agent_adapter.as_langchain_agent(
        llm=llm,
        verbose=True
    )
    
    # Run the agent
    result = await langchain_agent.arun(
        "Analyze the current market conditions for Ethereum and suggest a trading strategy."
    )
    
    print("LangChain agent result:", result)

    # Disconnect from JuliaOS
    await juliaos_client.disconnect()

Research Agent Adapter

import asyncio
import os
from dotenv import load_dotenv

from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor
from langchain.chains import LLMChain
from langchain.prompts import ChatPromptTemplate

from juliaos import JuliaOS
from juliaos.agents import AgentType
from juliaos.langchain import JuliaOSResearchAgentAdapter

async def research_agent_adapter_example():
    # Load environment variables
    load_dotenv()

    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create a research agent
    agent = await juliaos_client.agents.create_agent(
        name="LangChainResearchAgent",
        agent_type=AgentType.RESEARCH,
        config={
            "parameters": {
                "research_areas": ["market", "technology", "sentiment"],
                "data_sources": ["web", "api", "database"],
                "analysis_methods": ["statistical", "nlp", "trend"],
                "output_formats": ["text", "json", "chart"]
            }
        }
    )

    # Start the agent
    await agent.start()

    # Create a LangChain adapter for the agent
    llm = ChatOpenAI(temperature=0.7)
    agent_adapter = JuliaOSResearchAgentAdapter(agent)
    
    # Create a LangChain agent
    langchain_agent = agent_adapter.as_langchain_agent(
        llm=llm,
        verbose=True
    )
    
    # Run the agent
    result = await langchain_agent.arun(
        "Research the current state of Ethereum Layer 2 solutions and provide a summary."
    )
    
    print("LangChain agent result:", result)

    # Disconnect from JuliaOS
    await juliaos_client.disconnect()

Tools

JuliaOS provides LangChain tools that can be used with any LangChain agent:

Swarm Optimization Tool

import asyncio
import os
from dotenv import load_dotenv

from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import BaseTool

from juliaos import JuliaOS
from juliaos.langchain import SwarmOptimizationTool

async def swarm_optimization_tool_example():
    # Load environment variables
    load_dotenv()

    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create the swarm optimization tool
    swarm_tool = SwarmOptimizationTool(bridge=juliaos_client.bridge)
    
    # Create a LangChain agent with the tool
    llm = ChatOpenAI(temperature=0.7)
    agent = initialize_agent(
        [swarm_tool],
        llm,
        agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
        verbose=True
    )
    
    # Run the agent
    result = await agent.arun(
        "Optimize a function to find the minimum value of f(x) = x^2 + 2*x + 1 in the range [-10, 10]."
    )
    
    print("Agent result:", result)

    # Disconnect from JuliaOS
    await juliaos_client.disconnect()

Blockchain Query Tool

import asyncio
import os
from dotenv import load_dotenv

from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import BaseTool

from juliaos import JuliaOS
from juliaos.langchain import BlockchainQueryTool

async def blockchain_query_tool_example():
    # Load environment variables
    load_dotenv()

    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create the blockchain query tool
    blockchain_tool = BlockchainQueryTool(bridge=juliaos_client.bridge)
    
    # Create a LangChain agent with the tool
    llm = ChatOpenAI(temperature=0.7)
    agent = initialize_agent(
        [blockchain_tool],
        llm,
        agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
        verbose=True
    )
    
    # Run the agent
    result = await agent.arun(
        "What is the current gas price on Ethereum?"
    )
    
    print("Agent result:", result)

    # Disconnect from JuliaOS
    await juliaos_client.disconnect()

Wallet Management Tool

import asyncio
import os
from dotenv import load_dotenv

from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import BaseTool

from juliaos import JuliaOS
from juliaos.langchain import WalletManagementTool

async def wallet_management_tool_example():
    # Load environment variables
    load_dotenv()

    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create the wallet management tool
    wallet_tool = WalletManagementTool(bridge=juliaos_client.bridge)
    
    # Create a LangChain agent with the tool
    llm = ChatOpenAI(temperature=0.7)
    agent = initialize_agent(
        [wallet_tool],
        llm,
        agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
        verbose=True
    )
    
    # Run the agent
    result = await agent.arun(
        "Create a new wallet and check its balance."
    )
    
    print("Agent result:", result)

    # Disconnect from JuliaOS
    await juliaos_client.disconnect()

Chains

JuliaOS provides LangChain chains that use JuliaOS functionality:

Trading Analysis Chain

import asyncio
import os
from dotenv import load_dotenv

from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from langchain.prompts import ChatPromptTemplate

from juliaos import JuliaOS
from juliaos.langchain import TradingAnalysisChain

async def trading_analysis_chain_example():
    # Load environment variables
    load_dotenv()

    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create the trading analysis chain
    llm = ChatOpenAI(temperature=0.7)
    chain = TradingAnalysisChain.from_llm(
        llm=llm,
        bridge=juliaos_client.bridge,
        verbose=True
    )
    
    # Run the chain
    result = await chain.arun(
        market="crypto",
        symbol="ETH",
        timeframe="1d"
    )
    
    print("Chain result:", result)

    # Disconnect from JuliaOS
    await juliaos_client.disconnect()

Research Chain

import asyncio
import os
from dotenv import load_dotenv

from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from langchain.prompts import ChatPromptTemplate

from juliaos import JuliaOS
from juliaos.langchain import ResearchChain

async def research_chain_example():
    # Load environment variables
    load_dotenv()

    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create the research chain
    llm = ChatOpenAI(temperature=0.7)
    chain = ResearchChain.from_llm(
        llm=llm,
        bridge=juliaos_client.bridge,
        verbose=True
    )
    
    # Run the chain
    result = await chain.arun(
        topic="Ethereum Layer 2 Solutions",
        depth="medium",
        focus=["technology", "adoption", "performance"]
    )
    
    print("Chain result:", result)

    # Disconnect from JuliaOS
    await juliaos_client.disconnect()

Custom Tools

You can create custom LangChain tools that use JuliaOS functionality:

import asyncio
import os
from dotenv import load_dotenv

from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, AgentType
from langchain.tools import BaseTool

from juliaos import JuliaOS

class CustomJuliaOSTool(BaseTool):
    name = "custom_juliaos_tool"
    description = "A custom tool that uses JuliaOS functionality."
    
    def __init__(self, bridge):
        super().__init__()
        self.bridge = bridge
    
    async def _arun(self, query: str) -> str:
        # Execute a command on the JuliaOS backend
        result = await self.bridge.execute("custom.command", {"query": query})
        
        if result.success:
            return str(result.data)
        else:
            return f"Error: {result.error}"
    
    def _run(self, query: str) -> str:
        # Synchronous version (calls the async version)
        loop = asyncio.get_event_loop()
        return loop.run_until_complete(self._arun(query))

async def custom_tool_example():
    # Load environment variables
    load_dotenv()

    # Initialize JuliaOS
    juliaos_client = JuliaOS(host="localhost", port=8052)
    await juliaos_client.connect()

    # Create the custom tool
    custom_tool = CustomJuliaOSTool(bridge=juliaos_client.bridge)
    
    # Create a LangChain agent with the tool
    llm = ChatOpenAI(temperature=0.7)
    agent = initialize_agent(
        [custom_tool],
        llm,
        agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
        verbose=True
    )
    
    # Run the agent
    result = await agent.arun(
        "Use the custom JuliaOS tool to perform a task."
    )
    
    print("Agent result:", result)

    # Disconnect from JuliaOS
    await juliaos_client.disconnect()

See Also

  • Python Wrapper - Learn more about the JuliaOS Python wrapper

  • Agents - Learn more about agents in JuliaOS

  • Swarms - Learn more about swarms in JuliaOS