Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,19 @@ All notable changes to SkillOpt are documented here. This project adheres to
search setting. An API key echoed in an error body is redacted before the
text reaches `fail_reason`, and the round deadline is checked again after
each response.
- **OfficeQA SpecStream search** as an opt-in `env.search_mode=specstream`
provider for `openai_chat`/`qwen_chat`. The default stays `offline` and no
config selects SpecStream automatically. Selecting it needs
`SPECSTREAM_API_KEY` and sends the generated search queries, one `POST` per
query with `speed=fast`, with that key in an `Authorization: Bearer` header
to SpecStream's web search endpoint. The task question is not sent. No key,
credential or account is bundled, a missing key fails the rollout before
the first model call, and service errors fail the rollout with no fallback.
Redirects are not followed, an API key echoed in an error body is redacted,
and one `search_timeout_seconds` deadline, checked again after each
response, covers each round. It uses the core `httpx` dependency, so it
needs no extra. Its scores are not directly comparable to the paper's
Google-backed search setting.
- **SkillOpt-Sleep paired A/B evalkit** (`python -m skillopt_sleep.evalkit`):
McNemar plus percentile-bootstrap CIs on a fixed task manifest, with
task-cluster multi-seed inference and seeded null calibration for exact-test
Expand Down
43 changes: 41 additions & 2 deletions docs/reference/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,9 @@ corpus and makes no network search call.
| `env.search_mode: azure_search` | Use the model-provided Azure search path. |
| `env.search_mode: parallel` | Opt in to Parallel's hosted Search MCP. Requires `openai_chat` or `qwen_chat` and the `parallel` extra. |
| `env.search_mode: keenable` | Opt in to Keenable's search API. Requires `openai_chat` or `qwen_chat`; no extra and no key needed. |
| `env.search_timeout_seconds` | Whole MCP discovery/search deadline in seconds (default `20`); for `keenable`, the deadline for all queries of one round. |
| `env.search_max_num_results` | Maximum number of Parallel evidence results per round, or Keenable results per query (default `4`). For Keenable a round can therefore carry up to `max_queries_per_turn × search_max_num_results` results: 16 with the defaults, up to about 97k characters of evidence. |
| `env.search_mode: specstream` | Opt in to SpecStream's web search API. Requires `openai_chat` or `qwen_chat` and `SPECSTREAM_API_KEY`; no extra needed. |
| `env.search_timeout_seconds` | Whole MCP discovery/search deadline in seconds (default `20`); for `keenable` and `specstream`, the deadline for all queries of one round. |
| `env.search_max_num_results` | Maximum number of Parallel evidence results per round, or Keenable or SpecStream results per query (default `4`; at most `50` for SpecStream). For Keenable and SpecStream a round can therefore carry up to `max_queries_per_turn × search_max_num_results` results: 16 with the defaults, up to about 97k characters of evidence. |
| `env.max_queries_per_turn` / `env.max_tool_turns` | Bound model-requested queries and model rounds. |

#### Parallel Search MCP (opt-in)
Expand Down Expand Up @@ -293,6 +294,44 @@ source-page context is included when that corpus is available. This mode
changes the evidence source, so its scores are not directly comparable to,
and are not a reproduction of, the paper's Google-backed search setting.

#### SpecStream search (opt-in)

