optillm

algorithmicsuperintelligenceApache-2.0活跃维护

一个面向 LLM 的推理优化代理,通过 API 网关接入,自动套用思维链等推理策略来提升模型回答质量并降低调用成本。

Optimizing inference proxy for LLMs

v0.4.1发布于 2026-11-02 05:00 UTC4,341star +3 / 7 天401fork同步于 2026-11-10 11:38 UTC

怎么上手

由 README 提炼,执行前请确认
pip install optillm
export OPENAI_API_KEY="your-key-here"
optillm
硬件要求按 README 说明

README 未说明具体显存要求;本地推理需设置 OPTILLM_API_KEY,可加载任意 HuggingFace 模型并叠加 LoRA 适配器,也可只做代理不跑本地模型。

有 Docker 镜像
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

OpenAI 兼容的推理优化代理,不改模型权重就能提升推理准确率

一个面向 LLM 的推理优化代理,通过 API 网关接入,自动套用思维链等推理策略来提升模型回答质量并降低调用成本。

核心能力

  • 用模型名前缀或 extra_body 选择 20+ 推理优化技术
  • 支持 & 串行流水线与 | 并行组合多种技术
  • 内置本地推理服务,支持 logprobs 与 CoT/熵解码
  • proxy 插件可当自托管 LLM 网关做负载均衡与故障转移
  • 通过 LiteLLM 接入 OpenAI、Anthropic、Gemini 等多家模型

容易踩的坑

