LogoLogo
  • JuliaOS Documentation Hub
  • About JuliaOS
    • Mission & Vision
    • Features and Capabilities
    • Roadmap
    • Tokenomics
  • Ecosystem
    • Overview
  • Partners
    • Heurist
    • Fetch.ai
    • Soulgraph
    • cheqd.io
    • Aethir
    • Anyone
    • TensorLabs
    • Hashpower
  • Technology
    • Overview
    • Open Source
      • Modular Framework
      • CLI Mode
    • AI Platform
      • Dashboard
      • Agent Management
      • Swarm Management
      • Marketplace
      • Mining
    • LLM
    • Launchpad
    • Robotics & IOT
      • SwarmIOT
      • Modular AI with Robotics
        • J3OS MiniLLM
          • 🔧 Use Cases
  • Technical
    • Overview
    • Developer Hub
      • Getting Started
        • Installation Guide
          • Github Guide
        • Basic Concepts
        • Quick Start Guide
          • Handling secrets
        • Examples and Use
          • Example: Using the Trading Functionality
          • Example: Using the Benchmarking Feature
          • Example: Multi-Agent Swarm Coordination
          • Example: Using the Python Wrapper for LLM Integration
          • Example: Using Cross-Chain Bridges
          • Example: Creating and Running a Swarm Optimization
          • Page 4
      • Best Practices
        • Performance Tuning
        • Agent/Swarm Design Patterns
        • Best Practices & Patterns
        • Security Best Practices
      • CLI
        • JuliaOS CLI Interface
        • Agent Management (CLI)
        • CLI Configuration
        • Cross-Chain Hub (CLI)
        • Swarm Management (CLI)
        • CLI Troubleshooting
        • Wallet Management (CLI)
      • Framework SDK
        • Modules
          • Bridge
          • Agents Module
          • Dex
          • Swarms Module
          • Wallet
        • Python Wrapper
          • LangChain Integration
          • Python Wrapper
      • Contributing Guide
      • Extending JuliaOS
      • Development Setup & Conventions
      • Testing & Debugging
      • Troubleshooting
    • Architecture
      • High Level JuliaOS
      • CLI <-> Backend Communication
      • Data Storage Architecture
      • Framework Internals
      • Architecture Deep Dive
        • Architectual Notes
    • Concepts
      • Core Features & Concepts
      • Agents
        • Agent Skills & Specializations
      • Swarms
      • Neural Networks
      • Blockchains & Chains
      • Bridges (Cross-Chain)
      • Integrations
        • Google ADK
        • LLMs
        • Price Feed
        • DEX Integration
      • Storage
      • Trading Capabilities
      • Use Cases
      • Wallets
      • Portfolio Optimization
  • Research
    • JuliaOS Research
  • API Documentation
    • API Reference
      • API Reference: Julia Backend Commands
      • API Reference: CLI Commands
      • API Reference: Node.js API
      • API Reference: Python API
      • API Reference
  • Community
    • Community & Support
  • FAQ
    • General
    • Technical
    • Community
Powered by GitBook
On this page
  • JuliaOS Client
  • Agent Class
  • Swarm Class
  • Swarm Algorithms
  • NumPy Integration
  • Wallet Class
  • LangChain Integration
Export as PDF
  1. API Documentation
  2. API Reference

API Reference: Python API

This page details the programmatic API provided by the JuliaOS Python wrapper (pip install juliaos).

(Note: This is based on the wrapper's README. Exact method signatures, parameters, and return types should be confirmed by inspecting the wrapper's source code in /packages/python-wrapper/juliaos/ and potentially using type hints or help())

JuliaOS Client

The main entry point for interacting with the JuliaOS backend.

from juliaos import JuliaOS
import asyncio

async def main():
    # Using async context manager (recommended)
    async with JuliaOS(host='localhost', port=8052) as client:
        print("Connected to JuliaOS backend!")

        # Use other methods...
        agents = await client.list_agents()
        print(f"Found {len(agents)} agents.")
    # Connection is automatically closed when exiting the context

# Or using manual connection management
async def alternative():
    client = JuliaOS(host='localhost', port=8052)
    await client.connect()
    print("Connected to JuliaOS backend!")

    # Use other methods...
    agents = await client.list_agents()
    print(f"Found {len(agents)} agents.")

    await client.disconnect()

# asyncio.run(main())

Key Methods:

  • __init__(host: str = 'localhost', port: int = 8052, api_key: Optional[str] = None, auto_connect: bool = False): Initializes the client.

  • connect(): Establishes connection to the backend.

  • disconnect(): Closes the connection.

  • __aenter__(), __aexit__(): Async context manager support for cleaner code.

  • create_agent(name: str, agent_type: str, config: dict) -> Agent: Creates a new agent.

  • list_agents() -> List[AgentInfo]: Lists existing agents.

  • get_agent(agent_id: str) -> Agent: Retrieves an agent instance by ID.

  • create_swarm(algorithm: str | dict, config: dict, **kwargs) -> Swarm: Creates a new swarm (algorithm can be string type or dict with type/params).

  • list_swarms() -> List[SwarmInfo]: Lists existing swarms.

  • get_swarm(swarm_id: str) -> Swarm: Retrieves a swarm instance by ID.

  • connect_wallet(type: str, **kwargs) -> Wallet: Connects a wallet (details depend on type - likely limited in Python).

  • get_chain(chain_name: str) -> Chain: Gets an interface for chain operations.

  • get_dex(dex_name: str) -> DEX: Gets an interface for DEX operations.

