Skip to content

Commit f74e678

Browse files
codelionclaude
andauthored
Merge PR #352: streaming hints plugin and 0.4.1 release
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 parents b63ce5c + 3426254 commit f74e678

23 files changed

Lines changed: 1415 additions & 704 deletions

‎.github/workflows/test.yml‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,23 @@ jobs:
5353
python tests/test_ci_quick.py
5454
python -m pytest tests/test_plugins.py -v --tb=short || python tests/test_plugins.py
5555
python -m pytest tests/test_proxy_plugin.py -v --tb=short
56+
python -m pytest tests/test_streaming_hints.py -v --tb=short
57+
python -m pytest tests/test_plugin_gating.py -v --tb=short
58+
python -m pytest tests/test_max_completion_tokens.py -v --tb=short
59+
python -m pytest tests/test_bon_candidate_filtering.py -v --tb=short
60+
python -m pytest tests/test_compact_plugin.py -v --tb=short
61+
python -m pytest tests/test_completions_endpoint.py -v --tb=short
62+
python -m pytest tests/test_entropy_decoding_sampling.py -v --tb=short
63+
python -m pytest tests/test_mars_agent_routing.py -v --tb=short
64+
python -m pytest tests/test_mars_aggregation_sampling.py -v --tb=short
65+
python -m pytest tests/test_mars_imo25.py -v --tb=short
66+
python -m pytest tests/test_mars_workspace_verification.py -v --tb=short
67+
python -m pytest tests/test_mcts_selection.py -v --tb=short
68+
python -m pytest tests/test_privacy_plugin_performance.py -v --tb=short
69+
python -m pytest tests/test_readurls_ssrf.py -v --tb=short
70+
python -m pytest tests/test_rstar_backpropagation.py -v --tb=short
71+
python -m pytest tests/test_rstar_numeric_answers.py -v --tb=short
72+
python -m pytest tests/test_z3_solver_guard.py -v --tb=short
5673
python tests/test_approaches.py
5774
python tests/test_reasoning_simple.py
5875
python tests/test_batching.py
@@ -125,7 +142,7 @@ jobs:
125142
OPTILLM_API_KEY=optillm python tests/test_reasoning_integration.py
126143
OPTILLM_API_KEY=optillm python tests/test_json_plugin.py
127144
OPTILLM_API_KEY=optillm python tests/test_n_parameter.py
128-
OPTILLM_API_KEY=optillm python -m pytest tests/test_api_compatibility.py -v --tb=short || echo "API compatibility tests require pytest"
145+
OPTILLM_API_KEY=optillm python -m pytest tests/test_api_compatibility.py -v --tb=short
129146
OPTILLM_API_KEY=optillm python tests/test.py --approaches none --single-test "Simple Math Problem" || echo "Main test completed"
130147
131148
# Run SSL config tests (no server needed but requires proper env setup)
@@ -256,7 +273,6 @@ jobs:
256273
mcp-tests:
257274
runs-on: ubuntu-latest
258275
needs: unit-tests
259-
if: github.event_name == 'push' && github.ref == 'refs/heads/main' # Only run on main branch pushes (secrets available)
260276
strategy:
261277
matrix:
262278
python-version: ['3.12']
@@ -296,5 +312,6 @@ jobs:
296312
echo "MCP tests completed successfully!"
297313
env:
298314
OPTILLM_API_KEY: optillm
315+
# Not available on fork PRs, where the one test that needs it skips itself
299316
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
300317
HF_TOKEN: ${{ secrets.HF_TOKEN }}

‎README.md‎

Lines changed: 244 additions & 682 deletions
Large diffs are not rendered by default.