Anthropic API、llama.cpp-server 和 ollama 不支持多响应采样,可用技术受限;本地推理需额外下载 HuggingFace 模型,私有模型要设 HF_TOKEN;默认监听 8000 端口,客户端 base_url 需指向 http://localhost:8000/v1。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v0.4.1
  1. v0.4.1最新正式版2026-11-02 · 2026-11-02 05:00 UTC

    What's Changed

    Action required if you use these features

    • executecode is now disabled by default (#337, #302). The plugin runs Python from requests and LLM responses with no sandboxing. To keep using it, start optillm with --enable-unsafe-plugins=executecode or set OPTILLM_ENABLE_UNSAFE_PLUGINS=executecode. Only enable it in single-user, air-gapped environments.
    • MCP secrets could be written to logs. The MCP plugin wrote configured env and headers values, which can include API keys, to ~/.optillm/logs/mcp_plugin.log. It now logs only the names. If you use the plugin, check that file for old secrets and rotate any you find.

    New

    • Streaming hints plugin (#352, #206): streaming_hints watches the model's reasoning as it is generated and injects relevant hints from a memory bank at moments of uncertainty.
    • Legacy completions endpoint: the inbuilt inference server now exposes POST /v1/completions.
    • LLM gateway guide: docs/llm-gateway.md covers using the proxy plugin for routing and inference optimization together.

    Security

    • readurls: blocks SSRF destinations, including CGNAT/shared and multicast ranges.
    • z3: statically gates solver code to the declared z3/sympy subset and closes string-based evasions of the AST attribute denylist.

    Fixes

    • max_completion_tokens (#350): pass-through and proxy requests no longer add max_tokens, which o-series and gpt-5 models reject with a 400. The local inference server now honors max_completion_tokens.
    • mcts: follows tree selection through to a leaf.
    • mars: populates diverse aggregation groups, preserves full agent IDs when applying verification, and matches solution authors across string and integer IDs.
    • bon: excludes truncated and blank candidates.
    • rstar: backpropagates rewards from evaluated rollout nodes and preserves signed and decimal answers.
    • deepconf: votes and calibrates as in the DeepConf reference implementation.
    • entropy_decoding: keeps the nucleus head and applies min_p in sampling.

    Project

    • CI now runs every test file, and MCP tests run on pull requests.
    • The README has been streamlined.

    Thanks to Parman Mohammadalizadeh, akushonkamen, ZY Liu, flyingdoubleG, and Daniel Peng for their contributions.

    Full Changelog: https://github.com/algorithmicsuperintelligence/optillm/compare/v0.4.0...v0.4.1

  2. v0.4.02026-09-28 · 2026-09-28 02:27 UTC
    查看更新说明

    What's Changed

    Fix: proxy plugin config, logging and agent clients (#330, #331)

    • Proxy target ignored: without ~/.optillm/proxy_config.yaml, the proxy silently loaded the bundled example config and routed to its sample providers. It now creates an empty template instead. A single failed request no longer sends all later traffic to --base-url: 4xx errors don't mark a provider unhealthy, and unhealthy providers are retried before falling back.
    • /v1/models lists the configured providers' models (plus model_map aliases) with --approach proxy.
    • Agent clients (e.g. Crush): the none and proxy approaches now forward the original conversation, including tool_calls and tool results, instead of flattening it. Streamed responses carry tool calls, finish reason and usage. stream_options is no longer forwarded upstream, and messages with content: null no longer crash parsing.
    • Logging: --log / OPTILLM_LOG now apply to all modules and are case-insensitive, so DEBUG logs from the proxy and other plugins show up.

    MCP plugin ported to mcp 2.x

    • Works with the MCP Python SDK 2.x (MCPError, snake_case result fields).
    • New streamable_http transport, with headers and timeouts.

    Breaking changes

    • MCP websocket transport removed (dropped from the MCP Python SDK in 2.x). Configs using "transport": "websocket" must switch to streamable_http or sse.
    • Requires mcp>=2,<3. Environments that also need mcp<2 won't install.
    • The proxy no longer loads the bundled example_config.yaml when ~/.optillm/proxy_config.yaml is missing. Requests use the server's default client (--base-url) until you add providers.
    • OPTILLM_LOG_LEVEL removed. Use --log / OPTILLM_LOG; monitoring.log_level in the proxy config is an optional proxy-only override.

    Thanks to @brettowe for the detailed report.

    Full Changelog: https://github.com/algorithmicsuperintelligence/optillm/compare/v0.3.22...v0.4.0

  3. v0.3.222026-07-18 · 2026-07-18 12:38 UTC
    查看更新说明

    What's Changed

    Fix: autothink, thinkdeeper and deepconf for transformers >= 5 (#320)

    Since transformers 5, apply_chat_template(return_tensors="pt") returns a BatchEncoding rather than a plain tensor, so passing the result straight to model(input_ids=...) raised. The tensor is now unwrapped via .input_ids:

    • optillm/thinkdeeper.py
    • optillm/autothink/processor.py
    • optillm/deepconf/processor.py

    The unwrap is chained with the existing device transfer (.input_ids.to(self.model.device)) so tokens still land on the model's device — Tensor.to() returns a new tensor rather than mutating in place, so the assignment matters on CUDA/MPS.

    Thanks to @jacquerie for diagnosing and reporting this.

    README: dropped the GitHub stars badge and switched the downloads badge to pepy.tech, which reports actual download counts.

    Full Changelog: https://github.com/algorithmicsuperintelligence/optillm/compare/v0.3.21...v0.3.22

  4. v0.3.212026-07-05 · 2026-07-05 05:41 UTC
    查看更新说明

    What's Changed

    Fix: broken PyPI wheel — import optillm failed with ModuleNotFoundError: No module named 'math_verify' (#318)

    The published wheel is built from pyproject.toml [project.dependencies], which had drifted from requirements.txt, so pip install optillm shipped a package that couldn't even start:

    • math-verify was missing from pyproject.toml — optillm/cepo/cepo.py imports it at import time, so importing optillm crashed. (Affected 0.3.16–0.3.20.)
    • transformers was unpinned — the <5.13.0 cap added in 0.3.19 only landed in requirements.txt, so PyPI installs pulled transformers 5.13.0 and broke mlx-lm on Apple silicon.

    Fix

    Synced the runtime deps into pyproject.toml: added math-verify, pinned transformers>=5.0.0,<5.13.0, and outlines[transformers]>=1.2.3.

    Verified by building the wheel and installing it into a clean venv (only its declared deps) — import optillm succeeds and transformers resolves to 5.12.x.

    If you hit the math_verify import error on 0.3.16–0.3.20, upgrade to 0.3.21.

    Full Changelog: https://github.com/algorithmicsuperintelligence/optillm/compare/v0.3.20...v0.3.21

  5. v0.3.202026-07-05 · 2026-07-05 04:02 UTC
    查看更新说明

    What's Changed

    Fix: runaway local generation for models whose ChatML end token differs from their tokenizer EOS (#317)

    Running such a model through optillm's built-in local inference never stopped early and generated the full max_new_tokens default (4096) on every call that omitted max_tokens — e.g. dhara-250m's chat ends at <|im_end|> (49154) but its tokenizer eos_token is <|end_of_text|> (1), so it rambled ~800s/call.

    • Honor generation_config.eos_token_id: generation now resolves EOS from the model's own generation config (merging the tokenizer EOS as a fallback) instead of hardcoding tokenizer.eos_token_id. Fixes any chat model with this mismatch; well-behaved models (e.g. Qwen2.5, whose tokenizer EOS already is <|im_end|>) are unchanged.
    • OPTILLM_MAX_TOKENS: new env var to override the default max_new_tokens (default stays 4096), bounding any request that sends no max_tokens. An explicit request max_tokens still takes precedence. Useful for small models that don't reliably emit an EOS token.

    Only the local inference engine (OPTILLM_API_KEY=optillm) is affected; proxied providers handle stopping themselves. Includes unit tests for both helpers.

    Full Changelog: https://github.com/algorithmicsuperintelligence/optillm/compare/v0.3.19...v0.3.20

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    OptiLLM

    OptiLLM is an OpenAI API-compatible optimizing inference proxy that implements 20+ state-of-the-art techniques to dramatically improve LLM accuracy and performance on reasoning tasks, without requiring any model training or fine-tuning.

    It is possible to beat the frontier models using these techniques across diverse tasks by doing additional compute at inference time. A good example of how to combine such techniques is the CePO approach from Cerebras.

    Key features

    • Instant improvements: 2-10x better accuracy on math, coding, and logical reasoning
    • Drop-in replacement: Works with any OpenAI-compatible API endpoint
    • 20+ optimization techniques: From simple best-of-N to advanced MCTS and planning
    • Zero training required: Just proxy your existing API calls through OptiLLM
    • Production ready: Used in production by companies and researchers worldwide
    • Multi-provider: Supports OpenAI, Anthropic, Google, Cerebras, and 100+ models via LiteLLM

    Quick start

    pip install optillm
    export OPENAI_API_KEY="your-key-here"
    optillm
    

    Point any OpenAI client at the proxy and prefix the model name with a technique:

    from openai import OpenAI
    
    client = OpenAI(base_url="http://localhost:8000/v1")
    
    response = client.chat.completions.create(
        model="moa-gpt-4o-mini",  # This gives you GPT-4o performance from GPT-4o-mini
        messages=[{"role": "user", "content": "Solve: If 2x + 3 = 7, what is x?"}],
    )
    

    Before OptiLLM: "x = 1"
    After OptiLLM: "Let me work through this step by step: 2x + 3 = 7, so 2x = 4, therefore x = 2"

    Results

    TechniqueBase modelImprovementBenchmark
    MARSGemini 2.5 Flash Lite+30.0 pointsAIME 2025 (43.3 to 73.3)
    CePOLlama 3.3 70B+18.6 pointsMath-L5 (51.0 to 69.6)
    LongCePOLlama 3.3 70B+13.6 pointsInfiniteBench (58.0 to 71.6)
    AutoThinkDeepSeek-R1-1.5B+9.34 pointsGPQA-Diamond (21.72 to 31.06)
    PlanSearchGPT-4o-mini+20% pass@5LiveCodeBench
    MOAGPT-4o-miniMatches GPT-4Arena-Hard-Auto

    See benchmark results for the full tables.

    Installation

    pip

    pip install optillm
    

    Docker

    docker pull ghcr.io/algorithmicsuperintelligence/optillm:latest
    docker run -p 8000:8000 ghcr.io/algorithmicsuperintelligence/optillm:latest
    
    Image tagContents
    latestAll dependencies for local inference and plugins
    latest-proxyLightweight image without local inference
    latest-offlineSelf-contained image with pre-downloaded models (spaCy) for fully offline operation

    To build and run from the repository, set your keys in docker-compose.yaml or a .env file and run docker compose up -d.

    From source

    git clone https://github.com/algorithmicsuperintelligence/optillm.git
    cd optillm
    python3 -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt
    python optillm.py
    

    Providers

    Set the environment variable for your provider and the proxy picks the matching client.

    ProviderRequired environment variablesNotes
    OptiLLMOPTILLM_API_KEYBuilt-in local inference server; supports logprobs and decoding techniques such as cot_decoding and entropy_decoding
    OpenAIOPENAI_API_KEYAlso works with any OpenAI-compatible endpoint (e.g. OpenRouter) by setting --base-url
    CerebrasCEREBRAS_API_KEYSee the Cerebras docs
    Azure OpenAIAZURE_OPENAI_API_KEYAZURE_API_VERSIONAZURE_API_BASE
    Azure OpenAI (Managed Identity)AZURE_API_VERSIONAZURE_API_BASERequires az login; see the Azure docs
    LiteLLMDepends on the modelSee the LiteLLM docs

    Other models work through LiteLLM. For example, set GEMINI_API_KEY and call moa-gemini/gemini-1.5-flash-002.

    Usage

    Selecting a technique

    When the server runs with the default auto approach, a technique can be selected in three ways, in this order of preference:

    # 1. Model name prefix
    client.chat.completions.create(model="moa-gpt-4o-mini", messages=messages)
    
    # 2. extra_body field
    client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        extra_body={"optillm_approach": "bon|moa|mcts"},
    )
    
    # 3. Tag in the system or user prompt
    client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "<optillm_approach>re2</optillm_approach> How many r's are there in strawberry?"}],
    )
    

    If the server is started with a specific --approach, set model to the model name only.

    Combining techniques

    • & runs techniques as a pipeline from left to right, using each response as the request to the next stage: cot_reflection&moa
    • | runs techniques in parallel and returns the responses as a list: bon|moa|mcts

    How requests flow

    Sequence diagram showing optillm in use

    • A is an existing tool, framework, or your own code using any OpenAI client SDK.
    • B is the optillm service, which sends requests to the configured base_url.
    • C is any service providing an OpenAI-compatible chat completions endpoint.

    For an LLM without an OpenAI-compatible endpoint, you can use the LiteLLM proxy server.

    Local inference

    Set OPTILLM_API_KEY to any value to use the built-in inference server, and use the same value in your client. Any HuggingFace model can be passed as the model name; set HF_TOKEN for private models. Add LoRA adapters with the + separator and choose one with active_adapter (the last one is used by default).

    client = OpenAI(api_key="optillm", base_url="http://localhost:8000/v1")
    
    response = client.chat.completions.create(
        model="meta-llama/Llama-3.2-1B-Instruct+patched-codes/Llama-3.2-1B-FastApply+patched-codes/Llama-3.2-1B-FixVulns",
        messages=messages,
        temperature=0.2,
        logprobs=True,
        top_logprobs=3,
        extra_body={"active_adapter": "patched-codes/Llama-3.2-1B-FastApply"},
    )
    

    Alternate decoding techniques are available on the local server:

    response = client.chat.completions.create(
        model="meta-llama/Llama-3.2-1B-Instruct",
        messages=messages,
        temperature=0.2,
        extra_body={
            "decoding": "cot_decoding",  # or "entropy_decoding"
            # CoT specific params
            "k": 10,
            "aggregate_paths": True,
            # OR entropy specific params
            "top_k": 27,
            "min_p": 0.03,
        },
    )
    

    The server also exposes the legacy POST /v1/completions endpoint. Streaming is not supported on it yet; use /v1/chat/completions for streaming.

    curl http://localhost:8000/v1/completions \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $OPTILLM_API_KEY" \
      -d '{"model": "meta-llama/Llama-3.2-1B-Instruct", "prompt": "Write a haiku about recursion.", "max_tokens": 64}'
    

    External servers (llama.cpp, ollama)

    export OPENAI_API_KEY="sk-no-key"  # placeholder
    ./llama-server -c 4096 -m path_to_model
    python3 optillm.py --base-url http://localhost:8080/v1
    

    [!WARNING] The Anthropic API, llama.cpp-server, and ollama do not support sampling multiple responses from a model, which limits the available approaches to cot_reflection, leap, plansearch, rstar, rto, self_consistency, re2, and z3. For HuggingFace models, the built-in local inference server supports multiple responses.

    Use as an LLM gateway

    The proxy plugin turns OptiLLM into a self-hosted gateway with load balancing, failover, and health checks across any OpenAI-compatible providers, with no gateway fees. It can also apply any of the techniques below to the requests it routes, combining routing and optimization in one service. See Using OptiLLM as an LLM gateway for setup.

    Techniques

    ApproachSlugDescription
    MARS (Multi-Agent Reasoning System)marsMulti-agent reasoning with diverse temperature exploration, cross-verification, and iterative improvement
    Cerebras Planning and OptimizationcepoCombines Best of N, Chain-of-Thought, Self-Reflection, Self-Improvement, and various prompting techniques
    CoT with Reflectioncot_reflectionChain-of-thought reasoning with <thinking>, <reflection> and <output> sections
    PlanSearchplansearchSearch over candidate plans for solving a problem in natural language
    ReReadre2Improves reasoning by processing queries twice
    Self-Consistencyself_consistencyAn advanced self-consistency method
    Z3 Solverz3Uses the Z3 theorem prover for logical reasoning
    R* AlgorithmrstarThe R* algorithm for problem solving
    LEAPleapLearns task-specific principles from few-shot examples
    Round Trip OptimizationrtoOptimizes responses through a round-trip process
    Best of N SamplingbonGenerates multiple responses and selects the best one
    Mixture of AgentsmoaCombines responses from multiple critiques
    Monte Carlo Tree SearchmctsUses MCTS for decision-making in chat responses
    PV GamepvgApplies a prover-verifier game at inference time
    Deep ConfidenceLocal onlyConfidence-guided reasoning with multiple intensity levels
    CoT DecodingLocal onlyChain-of-thought decoding to elicit reasoning without explicit prompting
    Entropy DecodingLocal onlyAdaptive sampling based on the uncertainty of tokens during generation
    ThinkdeeperLocal onlyThe reasoning_effort parameter for reasoning models like DeepSeek R1
    AutoThinkLocal onlyCombines query complexity classification with steering vectors

    Plugins

    PluginSlugDescription
    System Prompt LearningsplImplements what Andrej Karpathy called the third paradigm for LLM learning, letting the model acquire problem-solving knowledge and strategies
    Deep ThinkdeepthinkA Gemini-like Deep Think approach using inference-time scaling for reasoning LLMs
    Long-Context Cerebras Planning and OptimizationlongcepoCombines planning and divide-and-conquer processing of long documents
    Majority Votingmajority_votingGenerates k candidate solutions and selects the most frequent answer (default k=6)
    MCP ClientmcpModel Context Protocol client for using any LLM with any MCP server
    RouterrouterUses the optillm-modernbert-large model to route requests to approaches based on the prompt
    Chain-of-CodecocCombines CoT with code execution and LLM-based code simulation
    MemorymemoryShort-term memory layer for unbounded context length with any LLM. Set OPTILLM_MEMORY_FILE to persist memories across requests
    CompactcompactCompresses conversation context that exceeds a token budget into a structured summary, keeping recent turns verbatim
    PrivacyprivacyAnonymizes PII in the request and restores it in the response
    Read URLsreadurlsFetches URLs found in the request and adds their content to the context
    Execute CodeexecutecodeRuns Python code from requests and LLM responses. Disabled by default; see Security
    JSONjsonStructured outputs using the outlines library; supports pydantic types and JSON schema
    GenSelectgenselectGenerates multiple candidates and selects the best based on quality criteria
    Web Searchweb_searchPerforms Google searches using Chrome automation (Selenium)
    Deep Researchdeep_researchTest-Time Diffusion Deep Researcher (TTD-DR) for research reports using iterative refinement
    ProxyproxyLoad balancing and failover across LLM providers with health monitoring and round-robin routing
    Streaming Hintsstreaming_hintsWatches reasoning as it is generated and injects relevant hints from a memory bank at moments of uncertainty

    MCP plugin

    The Model Context Protocol plugin connects OptiLLM to MCP servers, making their tools, resources, and prompts available to the model. When the model calls a tool, the plugin executes it and returns the result to the model.

    Configure servers in ~/.optillm/mcp_config.json:

    {
      "mcpServers": {
        "filesystem": {
          "transport": "stdio",
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/docs"],
          "description": "Local filesystem access"
        },
        "github": {
          "transport": "sse",
          "url": "https://api.githubcopilot.com/mcp",
          "headers": {
            "Authorization": "Bearer ${GITHUB_TOKEN}",
            "Accept": "text/event-stream"
          },
          "description": "GitHub MCP server"
        },
        "remote-http": {
          "transport": "streamable_http",
          "url": "https://api.example.com/mcp",
          "headers": {
            "Authorization": "Bearer ${API_TOKEN}"
          },
          "description": "Remote Streamable HTTP MCP server"
        }
      },
      "log_level": "INFO"
    }
    
    TransportRequiredOptional
    stdio (default)commandargs, env
    sseurlheaders, sse_read_timeout (default 300.0)
    streamable_httpurlheaders, sse_read_timeout (default 300.0)

    All transports accept description and timeout (connection timeout in seconds, default 5.0). The websocket transport was removed in MCP Python SDK 2.x; use streamable_http or sse instead. String values such as headers support ${VARIABLE_NAME} expansion, and those variables must be set before starting OptiLLM.

    Any of the official MCP servers can be used. Logs are written to ~/.optillm/logs/mcp_plugin.log; check there for connection and tool errors.

    Configuration

    Parameters can be passed on the command line. Most can also be set as environment variables prefixed with OPTILLM_, for example OPTILLM_APPROACH=mcts. Run optillm --help for the full list.

    ParameterDescriptionDefault
    --approachInference approach to useauto
    --modelOpenAI model to usegpt-4o-mini
    --base-urlBase URL for an OpenAI-compatible endpoint""
    --hostHost address to bind the server127.0.0.1
    --portPort to run the proxy on8000
    --optillm-api-keyOptional API key for client authentication to optillm""
    --nNumber of final responses to return1
    --return-full-responseReturn the full response including the CoT with <thinking> tagsFalse
    --mcts-simulationsNumber of MCTS simulations2
    --mcts-explorationExploration weight for MCTS0.2
    --mcts-depthSimulation depth for MCTS1
    --best-of-nNumber of samples for the best_of_n approach3
    --rstar-max-depthMaximum depth for the R* algorithm3
    --rstar-num-rolloutsNumber of rollouts for the R* algorithm5
    --rstar-cExploration constant for the R* algorithm1.4
    --cepo_*See CePO parameters belowVarious
    ParameterDescriptionDefault
    --cepo_bestofn_nNumber of responses to be generated in best of n stage3
    --cepo_bestofn_temperatureTemperature for verifier in best of n stage0.1
    --cepo_bestofn_max_tokensMaximum number of tokens for verifier in best of n stage4096
    --cepo_bestofn_rating_typeType of rating in best of n stage ("absolute" or "pairwise")"absolute"
    --cepo_planning_nNumber of plans generated in planning stage3
    --cepo_planning_mNumber of attempts to generate n plans in planning stage6
    --cepo_planning_temperature_step1Temperature for generator in step 1 of planning stage0.55
    --cepo_planning_temperature_step2Temperature for generator in step 2 of planning stage0.25
    --cepo_planning_temperature_direct_respTemperature for generator after step 2 if planning fails and answer directly0.1
    --cepo_planning_temperature_step3Temperature for generator in step 3 of planning stage0.1
    --cepo_planning_temperature_step4Temperature for generator in step 4 of planning stage0
    --cepo_planning_max_tokens_step1Maximum number of tokens in step 1 of planning stage4096
    --cepo_planning_max_tokens_step2Maximum number of tokens in step 2 of planning stage4096
    --cepo_planning_max_tokens_direct_respMaximum number of tokens after step 2 if planning fails and answer directly4096
    --cepo_planning_max_tokens_step3Maximum number of tokens in step 3 of planning stage4096
    --cepo_planning_max_tokens_step4Maximum number of tokens in step 4 of planning stage4096
    --cepo_use_reasoning_fallbackWhether to fallback to lower levels of reasoning when higher level failsFalse
    --cepo_num_of_retriesNumber of retries if llm call fails, 0 for no retries0
    --cepo_print_outputWhether to print the output of each stageFalse
    --cepo_config_filePath to CePO configuration fileNone
    --cepo_use_plan_diversityUse additional plan diversity stepFalse
    --cepo_rating_modelSpecify a model for rating step if different than for completionNone

    Security

    Network binding and authentication. The server binds to 127.0.0.1 by default. Use --host 0.0.0.0 to allow external connections, and only on trusted networks or with authentication enabled. Set --optillm-api-key (or OPTILLM_API_KEY) to require clients to send Authorization: Bearer <key>.

    Code execution. The executecode plugin runs Python from requests and LLM responses in a live Jupyter kernel with no sandboxing, so it is disabled unless you opt in. Only enable it in single-user, air-gapped environments where whoever submits requests is trusted with full access to the host.

    optillm --enable-unsafe-plugins=executecode
    # or: export OPTILLM_ENABLE_UNSAFE_PLUGINS=executecode
    

    URL fetching. The readurls plugin blocks requests to non-public destinations (private, loopback, link-local, and reserved addresses such as the cloud metadata IP 169.254.169.254) to prevent SSRF. Every redirect hop is re-validated and unresolvable hosts are rejected. Only opt out on trusted networks that need internal URL fetching:

    optillm --readurls-allow-internal
    # or: export OPTILLM_READURLS_ALLOW_INTERNAL=true
    

    The guard validates DNS resolution before each request, but the HTTP client resolves the host again when it connects, so a domain under attacker control could rebind to an internal address between the two lookups. For high-security deployments, also restrict the network egress of the optillm process with a firewall or service-mesh policy.

    SSL verification. Use a custom CA bundle for self-signed certificates or corporate proxies. Disabling verification is insecure and intended for development only. See SSL_CONFIGURATION.md for details.

    optillm --ssl-cert-path /path/to/ca-bundle.crt  # or: export OPTILLM_SSL_CERT_PATH=...
    optillm --no-ssl-verify                         # or: export OPTILLM_SSL_VERIFY=false
    

    Benchmark results

    MARS on AIME 2025, IMO 2025, and LiveCodeBench (Oct 2025)

    BenchmarkApproachProblemsCorrectAccuracyImprovement
    AIME 2025Baseline301343.3%-
    AIME 2025MARS302273.3%+30.0pp (+69.2%)
    IMO 2025Baseline6116.7%-
    IMO 2025MARS6233.3%+16.7pp (+100%)
    LiveCodeBench v5/v6Baseline1054139.05%-
    LiveCodeBench v5/v6MARS1055350.48%+11.43pp (+29.3%)

    Model: google/gemini-2.5-flash-lite-preview-09-2025 via OpenRouter. Configuration: 3 agents, 2-pass verification, thinking tags disabled for proofs.

    CePO on math and code benchmarks (Sep 2025)

    MethodAIME 2024AIME 2025GPQALiveCodeBench
    Qwen3 8B74.068.359.355.7
    CePO (using Qwen3 8B)86.780.062.560.5
    Qwen3 32B81.472.966.865.7
    CePO (using Qwen3 32B)90.783.370.071.9
    Qwen3 235B85.781.571.170.7
    DeepSeek R179.870.071.564.3
    OpenAI o3-mini79.674.876.866.3
    Grok3 Think83.977.380.270.6

    AutoThink on GPQA-Diamond and MMLU-Pro (May 2025)

    ModelGPQA-DiamondMMLU-Pro
    Accuracy (%)Avg. TokensAccuracy (%)Avg. Tokens
    DeepSeek-R1-Distill-Qwen-1.5B21.727868.2625.582842.75
    with Fixed Budget28.473570.0026.181815.67
    with AutoThink31.063520.5226.381792.50

    LongCePO on LongBench v2 (Apr 2025)

    Model¹Context windowShort samples (up to 32K words)Medium samples (32–128K words)
    Llama 3.3 70B Instruct128K36.7 (45.0)27.0 (33.0)
    LongCePO + Llama 3.3 70B Instruct8K36.8 ± 1.3838.7 ± 2.574 (39.735)²
    Mistral-Large-Instruct-2411128K41.7 (46.1)30.7 (34.9)
    o1-mini-2024-09-12128K48.6 (48.9)33.3 (32.9)
    Claude-3.5-Sonnet-20241022200K46.1 (53.9)38.6 (41.9)
    Llama-4-Maverick-17B-128E-Instruct524K32.22 (50.56)28.84 (41.86)

    ¹ Performance numbers reported by LongBench v2 authors, except for LongCePO and Llama-4-Maverick results.

    ² Numbers in parentheses for LongCePO indicate accuracy of majority voting from 5 runs.

    LongCePO on HELMET - InfiniteBench En.MC, 128K length (Apr 2025)

    ModelAccuracy (%)
    Llama 3.3 70B Instruct (full context)58.0
    LongCePO + Llama 3.3 70B Instruct (8K context)71.6 ± 1.855 (73.0)¹
    o1-mini-2024-09-12 (full context)58.0
    gpt-4o-2024-08-06 (full context)74.0

    ¹ Numbers in parentheses for LongCePO indicate accuracy of majority voting from 5 runs.

    CePO on math and code benchmarks (Mar 2025)

    MethodMath-L5MMLU-Pro (Math)CRUXLiveCodeBench (pass@1)Simple QA
    Llama 3.3 70B51.078.672.627.120.9
    Llama 3.1 405B49.879.273.031.813.5
    CePO (using Llama 3.3 70B)69.684.880.131.922.6
    QwQ 32B61.490.882.544.37.8
    CePO (using QwQ 32B)88.192.086.351.58.2
    DeepSeek R1 Llama83.182.084.047.314.6
    CePO (using DeepSeek R1 Llama)90.284.089.447.215.5

    coc-claude-3-5-sonnet-20241022 on AIME 2024 pass@1 (Nov 2024)

    ModelScore
    o1-mini56.67
    coc-claude-3-5-sonnet-2024102246.67
    coc-gemini/gemini-exp-112146.67
    o1-preview40.00
    gemini-exp-111436.67
    claude-3-5-sonnet-2024102220.00
    gemini-1.5-pro-00220.00
    gemini-1.5-flash-00216.67

    readurls&memory-gpt-4o-mini on Google FRAMES Benchmark (Oct 2024)

    ModelAccuracy
    readurls&memory-gpt-4o-mini61.29
    gpt-4o-mini50.61
    readurls&memory-Gemma2-9b30.1
    Gemma2-9b5.1
    Gemma2-27b30.8
    Gemini Flash 1.566.5
    Gemini Pro 1.572.9

    plansearch-gpt-4o-mini on LiveCodeBench (Sep 2024)

    Modelpass@1pass@5pass@10
    plansearch-gpt-4o-mini44.0359.3163.5
    gpt-4o-mini43.950.6153.25
    claude-3.5-sonnet51.3
    gpt-4o-2024-05-1345.2
    gpt-4-turbo-2024-04-0944.2

    moa-gpt-4o-mini on Arena-Hard-Auto (Aug 2024)

    Results showing Mixture of Agents approach using gpt-4o-mini on Arena Hard Auto Benchmark

    optillm with Patchwork (July 2024)

    We used optillm with patchwork, an open-source framework that automates development work such as PR reviews, bug fixing, and security patching through workflows called patchflows. The mixture of agents approach (moa) improved performance across all supported patchflows.

    Results showing optillm mixture of agents approach used with patchflows

    Testing

    pip install -r tests/requirements.txt
    
    # Approach tests
    python tests/test.py
    python tests/test.py --approaches moa bon mcts
    python tests/test.py --single-test "Simple Math Problem"
    
    # Unit and integration tests
    ./tests/run_tests.sh
    pytest tests/test_plugins.py -v
    

    Tests run on pull requests through GitHub Actions. See tests/README.md for the test structure and how to write new tests.

    Contributing

    References

    Citation

    If you use this library in your research, please cite:

    @software{optillm,
      title = {OptiLLM: Optimizing inference proxy for LLMs},
      author = {Asankhaya Sharma},
      year = {2024},
      publisher = {GitHub},
      url = {https://github.com/algorithmicsuperintelligence/optillm}
    }