### DeployConfig Initialization Example Source: https://docs.leeroo.com/docs/deployment/api-reference Example of initializing a DeployConfig instance and accessing its properties. ```python from kapso.deployment import DeployConfig config = DeployConfig( solution=solution, env_vars={ "API_KEY": "xxx", "DEBUG": "true", }, timeout=600, coding_agent="gemini", ) print(config.code_path) # "/path/to/solution" print(config.goal) # "Create a sentiment API" ``` -------------------------------- ### start() Source: https://docs.leeroo.com/docs/deployment/api-reference Starts or restarts a stopped deployment. ```APIDOC ## start() ### Description Start or restart a stopped deployment. ### Signature `def start(self) -> None` ``` -------------------------------- ### Start knowledge-graph infrastructure Source: https://docs.leeroo.com/docs/installation Run the provided script to start local Weaviate and Neo4j instances in Docker. ```bash bash scripts/start_infra.sh ``` -------------------------------- ### Software.start() usage example Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates restarting a stopped deployment and running it again. ```python # After stop() deployed_program.stop() print(deployed_program.is_healthy()) # False # Restart deployed_program.start() print(deployed_program.is_healthy()) # True # Can run again result = deployed_program.run({"text": "hello again"}) ``` -------------------------------- ### Software.start() method definition Source: https://docs.leeroo.com/docs/deployment/api-reference Defines the interface for starting or restarting a deployment. ```python @abstractmethod def start(self) -> None ``` -------------------------------- ### Software.logs() usage example Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates printing the logs returned by the deployment. ```python print(deployed_program.logs()) # Initialized local deployment # run() called with: {"text": "hello"} # run() completed: status=success ``` -------------------------------- ### kapso learn grade command example Source: https://docs.leeroo.com/docs/reference/cli Example of grading a bank against a specific split manifest. ```bash kapso learn grade --bank ./bank --bank-head lr_042 --split splits/d1.yaml ``` -------------------------------- ### kapso learn import command examples Source: https://docs.leeroo.com/docs/reference/cli Examples of importing archived campaign tarballs or subsets into the trajectory store. ```bash kapso learn import --subset docs/plans/learning/d1-subset.yaml kapso learn import --archive gs://bucket/runs/campaign/20260731T092629_lane-a2.tgz ``` -------------------------------- ### Software.name property usage example Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates accessing the deployment strategy name. ```python print(deployed_program.name) # "modal" ``` -------------------------------- ### Install Kapso dependencies Source: https://docs.leeroo.com/docs/benchmarks/ioai-2026 Install the package in editable mode to set up the environment. ```bash pip install -e . ``` -------------------------------- ### kapso learn mine command example Source: https://docs.leeroo.com/docs/reference/cli Example of mining all un-mined imported trajectories. ```bash kapso learn mine --all ``` -------------------------------- ### Software.run() usage example Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates how to execute a program and handle the resulting status. ```python result = deployed_program.run({"text": "hello"}) if result["status"] == "success": print(result["output"]) else: print(f"Error: {result['error']}") ``` -------------------------------- ### Install MLE-Bench Source: https://docs.leeroo.com/docs/installation Clones the MLE-Bench repository, installs Git LFS, and installs required dependencies. Requires Git LFS to be installed. ```bash git clone https://github.com/openai/mle-bench.git cd mle-bench git lfs install git lfs fetch --all git lfs pull pip install -e . cd .. pip install -r benchmarks/mle/requirements.txt ``` -------------------------------- ### Install the package from source Source: https://docs.leeroo.com/docs/installation Clone the repository and set up a dedicated Conda environment for development. ```bash git clone https://github.com/leeroo-ai/kapso.git cd kapso conda create -n kapso_conda python=3.12 conda activate kapso_conda pip install -e . ``` -------------------------------- ### Install RelBench Source: https://docs.leeroo.com/docs/installation Installs the RelBench package from PyPI. ```bash pip install relbench ``` -------------------------------- ### Deploying solutions with kapso deploy Source: https://docs.leeroo.com/docs/reference/cli Examples of deploying a solution directory using various flags like strategy, environment variables, and interactive mode. ```bash kapso deploy --solution-path ./solution kapso deploy --solution-path ./solution --strategy docker kapso deploy --solution-path ./solution --env API_KEY=xxx --interactive ``` -------------------------------- ### Install Leeroo Kapso Source: https://docs.leeroo.com/docs/knowledge/learning-pipeline Command to install the Leeroo Kapso framework via pip. ```bash pip install leeroo-kapso ``` -------------------------------- ### Install and log in to the coding-agent CLIs Source: https://docs.leeroo.com/docs/installation Install the OpenAI and Anthropic CLIs and perform interactive browser-based authentication. ```bash npm install -g @openai/codex codex login npm install -g @anthropic-ai/claude-code claude auth login ``` -------------------------------- ### kapso evolve command usage examples Source: https://docs.leeroo.com/docs/reference/cli Examples of running the kapso evolve command with different configurations, including goal strings, goal files, iteration limits, evaluation directories, and resume functionality. ```bash kapso evolve --goal "Build a web scraper for news articles" kapso evolve --goal-file problem.txt --iterations 20 kapso evolve --goal "Build a classifier" --eval-dir ./eval/ --data-dir ./data/ kapso evolve --goal "Build a classifier" --output ./campaign --resume ``` -------------------------------- ### Install ALE-Bench Source: https://docs.leeroo.com/docs/installation Clones the ALE-Bench repository and installs dependencies. Requires Docker and libcairo2-dev. ```bash git clone https://github.com/SakanaAI/ALE-Bench.git cd ALE-Bench pip install . pip install ".[eval]" bash ./scripts/docker_build_202301.sh $(id -u) $(id -g) cd .. ``` -------------------------------- ### Install and login to OpenAI Codex Source: https://docs.leeroo.com/docs/evolve/coding-agents Commands to install the OpenAI Codex CLI and authenticate the session. ```bash npm install -g @openai/codex codex login ``` -------------------------------- ### Install Leeroopedia MCP Source: https://docs.leeroo.com/docs/installation Installs the Leeroopedia MCP package via pip. ```bash pip install leeroopedia-mcp ``` -------------------------------- ### Initialize Kapso evolve() Source: https://docs.leeroo.com/docs/evolve/execution-flow The entry point for starting an experiment, defining the goal and optional evaluation or data directories. ```python solution = kapso.evolve( goal="Build a classifier with 95% accuracy", eval_dir="./evaluation/", # Optional: user-provided evaluation data_dir="./data/", # Optional: user-provided data max_iterations=10, ) ``` -------------------------------- ### SelectorAgent explain() method and usage Source: https://docs.leeroo.com/docs/deployment/api-reference Get a human-readable explanation of the deployment selection process. ```python def explain(self, solution: SolutionResult) -> str ``` ```python selector = SelectorAgent() explanation = selector.explain(solution) print(explanation) # Deployment Selection Analysis # ======================================== # # Strategy: modal # Interface: function # Provider: modal # Resources: {'gpu': 'T4', 'memory': '16Gi'} # # Reasoning: GPU workload detected (torch dependency) ``` -------------------------------- ### Example agent output format Source: https://docs.leeroo.com/docs/evolve/coding-agents A complete example of an agent response including natural language explanation followed by the required XML tags. ```text I've implemented the random forest classifier. Here's what I did: 1. Created main.py with the classifier implementation 2. Added data loading and preprocessing 3. Created kapso_evaluation/evaluate.py to test accuracy Implemented random forest classifier with GridSearchCV for hyperparameter tuning. Added cross-validation and accuracy reporting. kapso_evaluation/evaluate.py Loading data... Training model... Accuracy: 0.92 0.92 none ``` -------------------------------- ### Deploy software locally Source: https://docs.leeroo.com/docs/reference/kapso-api Example of deploying a solution using the LOCAL strategy, running it with input data, and stopping the deployment. ```python deployed = kapso.deploy(solution, strategy=DeployStrategy.LOCAL) result = deployed.run({"data_path": "./test.csv"}) deployed.stop() ``` -------------------------------- ### Install RelBench dependencies Source: https://docs.leeroo.com/docs/benchmarks/relbench Commands to install the evaluation layer and the modeling stack for RelBench. ```bash pip install relbench duckdb pooch pyarrow scikit-learn # evaluation layer pip install "relbench[full]" sentence-transformers \ lightgbm xgboost catboost tqdm # modeling stack (GPU machine) ``` -------------------------------- ### kapso research command examples Source: https://docs.leeroo.com/docs/reference/cli Examples of running deep web research with various objectives, modes, and depth settings. ```bash kapso research --objective "How to optimize transformers?" kapso research --objective "LLM fine-tuning" --mode idea kapso research --objective "RAG implementation" --mode idea --mode implementation kapso research --objective-file topic.txt --mode study --depth deep ``` -------------------------------- ### Software.run_batch() usage example Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates processing a list of inputs and iterating over the results. ```python results = deployed_program.run_batch([ {"text": "hello"}, {"text": "world"}, {"text": "test"}, ]) for result in results: print(result["output"]) ``` -------------------------------- ### learn_knowledge usage example Source: https://docs.leeroo.com/docs/reference/kapso-api An example of calling kapso.learn_knowledge with a repository source and research findings. ```python kapso.learn_knowledge( Source.Repo("https://github.com/huggingface/trl"), findings, wiki_dir="data/wikis", ) ``` -------------------------------- ### Creating deployed Software instances with DeploymentFactory Source: https://docs.leeroo.com/docs/deployment/api-reference Examples of using DeploymentFactory.create to deploy with auto-selection, forced strategies, or restricted strategy lists. ```python from kapso.deployment import DeploymentFactory, DeployStrategy, DeployConfig config = DeployConfig( solution=my_solution, env_vars={"API_KEY": "xxx"}, timeout=300, ) # Auto-select best strategy deployed_program = DeploymentFactory.create(DeployStrategy.AUTO, config) # Force specific strategy deployed_program = DeploymentFactory.create(DeployStrategy.MODAL, config) # Restrict to certain strategies deployed_program = DeploymentFactory.create( DeployStrategy.AUTO, config, strategies=["local", "docker"] ) ``` -------------------------------- ### CLI commands for knowledge base learner Source: https://docs.leeroo.com/docs/knowledge/learning-pipeline Examples of how to run the learner module from the command line with various options like branch specification, extraction-only mode, and custom directories. ```bash # Learn from a GitHub repository python -m kapso.knowledge_base.learners https://github.com/user/repo # Specify a branch python -m kapso.knowledge_base.learners https://github.com/user/repo --branch develop # Extract only (don't merge) python -m kapso.knowledge_base.learners https://github.com/user/repo --extract-only # Custom wiki directory python -m kapso.knowledge_base.learners https://github.com/user/repo --wiki-dir ./my_wikis # Verbose logging python -m kapso.knowledge_base.learners https://github.com/user/repo --verbose ``` -------------------------------- ### Manage Infrastructure for Search Backends Source: https://docs.leeroo.com/docs/knowledge/overview Use the provided scripts to start or stop the Weaviate and Neo4j database infrastructure required by the search backends. ```bash # Start Weaviate and Neo4j ./scripts/start_infra.sh # Stop infrastructure ./scripts/stop_infra.sh ``` -------------------------------- ### Initialize and Run KnowledgeMerger Source: https://docs.leeroo.com/docs/knowledge/learning-pipeline Example of how to instantiate the KnowledgeMerger and execute a merge operation on a set of proposed pages. ```python from kapso.knowledge_base.learners import KnowledgeMerger merger = KnowledgeMerger() result = merger.merge( proposed_pages=pages, wiki_dir="data/wikis", ) print(f"Created: {len(result.created)}") print(f"Edited: {len(result.edited)}") print(f"Failed: {len(result.failed)}") ``` -------------------------------- ### Execute Search Strategy in Python Source: https://docs.leeroo.com/docs/evolve/search-strategies Example of initializing and running a generic search strategy using the Kapso Python SDK. ```python from kapso.execution.search_strategies import SearchStrategyFactory strategy = SearchStrategyFactory.create( strategy_type="generic", problem_handler=handler, llm=llm, coding_agent_config=config, params={"ideation_timeout": 300}, ) strategy.run(context, budget_progress=0.0) best = strategy.get_best_experiment() ``` -------------------------------- ### Index a knowledge graph Source: https://docs.leeroo.com/docs/reference/kapso-api Example of indexing a wiki directory and initializing a Kapso instance with the resulting index path. ```python index_path = kapso.index_kg( wiki_dir="data/wikis", save_to="data/indexes/finetuning.index", ) kapso = Kapso(kg_index=index_path) ``` -------------------------------- ### Strategy config.yaml Structure Source: https://docs.leeroo.com/docs/deployment/architecture Example configuration file defining the provider, runner class, and resource requirements for a strategy. ```yaml name: modal provider: modal interface: function runner_class: ModalRunner default_resources: gpu: T4 memory: 16Gi run_interface: type: modal function_name: predict ``` -------------------------------- ### Deploy with Docker Strategy Source: https://docs.leeroo.com/docs/deployment/strategies Deploys the solution in a container. Requires Docker to be installed and running. ```python deployed = kapso.deploy(solution, strategy=DeployStrategy.DOCKER) ``` -------------------------------- ### Install OpenHands environment Source: https://docs.leeroo.com/docs/evolve/coding-agents Commands to create a dedicated Conda environment and install OpenHands dependencies. ```bash conda create -n openhands_env python=3.12 conda activate openhands_env pip install openhands-ai litellm ``` -------------------------------- ### Configure Evolve mode Source: https://docs.leeroo.com/docs/evolve/overview Example of setting the evolution mode to MINIMAL using the kapso.evolve function. ```python # Use a specific mode solution = kapso.evolve( goal="...", mode="MINIMAL", ) ``` -------------------------------- ### Example .index file structure Source: https://docs.leeroo.com/docs/knowledge/search-backends The .index file is a JSON reference containing metadata about the data source and backend configuration. ```json { "version": "1.0", "created_at": "2026-01-15T10:30:00Z", "data_source": "data/wikis", "search_backend": "kg_graph_search", "backend_refs": { "weaviate_collection": "KapsoKG", "embedding_model": "text-embedding-3-large" }, "page_count": 99 } ``` -------------------------------- ### Example usage of kapso.research Source: https://docs.leeroo.com/docs/reference/kapso-api A practical example of calling the research function with a specific objective, mode, and depth. ```python findings = kapso.research( "QLoRA fine-tuning memory optimizations", mode=["idea", "implementation"], depth="deep", ) ``` -------------------------------- ### Install Claude Code CLI Source: https://docs.leeroo.com/docs/evolve/coding-agents Command to install the Anthropic Claude Code CLI globally via npm. ```bash npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### Implement Runner Class Source: https://docs.leeroo.com/docs/deployment/adding-strategies Example of a runner.py file implementing the Runner class for a custom strategy. ```python from kapso.deployment.strategies.base import Runner from typing import Any, Dict class MyStrategyRunner(Runner): """Runner for my custom strategy.""" def __init__( self, code_path: str, module: str = "main", callable: str = "predict", **kwargs, ): self.code_path = code_path self.module = module self.callable = callable self._running = False def run(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Execute with inputs.""" if not self._running: self.start() try: # Your execution logic here result = self._execute(inputs) return {"status": "success", "output": result} except Exception as e: return {"status": "error", "error": str(e)} def start(self) -> None: """Start the service.""" # Initialize resources self._running = True def stop(self) -> None: """Stop and cleanup.""" # Cleanup resources self._running = False def is_healthy(self) -> bool: """Check if service is running.""" return self._running def get_logs(self) -> str: """Return execution logs.""" return "" def _execute(self, inputs: Dict) -> Any: """Internal execution logic.""" # Implement your execution here pass ``` -------------------------------- ### Software.stop() usage example Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates stopping a program and verifying its health status. ```python deployed_program.stop() print(deployed_program.is_healthy()) # False ``` -------------------------------- ### Run an evolve campaign Source: https://docs.leeroo.com/docs/reference/kapso-api Example usage of the kapso.evolve function to build a machine learning model, followed by printing the explanation of the resulting solution. ```python solution = kapso.evolve( goal="Build a random forest classifier for Iris with accuracy > 0.9", max_iterations=10, output_path="./iris_solution", ) print(solution.explain()) ``` -------------------------------- ### Deploy with BentoML strategy Source: https://docs.leeroo.com/docs/deployment/strategies Packages the solution as a BentoML service for self-hosted production serving. Requires the bentoml package to be installed. ```python deployed = kapso.deploy(solution, strategy=DeployStrategy.BENTOML) ``` -------------------------------- ### Check setup with kapso doctor output Source: https://docs.leeroo.com/docs/installation The doctor command reports configuration requirements and identifies missing dependencies. ```bash kapso doctor ``` ```text kapso doctor ==================================================================== [OK ] node [OK ] codex CLI [OK ] codex authenticated [OK ] claude CLI [OK ] claude authenticated [OK ] git [OK ] OPENAI_API_KEY (embeddings) [OK ] deploy target docker [-- ] deploy target modal needed by only needed for deploy(strategy=DeployStrategy.MODAL) fix pip install modal && modal token new ==================================================================== Required checks passed (9 checked). 1 optional item(s) marked [-- ] only limit features you may not need. ``` -------------------------------- ### get_endpoint() usage example Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates how to retrieve and print the API endpoint if it exists. ```python endpoint = deployed_program.get_endpoint() if endpoint: print(f"API available at: {endpoint}") ``` -------------------------------- ### Constructing a coding agent manually Source: https://docs.leeroo.com/docs/evolve/coding-agents Example of using the CodingAgentFactory to build a configuration and instantiate an agent for a specific workspace. ```python from kapso.execution.coding_agents.factory import CodingAgentFactory config = CodingAgentFactory.build_config( agent_type="claude_code", model="claude-opus-5", ) agent = CodingAgentFactory.create(config) agent.initialize("/path/to/workspace") result = agent.generate_code("Implement a sorting algorithm") print(f"Files changed: {result.files_changed}") print(f"Cost: ${result.cost:.4f}") ``` -------------------------------- ### Software.is_healthy() usage example Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates checking health before executing a run. ```python if deployed_program.is_healthy(): result = deployed_program.run(inputs) else: print("Software not healthy!") ``` -------------------------------- ### Initialize Kapso with configuration paths Source: https://docs.leeroo.com/docs/reference/configuration Demonstrates how to initialize the Kapso client using either the default packaged configuration or a custom path. ```python from kapso import Kapso kapso = Kapso() # packaged config kapso = Kapso(config_path="./my-config.yaml") # yours ``` -------------------------------- ### Initialize and use kg_llm_navigation Source: https://docs.leeroo.com/docs/knowledge/search-backends Demonstrates how to create a search instance using the kg_llm_navigation factory, index JSON data, and perform a search query. ```python import json from kapso.knowledge_base.search import KnowledgeSearchFactory search = KnowledgeSearchFactory.create("kg_llm_navigation") with open("kg_data.json") as handle: search.index(json.load(handle)) result = search.search( query="Best practices for feature engineering", context="Working on a tabular data competition", ) ``` -------------------------------- ### Workspace directory structure Source: https://docs.leeroo.com/docs/evolve/overview Visual representation of the workspace layout after Evolve setup. ```text workspace/ ├── kapso_evaluation/ # Agent builds evaluation here │ └── evaluate.py # Evaluation script ├── kapso_datasets/ # Data files (from data_dir) ├── .kapso/ │ └── repo_memory.json # Codebase understanding └── (solution code) # From initial_repo or agent-built ``` -------------------------------- ### Run Kapso evolve and deploy Source: https://docs.leeroo.com/docs/evolve/overview Demonstrates initializing a Kapso instance, evolving a solution with specific goals and optional data/evaluation directories, and deploying the resulting program locally. ```python from kapso import Kapso, DeployStrategy kapso = Kapso() # Build a solution - agent builds evaluation dynamically # Include success criteria in the goal solution = kapso.evolve( goal="Build a random forest classifier for Iris with accuracy > 0.9", max_iterations=10, ) # With user-provided evaluation and data solution = kapso.evolve( goal="Optimize model inference speed to < 10ms", eval_dir="./my_evaluation/", # Copied to kapso_evaluation/ data_dir="./my_data/", # Copied to kapso_datasets/ initial_repo="https://github.com/org/starter", # Or local path ) # Deploy and run deployed_program = kapso.deploy(solution, strategy=DeployStrategy.LOCAL) result = deployed_program.run({"data_path": "./test.csv"}) ``` -------------------------------- ### Deployment error handling pattern Source: https://docs.leeroo.com/docs/deployment/api-reference Example of using DeploymentFactory with try-except-finally blocks to manage deployment execution and resource cleanup. ```python try: deployed_program = DeploymentFactory.create(DeployStrategy.MODAL, config) result = deployed_program.run(inputs) if result["status"] == "error": print(f"Execution error: {result['error']}") except ValueError as e: print(f"Invalid configuration: {e}") except RuntimeError as e: print(f"Deployment failed: {e}") finally: if 'deployed_program' in locals(): deployed_program.stop() ``` -------------------------------- ### Bootstrap from existing repo Source: https://docs.leeroo.com/docs/evolve/repo-memory Initializes a baseline model for the repository using an LLM backend. ```python from kapso.core.llm import LLMBackend llm = LLMBackend() # Build evidence-backed model via LLM RepoMemoryManager.bootstrap_baseline_model( repo_root="/path/to/repo", llm=llm, initial_repo="/original/repo", max_retries=2, ) ``` -------------------------------- ### get_deployment_info() method definition and return value Source: https://docs.leeroo.com/docs/deployment/api-reference Defines the signature for retrieving deployment metadata and shows an example of the returned dictionary structure. ```python def get_deployment_info(self) -> Dict[str, Any] ``` ```python { "strategy": "modal", "provider": "modal", "endpoint": "https://...", "adapted_path": "/path/to/...", "adapted_files": ["modal_app.py", "main.py"], "resources": {"gpu": "T4", "memory": "16Gi"}, } ``` -------------------------------- ### kapso --list-agents Source: https://docs.leeroo.com/docs/reference/cli Lists the available coding agents, including their associated models and installation commands. ```APIDOC ## kapso --list-agents ### Description Lists the available coding agents with their models and install commands. ### Usage `kapso --list-agents` ``` -------------------------------- ### Test strategy lifecycle with MyStrategyRunner Source: https://docs.leeroo.com/docs/deployment/adding-strategies Demonstrates how to verify the start, run, and stop lifecycle methods of a deployment strategy runner using pytest. ```python import pytest from kapso.deployment.strategies.my_strategy.runner import MyStrategyRunner def test_runner_lifecycle(): runner = MyStrategyRunner( code_path="/path/to/code", module="main", callable="predict", ) # Test start runner.start() assert runner.is_healthy() # Test run result = runner.run({"input": "test"}) assert result["status"] == "success" # Test stop runner.stop() assert not runner.is_healthy() ``` -------------------------------- ### Create adapter_instruction.txt Source: https://docs.leeroo.com/docs/deployment/adding-strategies Defines adaptation instructions, required files, and the entry point format for the strategy. ```markdown ## Adaptation Instructions for My Strategy ### Required Files 1. `run.py` - Entry point script 2. `requirements.txt` - Dependencies ### Entry Point Format ```python def predict(inputs: dict) -> dict: """Main prediction function.""" # Implementation return {"result": ...} ``` ### Environment Variables - `MY_STRATEGY_CONFIG` - Configuration path ### Notes - Keep dependencies minimal - Handle errors gracefully ``` -------------------------------- ### Indexing corpora with kapso index_kg Source: https://docs.leeroo.com/docs/reference/cli Examples of indexing wiki directories or JSON data files into a knowledge graph, with options to force overwrite existing data. ```bash kapso index_kg --wiki-dir ./data/wikis --save-to ./data/indexes/ml.index kapso index_kg --data-path ./data/kg_data.json --save-to ./data/indexes/kaggle.index kapso index_kg --wiki-dir ./data/wikis --save-to ./data/indexes/ml.index --force ``` -------------------------------- ### Kapso.deploy() Source: https://docs.leeroo.com/docs/reference/kapso-api Turns a solution into running software. ```APIDOC ## deploy() ### Description Deploys a generated solution into a running software instance. ### Returns - **Software** - The deployed software instance. ``` -------------------------------- ### kapso watch command usage Source: https://docs.leeroo.com/docs/reference/cli Examples of monitoring evolve, learn, or learn_knowledge operations using the watch command with various flags. ```bash kapso watch ./campaign kapso watch learning/status kapso watch ./campaign --follow kapso watch ./campaign --json | jq -r '[.state] | @tsv' ``` -------------------------------- ### Initialize bank repository Source: https://docs.leeroo.com/docs/learning/bank Creates the bank home as a bare repository with a founding skeleton. ```bash kapso learn init-bank ``` -------------------------------- ### Orchestrator configuration structure Source: https://docs.leeroo.com/docs/evolve/orchestrator Example configuration defining search strategies, retry logic, coding agent settings, and knowledge search parameters for the orchestrator. ```yaml modes: GENERIC: search_strategy: type: "generic" params: idea_generation_model: "claude-opus-5" implementation_model: "claude-opus-5" auth_mode: "oauth" gate_failure_policy: "warn" ideation_gates: ["research", "experiment_history", "repo_memory", "leeroopedia"] retry: max_attempts: 2 initial_delay_seconds: 5 max_delay_seconds: 60 multiplier: 2 jitter: true coding_agent: type: "claude_code" model: "claude-opus-5" agent_specific: auth_mode: "oauth" knowledge_search: type: "kg_graph_search" enabled: true preset: "DEFAULT" ``` -------------------------------- ### Kapso.learn() Source: https://docs.leeroo.com/docs/reference/kapso-api Mines a finished campaign into the lesson bank. ```APIDOC ## learn() ### Description Mines data from a completed campaign into the lesson bank. ### Returns - **LessonResult** - The result of the learning process. ``` -------------------------------- ### Run kapso doctor commands Source: https://docs.leeroo.com/docs/reference/cli Examples of running the doctor command to check configuration, optionally filtered by a specific verb or including model probes. ```bash kapso doctor kapso doctor evolve kapso doctor evolve --models ``` -------------------------------- ### Initialize and execute kg_graph_search Source: https://docs.leeroo.com/docs/knowledge/search-backends Demonstrates how to instantiate the kg_graph_search backend using the KnowledgeSearchFactory and perform a search with specific filters. ```python from kapso.knowledge_base.search import KnowledgeSearchFactory, KGSearchFilters search = KnowledgeSearchFactory.create("kg_graph_search", params={ "weaviate_collection": "KapsoKG", "embedding_model": "text-embedding-3-large", "use_llm_reranker": True, }) result = search.search( query="How to fine-tune an LLM with limited GPU memory?", filters=KGSearchFilters(top_k=5, domains=["LLMs", "PEFT"]), ) for item in result: print(f"{item.id}: {item.score:.2f}") context = result.to_context_string(max_results=3) ``` -------------------------------- ### kapso learn init-bank Source: https://docs.leeroo.com/docs/reference/cli Initializes the bank home. ```APIDOC ## kapso learn init-bank ### Description Creates the bank home. ### Parameters - **--config** (string) - Required - Configuration file ``` -------------------------------- ### Deploy a Kapso solution Source: https://docs.leeroo.com/docs/deployment/overview Demonstrates the full lifecycle of deploying a solution, including strategy selection, running inference, and lifecycle management. ```python from kapso import Kapso, DeployStrategy kapso = Kapso() solution = kapso.evolve(goal="Build a classifier") # Deploy with explicit strategy deployed_program = kapso.deploy(solution, strategy=DeployStrategy.LOCAL) # Run inference result = deployed_program.run({"data_path": "./test.csv"}) print(result) # {"status": "success", "output": ...} # Lifecycle management deployed_program.stop() deployed_program.start() deployed_program.stop() ``` -------------------------------- ### Software.run(inputs: Dict) -> Dict Source: https://docs.leeroo.com/docs/deployment/overview Executes the deployment with the provided input data and returns a status object. ```APIDOC ## Software.run(inputs) ### Description Executes the deployment with the provided input data. ### Parameters - **inputs** (Dict) - Required - Input data for the execution. ### Response - **status** (string) - "success" or "error" - **output** (any) - Result of the execution (on success) - **error** (string) - Error message (on error) ``` -------------------------------- ### Software.__call__() shorthand Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates that calling the instance directly is equivalent to calling run(). ```python # These are equivalent result = deployed_program.run(inputs) result = deployed_program(inputs) ``` -------------------------------- ### get_adapted_path() usage example Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates how to call get_adapted_path() and print the resulting path. ```python path = deployed_program.get_adapted_path() print(path) # "/path/to/solution_adapted_modal" ``` -------------------------------- ### Enable serving configuration Source: https://docs.leeroo.com/docs/learning/serving Configure the learning module to enable serving and specify the local path for the bank. ```yaml learning: serving: enabled: true bank: local_path: data/kapso-bank.git ``` -------------------------------- ### Deploying a solution Source: https://docs.leeroo.com/docs/quickstart Deploy a solution using a specified strategy and run it with input data. DeployStrategy options include LOCAL, DOCKER, MODAL, BENTOML, and LANGGRAPH. ```python from kapso import Kapso, DeployStrategy deployed = kapso.deploy(solution, strategy=DeployStrategy.LOCAL) result = deployed.run({"data_path": "./test.csv"}) deployed.stop() ``` -------------------------------- ### Deploy with LOCAL strategy Source: https://docs.leeroo.com/docs/deployment/strategies Runs the solution as a plain Python process in the current environment. This strategy is best for development and debugging as it offers no isolation. ```python deployed = kapso.deploy(solution, strategy=DeployStrategy.LOCAL) result = deployed.run({"data_path": "./data.csv"}) ``` -------------------------------- ### Manage deployment lifecycle with kapso.deploy Source: https://docs.leeroo.com/docs/deployment/overview Demonstrates how to deploy a program, check its health, and perform stop/start operations for resource cleanup. ```python deployed_program = kapso.deploy(solution, strategy=DeployStrategy.LOCAL) # Initial run result = deployed_program.run({"data": "..."}) # Check health if deployed_program.is_healthy(): print("Service is running") # Stop (cleanup resources) deployed_program.stop() # Restart deployed_program.start() # Run again result = deployed_program.run({"data": "..."}) # Final cleanup deployed_program.stop() ``` -------------------------------- ### Get specific section Source: https://docs.leeroo.com/docs/evolve/repo-memory Retrieves the text content of a specific section from the repository memory. ```python # Read a section section_text = RepoMemoryManager.get_section(doc, "core.architecture") print(section_text) ``` -------------------------------- ### Context manager support Source: https://docs.leeroo.com/docs/deployment/api-reference Demonstrates using the deployment as a context manager to ensure automatic cleanup via stop(). ```python with DeploymentFactory.create(strategy, config) as deployed_program: result = deployed_program.run(inputs) # deployed_program.stop() called automatically ``` -------------------------------- ### Create selector_instruction.txt Source: https://docs.leeroo.com/docs/deployment/adding-strategies Provides documentation for auto-selection, including summary, usage conditions, and requirements. ```markdown ## My Strategy ### Summary A custom deployment strategy for [specific use case]. ### When to Use - Condition 1 - Condition 2 - Condition 3 ### When NOT to Use - Anti-condition 1 - Anti-condition 2 ### Requirements - Requirement 1 - Requirement 2 ``` -------------------------------- ### Get cumulative cost with Orchestrator Source: https://docs.leeroo.com/docs/evolve/overview Retrieves the total cost tracked by the orchestrator across all components. ```python # Get cumulative cost cost = orchestrator.get_cumulative_cost() print(f"Total cost: ${cost:.2f}") ``` -------------------------------- ### kapso learn develop command Source: https://docs.leeroo.com/docs/reference/cli Runs a development session with a split manifest and learner version. ```bash kapso learn develop --split splits/d1.yaml --learner-version v3 ``` -------------------------------- ### Kapso Constructor Source: https://docs.leeroo.com/docs/reference/kapso-api Initializes a new Kapso instance with optional configuration, knowledge graph index, and lesson bank path. ```APIDOC ## Kapso(config_path: str | None = None, kg_index: str | None = None, bank: str | None = None) ### Description Initializes the Kapso client. If no arguments are provided, it defaults to the packaged config.yaml. ### Parameters - **config_path** (str | None) - Optional - Path to a config file. - **kg_index** (str | None) - Optional - Path to an existing .index file. Without one, knowledge search is disabled. - **bank** (str | None) - Optional - Lesson-bank home directory, overriding the default config path. ``` -------------------------------- ### Claude Code configuration block Source: https://docs.leeroo.com/docs/evolve/coding-agents Example configuration for the Claude Code agent, specifying the model and authentication mode. ```yaml coding_agent: type: "claude_code" model: "claude-opus-5" agent_specific: auth_mode: "oauth" claude_md_path: "CLAUDE.md" ``` -------------------------------- ### DeploymentFactory.explain_strategy() Source: https://docs.leeroo.com/docs/deployment/api-reference Retrieves a one-line description for a specific deployment strategy. ```APIDOC ## DeploymentFactory.explain_strategy() ### Description Get explanation of a deployment strategy. ### Signature ```python @classmethod def explain_strategy(cls, strategy: str) -> str ``` ### Parameters - **strategy** (str) - Required - Strategy name ### Returns - **str** - One-line description from selector instruction ``` -------------------------------- ### SelectorAgent.explain() Source: https://docs.leeroo.com/docs/deployment/api-reference Provides a human-readable explanation of the deployment selection. ```APIDOC ## SelectorAgent.explain() ### Description Get human-readable explanation of selection. ### Signature `def explain(self, solution: SolutionResult) -> str` ``` -------------------------------- ### DeploymentFactory.list_strategies() Source: https://docs.leeroo.com/docs/deployment/api-reference Lists all available deployment strategies. ```APIDOC ## DeploymentFactory.list_strategies() ### Description List all available deployment strategies. ### Signature ```python @classmethod def list_strategies(cls) -> List[str] ``` ### Returns - **List[str]** - List of strategy names ``` -------------------------------- ### Explaining a deployment strategy Source: https://docs.leeroo.com/docs/deployment/api-reference Retrieving the description for a specific strategy name. ```python desc = DeploymentFactory.explain_strategy("modal") print(desc) # "Serverless GPU deployment on Modal.com with auto-scaling." ``` -------------------------------- ### Example feedback iteration flow Source: https://docs.leeroo.com/docs/evolve/feedback-generator The feedback generator provides iterative suggestions that the coding agent uses to improve performance. ```text Iteration 1: Accuracy 0.75 Feedback: "Try ensemble methods and feature selection" Iteration 2: Accuracy 0.88 Feedback: "Close to target. Try hyperparameter tuning" Iteration 3: Accuracy 0.92 Feedback: "Goal achieved! Accuracy 0.92 > 0.9 target" ``` -------------------------------- ### Listing available deployment strategies Source: https://docs.leeroo.com/docs/deployment/api-reference Retrieving and printing the list of supported deployment strategies. ```python strategies = DeploymentFactory.list_strategies() print(strategies) # ['bentoml', 'docker', 'langgraph', 'local', 'modal'] ``` -------------------------------- ### Create and connect bank with gh CLI Source: https://docs.leeroo.com/docs/learning/bank Initializes and connects a repository in a single step using the GitHub CLI. ```bash kapso bank create your-org/kapso-bank ``` -------------------------------- ### Interact with StrategyRegistry Source: https://docs.leeroo.com/docs/deployment/adding-strategies Demonstrates how to list strategies, verify existence, and retrieve runner classes or instructions from the registry. ```python from kapso.deployment.strategies import StrategyRegistry registry = StrategyRegistry.get() # List all strategies strategies = registry.list_strategies() print(strategies) # ["bentoml", "docker", "langgraph", "local", "modal", "my_strategy"] # Check if strategy exists exists = registry.strategy_exists("my_strategy") # Get runner class runner_class = registry.get_runner_class("my_strategy") # Get instructions selector_inst = registry.get_selector_instruction("my_strategy") adapter_inst = registry.get_adapter_instruction("my_strategy") ``` -------------------------------- ### DeploymentFactory.explain_strategy() method signature Source: https://docs.leeroo.com/docs/deployment/api-reference Signature for retrieving a one-line description of a specific deployment strategy. ```python @classmethod def explain_strategy(cls, strategy: str) -> str ``` -------------------------------- ### Importing Kapso components Source: https://docs.leeroo.com/docs/reference/kapso-api Initialize the Kapso client by importing the necessary classes from the top-level package. ```python from kapso import Kapso, Source, DeployStrategy kapso = Kapso() ``` -------------------------------- ### Implement Runner base class Source: https://docs.leeroo.com/docs/deployment/adding-strategies Defines the abstract base class for all deployment runners, requiring implementation of run, stop, start, and is_healthy methods. ```python from abc import ABC, abstractmethod from typing import Any, Dict, Union class Runner(ABC): """Base class for deployment runners.""" @abstractmethod def run(self, inputs: Union[Dict, str, bytes]) -> Any: """Execute with inputs; DeployedSoftware normalizes the result.""" pass @abstractmethod def stop(self) -> None: """Stop and cleanup resources.""" pass @abstractmethod def start(self) -> None: """Start or restart the service.""" pass @abstractmethod def is_healthy(self) -> bool: """Check if service is running and ready.""" pass def get_logs(self) -> str: """Return execution logs.""" return "" ``` -------------------------------- ### Deploy using a custom strategy Source: https://docs.leeroo.com/docs/deployment/adding-strategies Shows how to use a custom strategy via the kapso.deploy method or the DeploymentFactory. ```python from kapso import Kapso from kapso.deployment import DeployStrategy # The enum member appears automatically: DeployStrategy rebuilds # itself from every strategies/ directory that has a config.yaml deployed_program = kapso.deploy(solution, strategy=DeployStrategy.MY_STRATEGY) # Or via factory from kapso.deployment import DeploymentFactory, DeployConfig config = DeployConfig(solution=solution) deployed_program = DeploymentFactory.create(DeployStrategy.MY_STRATEGY, config) ``` -------------------------------- ### Run Kapso learning stages via CLI Source: https://docs.leeroo.com/docs/learning/pipeline Execute the four stages of the learning pipeline individually using the Kapso CLI. ```bash kapso learn import --archive ./campaign.tgz kapso learn mine --all kapso learn grade --bank ./bank --bank-head lr_042 --trajectory kapso learn update --learner-version crew_v4 --batch-manifest batch.yaml ``` -------------------------------- ### DeploymentFactory.print_strategies_info() Source: https://docs.leeroo.com/docs/deployment/api-reference Prints detailed information about all available deployment strategies to the console. ```APIDOC ## DeploymentFactory.print_strategies_info() ### Description Print information about all deployment strategies. ### Signature ```python @classmethod def print_strategies_info(cls) -> None ``` ``` -------------------------------- ### Using feedback generator via kapso.evolve Source: https://docs.leeroo.com/docs/evolve/feedback-generator The feedback generator is invoked automatically when calling kapso.evolve(). This example shows how to check for success or retrieve feedback. ```python solution = kapso.evolve( goal="Build a classifier with accuracy > 0.9", max_iterations=10, ) # Check if goal was achieved if solution.succeeded: print(f"Goal achieved with score: {solution.final_score}") else: print(f"Final feedback: {solution.final_feedback.feedback}") ``` -------------------------------- ### Define and use an external evaluator with kapso.evolve Source: https://docs.leeroo.com/docs/evolve/external-evaluation This example demonstrates defining an evaluate_candidate function that runs an external script and passing it to the iteration_evaluator parameter in kapso.evolve. ```python import json import subprocess from kapso import IterationEvaluationResult def evaluate_candidate(context): completed = subprocess.run( ["python", "evaluation/run.py", "--json"], cwd=context.workspace_dir, check=True, capture_output=True, text=True, ) report = json.loads(completed.stdout) return IterationEvaluationResult( metrics={ "validation_accuracy": report["accuracy"], "p95_latency_ms": report["p95_latency_ms"], }, primary_metric="validation_accuracy", metadata={"suite_version": report["suite_version"]}, ) solution = kapso.evolve( goal="Improve the support agent", output_path="./campaign", max_iterations=3, iteration_evaluator=evaluate_candidate, ) ``` -------------------------------- ### Run Kapso CLI commands with custom configuration Source: https://docs.leeroo.com/docs/reference/configuration Shows how to pass a custom configuration file path to Kapso CLI commands. ```bash kapso doctor --config ./my-config.yaml kapso learn mine --all --config ./my-config.yaml ``` -------------------------------- ### List registered Kapso agents Source: https://docs.leeroo.com/docs/evolve/coding-agents Executes the command to display all currently registered coding agents, including their descriptions, default models, installation commands, and required environment variables. ```bash kapso --list-agents ``` -------------------------------- ### Create Strategy Directory Source: https://docs.leeroo.com/docs/deployment/adding-strategies Command to create the directory for a new custom strategy. ```bash mkdir -p src/kapso/deployment/strategies/my_strategy ``` -------------------------------- ### kapso.deploy() Source: https://docs.leeroo.com/docs/quickstart Deploys a solution using a specified strategy. ```APIDOC ## kapso.deploy(solution, strategy=DeployStrategy.AUTO) ### Description Deploys the provided solution using the specified deployment strategy. ### Parameters - **solution** (SolutionResult) - Required - The solution object returned by evolve(). - **strategy** (DeployStrategy) - Optional - The strategy to use (AUTO, LOCAL, DOCKER, MODAL, BENTOML, LANGGRAPH). ``` -------------------------------- ### kapso learn gauntlet command Source: https://docs.leeroo.com/docs/reference/cli Runs the gauntlet for a completed development run. ```bash kapso learn gauntlet --learner-version v3 ``` -------------------------------- ### Execute a full Kapso campaign Source: https://docs.leeroo.com/docs This script initializes a Kapso instance, researches a problem, ingests external knowledge, evolves a solution, and deploys the final model. Note that learn() and learn_knowledge() serve distinct memory purposes. ```python from kapso import Kapso, Source, DeployStrategy kapso = Kapso(kg_index="data/indexes/legal_contracts.index") # Research the problem space findings = kapso.research( "RLHF and DPO fine-tuning for legal contract analysis", mode=["idea", "implementation"], depth="deep", ) # Fold public knowledge into the knowledge graph kapso.learn_knowledge( Source.Repo("https://github.com/huggingface/trl"), findings, wiki_dir="data/wikis", ) # Run the campaign solution = kapso.evolve( goal=( "Fine-tune Llama-3.1-8B on the CUAD dataset for legal clause risk " "classification, target F1 > 0.85 on high-risk clause detection" ), context=[findings.to_string()], output_path="./models/legal_risk_v1", ) # Bank what the campaign learned, so the next one starts ahead kapso.learn(solution) # Ship it deployed = kapso.deploy(solution, strategy=DeployStrategy.MODAL) ``` -------------------------------- ### Printing deployment strategies information Source: https://docs.leeroo.com/docs/deployment/api-reference Outputting summary information for all registered deployment strategies. ```python DeploymentFactory.print_strategies_info() # Available Deployment Strategies: # ================================================== # bentoml: Production ML service deployment... # docker: Run in an isolated Docker container... # ... ``` -------------------------------- ### Deploy with Modal Strategy Source: https://docs.leeroo.com/docs/deployment/strategies Deploys the solution to the Modal serverless platform. Requires the modal package and authentication. ```python deployed = kapso.deploy(solution, strategy=DeployStrategy.MODAL) ``` -------------------------------- ### Run a campaign via CLI Source: https://docs.leeroo.com/docs/quickstart Initiate a campaign using the CLI with a specific goal, iteration limit, and output directory. ```bash kapso evolve \ --goal "Build a random forest classifier for the Iris dataset with accuracy > 0.9" \ --iterations 10 \ --output ./iris_solution ``` -------------------------------- ### Define Knowledge Sources Source: https://docs.leeroo.com/docs/knowledge/learning-pipeline Demonstrates how to instantiate various Source types for the knowledge base, including repositories, solutions, and research findings. ```python from kapso.knowledge_base.types import Source # Repository source repo = Source.Repo("https://github.com/user/repo", branch="main") # Solution source (from evolve()) solution = kapso.evolve(goal="...") sol_source = Source.Solution(solution) # Research sources (from research()) findings = kapso.research("topic", mode=["idea", "implementation"]) # findings.ideas is List[Source.Idea] # findings.implementations is List[Source.Implementation] ``` -------------------------------- ### DeploymentFactory.list_strategies() method signature Source: https://docs.leeroo.com/docs/deployment/api-reference Signature for listing all available deployment strategies. ```python @classmethod def list_strategies(cls) -> List[str] ``` -------------------------------- ### Index and Load Pre-indexed Knowledge Graph Source: https://docs.leeroo.com/docs/knowledge/overview Use index_kg to process wiki pages into an index file, then load that index into the Kapso instance for campaign evolution. ```python from kapso import Kapso # One-time: Index wiki pages kapso = Kapso() kapso.index_kg( wiki_dir="data/wikis_llm_finetuning", save_to="data/indexes/llm_finetuning.index", ) # Every time: Load existing index kapso = Kapso(kg_index="data/indexes/llm_finetuning.index") solution = kapso.evolve(goal="Fine-tune LLaMA with QLoRA") ``` -------------------------------- ### KnowledgeSearchFactory.create Source: https://docs.leeroo.com/docs/knowledge/search-backends Initializes a search backend instance using the specified configuration type. ```APIDOC ## KnowledgeSearchFactory.create(type: str) ### Description Creates a new search backend instance. The 'kg_llm_navigation' preset is used for LLM-based graph navigation. ### Parameters - **type** (str) - Required - The identifier for the search backend (e.g., "kg_llm_navigation"). ### Example ```python from kapso.knowledge_base.search import KnowledgeSearchFactory search = KnowledgeSearchFactory.create("kg_llm_navigation") ``` ``` -------------------------------- ### DeploymentFactory.print_strategies_info() method signature Source: https://docs.leeroo.com/docs/deployment/api-reference Signature for printing detailed information about all available deployment strategies. ```python @classmethod def print_strategies_info(cls) -> None ``` -------------------------------- ### Importing Campaign Bundles Source: https://docs.leeroo.com/docs/learning/pipeline Commands to import bundles using a subset configuration or an archive path. ```bash kapso learn import --subset subset.yaml kapso learn import --archive gs://bucket/runs/task/20260731T092629_lane-a2.tgz ``` -------------------------------- ### Configure Leeroopedia API Key Source: https://docs.leeroo.com/docs/installation Adds the required API key to the .env file. ```bash LEEROOPEDIA_API_KEY=kpsk_... ``` -------------------------------- ### Deployment configuration with DeployConfig Source: https://docs.leeroo.com/docs/deployment/overview Configure a deployment by specifying the solution, environment variables, and the coding agent, then create the deployment using DeploymentFactory. ```python from kapso.deployment import DeployConfig config = DeployConfig( solution=solution, env_vars={"API_KEY": "..."}, coding_agent="claude_code", ) deployed_program = DeploymentFactory.create(DeployStrategy.LOCAL, config) ```