‎docs/llm-gateway.md‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Using OptiLLM as an LLM gateway
2+
3+
OptiLLM's proxy mode gives you one self-hosted, OpenAI-compatible endpoint in front of any number of providers, with load balancing, failover, and health checks. It is free and Apache-2.0 licensed, and you pay your providers directly.
4+
5+
OptiLLM combines routing and inference optimization in the same service. The same request that is routed across providers can also run through [20+ state-of-the-art reasoning techniques](../README.md#techniques), so your gateway can improve answers as well as deliver them.
6+
7+
## Quick start
8+
9+
Create `~/.optillm/proxy_config.yaml`:
10+
11+
```yaml
12+
providers:
13+
- name: openai
14+
base_url: https://api.openai.com/v1
15+
api_key: ${OPENAI_API_KEY}
16+
weight: 3
17+
18+
- name: together
19+
base_url: https://api.together.xyz/v1
20+
api_key: ${TOGETHER_API_KEY}
21+
weight: 1
22+
model_map:
23+
gpt-4o-mini: meta-llama/Llama-3.3-70B-Instruct-Turbo
24+
25+
- name: local
26+
base_url: http://localhost:8080/v1
27+
api_key: none
28+
max_concurrent: 2
29+
30+
routing:
31+
strategy: weighted # or round_robin, failover
32+
health_check:
33+
enabled: true
34+
interval: 30
35+
```
36+
37+
Start the server with the proxy as the default approach and protect it with an API key:
38+
39+
```bash
40+
optillm --approach proxy --optillm-api-key "$GATEWAY_KEY"
41+
```
42+
43+
Point any OpenAI client at it:
44+
45+
```python
46+
from openai import OpenAI
47+
48+
client = OpenAI(api_key=GATEWAY_KEY, base_url="http://localhost:8000/v1")
49+
50+
response = client.chat.completions.create(
51+
model="gpt-4o-mini",
52+
messages=[{"role": "user", "content": "Hello"}],
53+
)
54+
```
55+
56+
If a provider fails, the request moves to the next one, and then to the server's default client (`--base-url`) if one is available.
57+
58+
## Adding inference optimization
59+
60+
Start the server without `--approach proxy` and select the proxy per request, on its own or wrapped around a technique:
61+
62+
```python
63+
# Route only
64+
client.chat.completions.create(model="proxy-gpt-4o-mini", messages=messages)
65+
66+
# Run Mixture of Agents, sending its calls through the proxy
67+
client.chat.completions.create(
68+
model="gpt-4o-mini",
69+
messages=messages,
70+
extra_body={"optillm_approach": "proxy", "proxy_wrap": "moa"},
71+
)
72+
```
73+
74+
See the [proxy plugin documentation](../optillm/plugins/proxy/README.md) for the full configuration reference.

‎optillm/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Version information
2-
__version__ = "0.4.0"
2+
__version__ = "0.4.1"
33

44
import os as _os
55

‎optillm/inference.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1872,6 +1872,10 @@ def create(
18721872
) -> ChatCompletion:
18731873
"""Create a chat completion with OpenAI-compatible parameters"""
18741874
logger.info("Starting chat completion creation")
1875+
# max_completion_tokens is the preferred name for the same limit
1876+
max_completion_tokens = kwargs.pop("max_completion_tokens", None)
1877+
if max_completion_tokens is not None:
1878+
max_tokens = max_completion_tokens
18751879
if stream:
18761880
raise NotImplementedError("Streaming is not yet supported")
18771881

‎optillm/plugins/mcp_plugin.py‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,6 @@ def load_config(self) -> bool:
192192

193193
with open(self.config_path, 'r') as f:
194194
config_data = f.read()
195-
logger.debug(f"Raw config data: {config_data}")
196195
config = json.loads(config_data)
197196

198197
# Set log level
@@ -204,7 +203,7 @@ def load_config(self) -> bool:
204203
servers_config = config.get("mcpServers", {})
205204
for server_name, server_config in servers_config.items():
206205
self.servers[server_name] = ServerConfig.from_dict(server_config)
207-
logger.debug(f"Loaded server config for {server_name}: {server_config}")
206+
logger.debug(f"Loaded server config for {server_name} (transport: {self.servers[server_name].transport})")
208207

209208
logger.info(f"Loaded configuration with {len(self.servers)} servers")
210209
return True
@@ -398,7 +397,7 @@ async def connect_sse(self) -> bool:
398397
"""Connect to server using SSE transport and discover capabilities"""
399398
logger.info(f"Connecting to SSE server: {self.server_name}")
400399
logger.debug(f"SSE URL: {self.config.url}")
401-
logger.debug(f"Headers: {self.config.headers}")
400+
logger.debug(f"Headers: {list(self.config.headers or {})}")
402401

403402
if not self.config.url:
404403
logger.error(f"SSE transport requires URL for server {self.server_name}")
@@ -435,7 +434,6 @@ async def connect_websocket(self) -> bool:
435434

436435
async def connect_stdio_native(self) -> bool:
437436
"""Connect using stdio transport with local executable"""
438-
logger.debug(f"Server configuration: {vars(self.config)}")
439437

440438
# Validate stdio configuration
441439
if not self.config.command:
@@ -455,7 +453,7 @@ async def connect_stdio_native(self) -> bool:
455453

456454
logger.debug(f"Using command: {full_command}")
457455
logger.debug(f"Arguments: {self.config.args}")
458-
logger.debug(f"Environment: {self.config.env}")
456+
logger.debug(f"Environment variables: {list(self.config.env or {})}")
459457

460458
# Create server parameters
461459
server_params = StdioServerParameters(

‎optillm/plugins/proxy_plugin.py‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,18 @@ def _request_messages(system_prompt: str, initial_query: str, messages: Optional
3737
{"role": "user", "content": initial_query}
3838
]
3939

40+
def _passthrough_config(request_config: Optional[dict]) -> dict:
41+
"""
42+
Build the kwargs forwarded to a provider. Streaming is stripped to force a
43+
complete response (server.py converts it to SSE if needed), and the max_tokens
44+
copy of max_completion_tokens is dropped because o-series and gpt-5 models reject it.
45+
"""
46+
api_config = dict(request_config or {})
47+
api_config.pop('stream', None)
48+
if api_config.get('max_completion_tokens') is not None:
49+
api_config.pop('max_tokens', None)
50+
return api_config
51+
4052
def run(system_prompt: str, initial_query: str, client, model: str,
4153
request_config: dict = None, messages: list = None) -> Tuple[str, int]:
4254
"""
@@ -65,9 +77,7 @@ def run(system_prompt: str, initial_query: str, client, model: str,
6577

6678
if not config.get('providers'):
6779
logger.warning(f"No providers configured in {ProxyConfig._config_path}, falling back to original client")
68-
# Strip stream parameter to force complete response
69-
api_config = dict(request_config or {})
70-
api_config.pop('stream', None)
80+
api_config = _passthrough_config(request_config)
7181

7282
response = client.chat.completions.create(
7383
model=model,
@@ -143,10 +153,7 @@ def run(system_prompt: str, initial_query: str, client, model: str,
143153
# message support and merges the system prompt when needed.
144154
logger.info(f"Direct proxy routing for model: {model}")
145155

146-
# Strip stream parameter to force complete response
147-
# server.py will handle converting to SSE streaming format if needed
148-
api_config = dict(request_config or {})
149-
api_config.pop('stream', None)
156+
api_config = _passthrough_config(request_config)
150157

151158
response = proxy_client.chat.completions.create(
152159
model=model,
@@ -162,9 +169,7 @@ def run(system_prompt: str, initial_query: str, client, model: str,
162169
logger.error(f"Proxy plugin error: {e}", exc_info=True)
163170
# Fallback to original client
164171
logger.info("Falling back to original client")
165-
# Strip stream parameter to force complete response
166-
api_config = dict(request_config or {})
167-
api_config.pop('stream', None)
172+
api_config = _passthrough_config(request_config)
168173

169174
response = client.chat.completions.create(
170175
model=model,
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
# Streaming Hints
2+
3+
Injects hints from a memory bank into the model's reasoning while it is being generated, inspired by [this idea from Will Brown](https://x.com/willccbb/status/1940557166248972387). Instead of putting every piece of guidance in the prompt up front, the plugin watches the reasoning and adds one targeted hint at the moment the model hesitates or moves to a new step.
4+
5+
This is the inference half of the approach. The retriever is rule-based for now; training the injection policy with RL is future work (see below).
6+
7+
## How it works
8+
9+
1. The model answers the query in segments of at most `segment_tokens` tokens.
10+
2. Each segment is fed sentence by sentence to the `StreamingHintRetriever`.
11+
3. A sentence is an **injection point** when at least `min_gap_chars` characters have passed since the last hint and the sentence contains an uncertainty signal ("wait", "hmm", "not sure", "let me check", ...) or ends a paragraph.
12+
4. At an injection point the retriever queries the `HintMemoryBank` with the problem plus the most recent reasoning. If the best unused hint scores at least `hint_threshold`, the segment is cut after that sentence and the hint is appended as `<hint>...</hint>`.
13+
5. Generation continues from the cut, with the reasoning so far (hints included) in the prompt. This repeats until the model finishes, `max_segments` is reached, or `max_tokens` is spent.
14+
15+
Segments are used instead of a token stream so the plugin works with every client optillm supports, including the local inference server, which does not stream. The cost is that up to one segment of text after an injection point is generated and then discarded.
16+
17+
The memory bank ranks hints by TF-IDF cosine similarity over the hint text and its keywords. It is pure Python, so the plugin has no extra dependencies.
18+
19+
## Usage
20+
21+
```python
22+
from openai import OpenAI
23+
24+
client = OpenAI(api_key="sk-...", base_url="http://localhost:8000/v1")
25+
26+
response = client.chat.completions.create(
27+
model="streaming_hints-gpt-4o-mini",
28+
messages=[{"role": "user", "content": "A train travels 120 km in 1.5 hours. What is its speed in m/s?"}],
29+
extra_body={"hint_threshold": 0.25, "show_hints": True},
30+
)
31+
```
32+
33+
It combines with other approaches like any plugin, for example `streaming_hints&cot_reflection-gpt-4o-mini`.
34+
35+
## Configuration
36+
37+
All options are read from the request body (`extra_body`).
38+
39+
| Option | Default | Description |
40+
|---|---|---|
41+
| `hint_threshold` | `0.2` | Minimum similarity score for a hint to be injected |
42+
| `max_hints` | `3` | Maximum number of hints injected per request |
43+
| `min_gap_chars` | `200` | Minimum characters of reasoning between two injections |
44+
| `segment_tokens` | `512` | Maximum tokens generated per segment |
45+
| `max_segments` | `8` | Maximum number of segments per request |
46+
| `hints_path` | bundled `hints.json` | Path to a custom hint bank |
47+
| `show_hints` | `false` | Return the reasoning with the `<hint>` tags instead of the model text only |
48+
49+
`max_tokens`, if set, caps the completion tokens across all segments.
50+
51+
## Custom hints
52+
53+
A hint bank is a JSON list. `keywords` count twice as much as words in `text` when matching.
54+
55+
```json
56+
[
57+
{
58+
"id": "math-units",
59+
"domain": "math",
60+
"text": "Write down the units of every quantity and check both sides match.",
61+
"keywords": ["units", "speed", "rate", "convert"]
62+
}
63+
]
64+
```
65+
66+
The bundled bank has 20 general hints for math, coding and logical reasoning. Domain-specific banks will usually do better.
67+
68+
## Future work
69+
70+
- **RL-trained retriever.** Learn when to inject and which hint to pick from downstream task accuracy, with and without hints as the reward signal. `Hint.uses` is tracked as a starting point for usage statistics.
71+
- **Embedding retrieval.** A bank backed by sentence embeddings can replace TF-IDF behind the same `search` interface.
72+
- **Token streaming.** For providers that stream, the retriever can be fed token deltas directly and the stream cancelled at the injection point, which avoids the discarded tail of a segment.
73+
- **Evaluation.** Benchmark results (GSM8K, MATH, HumanEval, MMLU) against the plain model and against putting all hints in the prompt.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
"""
2+
Streaming Hints Plugin for OptiLLM
3+
4+
Monitors the model's reasoning as it is generated and injects relevant hints
5+
from a memory bank at moments of uncertainty or between reasoning steps.
6+
"""
7+
8+
from .memory_bank import Hint, HintMemoryBank
9+
from .retriever import Injection, StreamingHintRetriever
10+
from .streaming_hints import run_streaming_hints
11+
12+
__all__ = ['Hint', 'HintMemoryBank', 'Injection', 'StreamingHintRetriever', 'run_streaming_hints']

0 commit comments

Comments
 (0)