[SpecStream](https://specstream.ai/docs) web search is never selected
automatically, by default or by `auto`. It is used only when you set
`env.search_mode=specstream` explicitly, for example with
`--cfg-options env.search_mode=specstream`, and it needs `SPECSTREAM_API_KEY`;
selecting the mode without that variable fails the rollout before the first
model call and before any request. It calls a plain HTTPS JSON API through the
core `httpx` dependency, so it needs no extra. SkillOpt bundles no SpecStream
API key, credential or account; if you enable this mode, you use the service
under SpecStream's own terms.

**Data boundary.** When this mode is selected, each search round sends each
query from the model's generated `<search_queries>` to
`https://api.specstream.ai/v1/web-search`, one HTTPS `POST` per query. A
request carries exactly:

- a JSON body with the query text as `q`, `env.search_max_num_results` as
`num`, and `"speed": "fast"`;
- your `SPECSTREAM_API_KEY`, in an `Authorization: Bearer` header;
- SkillOpt's `User-Agent` (`SkillOpt/<version> (+https://github.com/microsoft/SkillOpt)`)
and httpx's standard transport headers.

SkillOpt does not send the task question, the OfficeQA corpus or any other
credential as such. A generated query is model output, though, so it can
repeat text from the question, from the provided document context or from the
skill. Redirects are not followed, so the key and the queries go only to that
endpoint. Each request is billed to the key's account at the `fast` search
rate listed in SpecStream's documentation. Rate-limit, credit and other
service errors fail the rollout with a search diagnostic that carries the
service's error message, with the key redacted; an explicit provider never
silently falls back to another one.

SpecStream search does not require a local OfficeQA document corpus; parsed
source-page context is included when that corpus is available. This mode
changes the evidence source, so its scores are not directly comparable to,
and are not a reproduction of, the paper's Google-backed search setting.

## Credential Environment Variables

### Azure-family backend
Expand Down
20 changes: 16 additions & 4 deletions skillopt/envs/officeqa/rollout.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

from skillopt.envs.officeqa.evaluator import evaluate
from skillopt.envs.officeqa.keenable_search import keenable_search
from skillopt.envs.officeqa.specstream_search import API_KEY_ENV as SPECSTREAM_API_KEY_ENV
from skillopt.envs.officeqa.specstream_search import specstream_search
from skillopt.envs.officeqa.tool_runtime import (
build_oracle_parsed_pages_context,
custom_search,
Expand Down Expand Up @@ -74,6 +76,7 @@
_AZURE_SEARCH_MODE = "azure_search"
_PARALLEL_SEARCH_MODE = "parallel"
_KEENABLE_SEARCH_MODE = "keenable"
_SPECSTREAM_SEARCH_MODE = "specstream"
def _normalize_search_mode(search_mode: str | None) -> str:
normalized = str(search_mode or _DEFAULT_SEARCH_MODE).strip().lower()
if normalized in {"custom", _CUSTOM_SEARCH_MODE}:
Expand All @@ -84,6 +87,8 @@ def _normalize_search_mode(search_mode: str | None) -> str:
return _PARALLEL_SEARCH_MODE
if normalized == _KEENABLE_SEARCH_MODE:
return _KEENABLE_SEARCH_MODE
if normalized == _SPECSTREAM_SEARCH_MODE:
return _SPECSTREAM_SEARCH_MODE
return _DEFAULT_SEARCH_MODE
def _load_parallel_search():
"""Import the Parallel client only when `parallel` mode is actually selected.
Expand Down Expand Up @@ -119,7 +124,7 @@ def _build_system(
"answer inside <answer>...</answer>.\n\n"
+ skill_section
).rstrip()
if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE}:
if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE, _SPECSTREAM_SEARCH_MODE}:
protocol = (
"You are an expert OfficeQA research assistant. Solve the question using the provided oracle parsed "
"OfficeQA page(s) and evidence returned by the controller-managed custom search loop.\n\n"
Expand Down Expand Up @@ -193,7 +198,7 @@ def _build_user(
parts.append("## File Hints\n" + "\n".join(f"- {hint}" for hint in item["source_files"]))
if diagnostic_mode and diagnostic_instruction.strip():
parts.append(f"## Training Readout\n{diagnostic_instruction.strip()}")
if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE}:
if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE, _SPECSTREAM_SEARCH_MODE}:
parts.append(
_build_round_instruction(
turn=turn,
Expand Down Expand Up @@ -384,6 +389,8 @@ def _run_custom_search_process(
raise ValueError("custom_search mode requires a non-empty search_api_url")
if search_mode == _CUSTOM_SEARCH_MODE and not os.environ.get(search_auth_env, "").strip():
raise ValueError(f"custom_search mode requires auth token env var {search_auth_env}")
if search_mode == _SPECSTREAM_SEARCH_MODE and not os.environ.get(SPECSTREAM_API_KEY_ENV, "").strip():
raise ValueError(f"specstream mode requires the {SPECSTREAM_API_KEY_ENV} environment variable")
if get_target_backend() not in {"openai_chat", "qwen_chat"}:
raise ValueError(f"{search_mode} mode is only supported with target_backend='openai_chat' or 'qwen_chat'")
system = _build_system(
Expand Down Expand Up @@ -450,6 +457,11 @@ def _run_custom_search_process(
results_text = keenable_search(
queries, max_num_results=search_max_num_results, timeout=search_timeout_seconds,
)
elif search_mode == _SPECSTREAM_SEARCH_MODE:
# Same rule as Parallel: a failed explicit provider stays an error.
results_text = specstream_search(
queries, max_num_results=search_max_num_results, timeout=search_timeout_seconds,
)
else:
results_text = _execute_custom_search_round(
queries,
Expand Down Expand Up @@ -590,7 +602,7 @@ def process_one(
else "Treat it as primary document evidence for answering the question."
),
)
elif normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE}:
elif normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE, _SPECSTREAM_SEARCH_MODE}:
try:
docs_roots = resolve_docs_roots(data_dirs)
except FileNotFoundError:
Expand Down Expand Up @@ -629,7 +641,7 @@ def process_one(
last_response_metadata: dict = {}
allowed_files = [os.path.basename(path) for path in candidate_files]
try:
if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE}:
if normalized_search_mode in {_CUSTOM_SEARCH_MODE, _PARALLEL_SEARCH_MODE, _KEENABLE_SEARCH_MODE, _SPECSTREAM_SEARCH_MODE}:
system, user, final_response, final_answer, conversation, fail_reason, last_response_metadata = _run_custom_search_process(
item,
skill_content,
Expand Down
112 changes: 112 additions & 0 deletions skillopt/envs/officeqa/specstream_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"""SpecStream web search client for the OfficeQA controller's search rounds.

Reached only through the explicit `search_mode=specstream` selection, and only
with `SPECSTREAM_API_KEY` set. Every call sends each of the model's generated
queries, and nothing else from the task, to SpecStream's web search API.
"""
from __future__ import annotations

import os
import time
from urllib.parse import urlsplit

import httpx

from skillopt import __version__

SEARCH_URL = "https://api.specstream.ai/v1/web-search"
API_KEY_ENV = "SPECSTREAM_API_KEY"
USER_AGENT = f"SkillOpt/{__version__} (+https://github.com/microsoft/SkillOpt)"
# `fast` is the lower-cost search tier.
SPEED = "fast"
MAX_RESULTS_LIMIT = 50


def _render(index: int, query: str, sources: list, max_num_results: int) -> str:
blocks = []
for item in sources:
if len(blocks) >= max_num_results:
break
if not isinstance(item, dict):
raise RuntimeError("SpecStream search returned an invalid source item")
url = item.get("url")
if url is None or url == "":
continue
if not isinstance(url, str) or urlsplit(url).scheme not in {"http", "https"} or not urlsplit(url).netloc:
raise RuntimeError("SpecStream search returned an invalid source URL")
snippet = item.get("snippet") or ""
if not isinstance(snippet, str):
raise RuntimeError("SpecStream search returned an invalid snippet")
if not snippet.strip():
highlights = item.get("highlights") or []
if not isinstance(highlights, list):
raise RuntimeError("SpecStream search returned invalid highlights")
snippet = " ".join(text.strip() for text in highlights if isinstance(text, str) and text.strip())
title = item.get("title")
if not isinstance(title, str) or not title.strip():
title = url
published = item.get("published")
dated = f"Published: {published.strip()}\n" if isinstance(published, str) and published.strip() else ""
blocks.append(f"[{len(blocks) + 1}] {title.strip()}\nURL: {url}\n{dated}{snippet.strip()[:6000]}")
body = "\n\n".join(blocks) if blocks else "[no search results]"
return f"## Query {index}\nQuery: {query}\n\n{body}"


def _error_detail(response: httpx.Response) -> str:
"""Prefer the API's `error.message`; fall back to the raw body text."""
try:
payload = response.json()
except ValueError:
return response.text
error = payload.get("error") if isinstance(payload, dict) else None
message = error.get("message") if isinstance(error, dict) else None
return message if isinstance(message, str) and message.strip() else response.text


def specstream_search(queries: list[str], *, max_num_results: int = 4, timeout: float = 20) -> str:
"""Search each query within one round deadline and render URL evidence.

Requires `SPECSTREAM_API_KEY`. Service errors propagate to the controller;
an exceeded deadline always raises the built-in `TimeoutError`.
"""
if not queries or any(not isinstance(query, str) or not query.strip() for query in queries):
raise ValueError("SpecStream search requires non-empty queries")
if timeout <= 0 or not 1 <= max_num_results <= MAX_RESULTS_LIMIT:
raise ValueError(f"SpecStream search needs a positive timeout and 1-{MAX_RESULTS_LIMIT} results")
api_key = os.environ.get(API_KEY_ENV, "").strip()
if not api_key:
raise ValueError(f"specstream mode requires the {API_KEY_ENV} environment variable")
headers = {"User-Agent": USER_AGENT, "Authorization": f"Bearer {api_key}"}
deadline = time.monotonic() + timeout
sections = []
# Redirects are not followed, so the key and the queries only ever go to SEARCH_URL.
with httpx.Client(headers=headers, follow_redirects=False) as client:
for index, query in enumerate(queries, start=1):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError(f"SpecStream search exceeded its {timeout}s deadline")
try:
response = client.post(
SEARCH_URL, json={"q": query, "num": max_num_results, "speed": SPEED}, timeout=remaining,
)
except httpx.TimeoutException as exc:
raise TimeoutError(f"SpecStream search exceeded its {timeout}s deadline") from exc
# httpx applies `timeout` per phase, so a slow response can still end
# past the round deadline; check it again once the response is in.
if time.monotonic() > deadline:
raise TimeoutError(f"SpecStream search exceeded its {timeout}s deadline")
if response.status_code != 200:
# The error text reaches fail_reason, results.jsonl and the
# reflection prompt. Redact before cutting, so a key straddling
# the cut can't leak a prefix.
detail = _error_detail(response).replace(api_key, "[redacted]")
raise RuntimeError(f"SpecStream search HTTP {response.status_code}: {detail[:1000]}")
try:
payload = response.json()
except ValueError as exc:
raise RuntimeError("SpecStream search returned invalid JSON") from exc
data = payload.get("data") if isinstance(payload, dict) else None
if not isinstance(data, dict) or not isinstance(data.get("sources"), list):
raise RuntimeError("SpecStream search returned invalid results")
sections.append(_render(index, query, data["sources"], max_num_results))
return "\n\n".join(sections)
Loading