Agent Class

Represents a single agent instance.

# Assuming 'agent' is an instance obtained from client.get_agent() or client.create_agent()

await agent.start()
status = await agent.get_status()
result = await agent.execute_task("specific_task_name", data={...})
await agent.stop()

Key Methods:

  • start(): Starts the agent's operation.

  • stop(): Stops the agent.

  • get_status() -> dict: Retrieves the current status and state.

  • execute_task(task_name: str, data: dict) -> dict: Sends a task to the agent.

  • update_config(config: dict): Updates the agent's configuration.

  • add_skill(...), remove_skill(...): Manage agent skills (if implemented).

Swarm Class

Represents a swarm instance.

# Assuming 'swarm' is an instance obtained from client.get_swarm() or client.create_swarm()

await swarm.start()
status = await swarm.get_status()
await swarm.add_agent(agent_id)

# For optimization swarms:
def objective_func(x):
    return sum(xi**2 for xi in x)

opt_result = await swarm.optimize(
    objective=objective_func,
    iterations=100,
    minimize=True
)
print(opt_result.best_solution, opt_result.best_fitness)

await swarm.stop()

Key Methods:

  • start(): Starts the swarm's operation/optimization.

  • stop(): Stops the swarm.

  • get_status() -> dict: Retrieves swarm status.

  • add_agent(agent_id: str): Adds an agent to the swarm.

  • remove_agent(agent_id: str): Removes an agent.

  • optimize(objective: Callable, iterations: int, minimize: bool = True, **kwargs) -> OptimizationResult: Runs the swarm optimization algorithm.

Swarm Algorithms

The Python wrapper provides direct access to various swarm optimization algorithms:

from juliaos import JuliaOS
from juliaos.swarms import (
    DifferentialEvolution, ParticleSwarmOptimization,
    GreyWolfOptimizer, AntColonyOptimization,
    GeneticAlgorithm, WhaleOptimizationAlgorithm,
    HybridDEPSO
)

async def main():
    async with JuliaOS() as juliaos:
        # Create algorithm instance
        de = DifferentialEvolution(juliaos.bridge)

        # Define objective function
        def sphere(x):
            return sum(xi**2 for xi in x)

        # Define bounds
        bounds = [(-5.0, 5.0), (-5.0, 5.0)]

        # Run optimization
        result = await de.optimize(
            objective_function=sphere,
            bounds=bounds,
            config={
                "population_size": 30,
                "max_generations": 100
            }
        )

        print(f"Best fitness: {result['best_fitness']}")
        print(f"Best position: {result['best_position']}")

NumPy Integration

The Python wrapper provides seamless integration with NumPy for scientific computing and optimization:

import numpy as np
from juliaos import JuliaOS
from juliaos.swarms import DifferentialEvolution

# Define objective function using NumPy
def rastrigin(x: np.ndarray) -> float:
    return 10 * len(x) + np.sum(x**2 - 10 * np.cos(2 * np.pi * x))

async def main():
    async with JuliaOS() as juliaos:
        # Create algorithm instance
        de = DifferentialEvolution(juliaos.bridge)

        # Define bounds as NumPy array
        bounds = np.array([[-5.12, 5.12]] * 5)  # 5-dimensional problem

        # Run optimization
        result = await de.optimize(
            objective_function=rastrigin,
            bounds=bounds,
            config={
                "population_size": 30,
                "max_generations": 100
            }
        )

        # Access result with NumPy arrays
        best_position = result['best_position_np']  # NumPy array
        best_fitness = result['best_fitness']

        print(f"Best position: {best_position}")
        print(f"Best fitness: {best_fitness}")

NumPy Utilities:

  • numpy_objective_wrapper(func: Callable) -> Callable: Wraps a NumPy-based objective function.

  • numpy_bounds_converter(bounds: Union[List[Tuple[float, float]], np.ndarray]) -> List[Tuple[float, float]]: Converts NumPy-style bounds.

  • numpy_result_converter(result: Dict[str, Any]) -> Dict[str, Any]: Converts results to include NumPy arrays.

Wallet Class

Represents a connected wallet (likely limited functionality compared to JS WalletManager).

# Assuming 'wallet' is an instance from client.connect_wallet()

balance = await wallet.get_balance()
tx_receipt = await wallet.send_transaction(to='0x...', amount='0.1', token='ETH')
signature = await wallet.sign_message("Hello JuliaOS")

Key Methods (Likely):

  • get_balance(token: str = None) -> str: Gets native or token balance.

  • send_transaction(to: str, amount: str, token: str = None, **kwargs) -> TransactionReceipt: Sends transaction (requires backend key management or external signer integration).

  • sign_message(message: str) -> str: Signs message (requires backend key management or external signer integration).

LangChain Integration

Provides tools and wrappers for LangChain.

  • JuliaOSAgentAdapter: Adapts a JuliaOS Agent for use as a LangChain agent.

  • Tools (e.g., SwarmOptimizationTool, BlockchainQueryTool): Allow LangChain agents to use JuliaOS capabilities.

  • Memory (e.g., JuliaOSConversationBufferMemory): Use JuliaOS storage for LangChain memory.

  • Chains (e.g., SwarmOptimizationChain): Pre-built chains using JuliaOS components.

  • Retrievers (e.g., JuliaOSVectorStoreRetriever): Use JuliaOS storage for retrieval.

See LangChain Integration Guide (or dedicated page) for details.

PreviousAPI Reference: Node.js APINextAPI Reference