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
JuliaOS
ClientThe 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
Agent
ClassRepresents 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
Swarm
ClassRepresents 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
Wallet
ClassRepresents 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 JuliaOSAgent
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.