Skip to content

Commit dc6871d

Browse files
committed
Add provider extra_body passthrough
1 parent c688118 commit dc6871d

18 files changed

Lines changed: 264 additions & 50 deletions

‎README.md‎

Lines changed: 67 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ If you are new to the project, the recommended reading order is:
8686

8787
## 📰 News
8888

89+
🚩 **Update** (2026-06-06) Provider-specific OpenAI-compatible request options can now be passed consistently across Python import mode, CLI, and API server mode through a validated `extra_body` object.
90+
8991
🚩 **Update** (2026-06-06) Runtime configuration names are now consolidated, the duplicate LLM-call loop limit has been removed, and the default long-run profile now uses `MAX_ROUNDS=500`, `MAX_RUNTIME_SECONDS=10800`, `TIMEOUT_SECONDS=1200`, `MAX_INPUT_TOKENS=128000`, and `COMPACT_TRIGGER_TOKENS=96k`.
9092

9193
🚩 **Update** (2026-05-22) Added a real API smoke test that runs the five SGI benchmark README server commands and OpenAI SDK examples, then validates each expected final-answer format.
@@ -96,11 +98,11 @@ If you are new to the project, the recommended reading order is:
9698

9799
🚩 **Update** (2026-05-21) The Python import API now exposes the same core runtime controls as CLI mode: default workspace, role prompt strings/files, image inputs, explicit tool sets, optional extra tools, and decorated custom function tools.
98100

99-
🚩 **Update** (2026-05-20) Tool calls now use single-request semantics, and the ReAct runtime can execute adjacent read-only tool calls concurrently. For example, `Read, Read, Edit, Read` runs as `[Read + Read]`, then `[Edit]`, then `[Read]`, preserving mutation boundaries while improving retrieval throughput.
100-
101101
<details>
102102
<summary>👉 More News (Click to expand)</summary>
103103

104+
🚩 **Update** (2026-05-20) Tool calls now use single-request semantics, and the ReAct runtime can execute adjacent read-only tool calls concurrently. For example, `Read, Read, Edit, Read` runs as `[Read + Read]`, then `[Edit]`, then `[Read]`, preserving mutation boundaries while improving retrieval throughput.
105+
104106
🚩 **Update** (2026-05-19) `WebFetch` now exposes a single-string `url` schema for broader provider compatibility, including Gemini tool declarations. Fetch multiple pages with multiple `WebFetch` calls.
105107

106108
🚩 **Update** (2026-05-14) ResearchHarness now supports optional extra tools that are not loaded into the default tool set. The first one is `str_replace_editor`, a text editing compatibility tool enabled explicitly with `--extra-tool str_replace_editor`.
@@ -394,16 +396,17 @@ Details:
394396
arguments win for that agent instance. This includes `api_key`, `api_base`,
395397
`model_name`, `timeout_seconds`, `max_input_tokens`, `max_output_tokens`,
396398
`max_retries`, `temperature`, `top_p`, `presence_penalty`,
397-
`compact_trigger_tokens`, `max_rounds`, and
399+
`compact_trigger_tokens`, provider-specific `extra_body`, `max_rounds`, and
398400
`max_runtime_seconds`.
399401
- Environment variables for these runtime settings use the upper-case form of
400402
the Python argument name, for example `max_rounds` -> `MAX_ROUNDS` and
401403
`compact_trigger_tokens` -> `COMPACT_TRIGGER_TOKENS`.
402404
- If a setting exists both as a command-line argument and an environment-level
403405
default, the command-line argument wins for that run. For example,
404406
`--workspace-root` overrides `WORKSPACE_ROOT`.
405-
- In API server mode, request-local options such as `model` and
406-
`extra_body["workspace-root"]` override server defaults only for that request.
407+
- In API server mode, request-local options such as `model`,
408+
`extra_body["workspace-root"]`, and `extra_body["llm-extra-body"]` override
409+
server defaults only for that request.
407410
- Process environment variables already exported in the shell are not
408411
overwritten by `.env`.
409412
- `.env` fills missing environment variables only; it is a convenient local
@@ -427,6 +430,29 @@ Details:
427430
`.env` in CLI mode. Use the Python API when these need to be set
428431
programmatically per agent.
429432

433+
### Provider-Specific Extra Body
434+
435+
Some OpenAI-compatible providers expose request fields that are not part of the
436+
standard OpenAI SDK surface, such as model-specific thinking switches.
437+
ResearchHarness supports these fields through a single provider-specific
438+
`extra_body` object and forwards it unchanged to the underlying OpenAI SDK call.
439+
ResearchHarness does not interpret these keys and does not hard-code provider
440+
names or fields.
441+
442+
Use the same JSON object across modes:
443+
444+
| Mode | How to pass it |
445+
|---|---|
446+
| Python import | `create_agent(..., extra_body={"enable_thinking": False})` |
447+
| CLI | `--llm-extra-body-json '{"enable_thinking": false}'` |
448+
| OpenAI-compatible API server | OpenAI SDK `extra_body={"llm-extra-body": {"enable_thinking": false}}` |
449+
450+
The value must be a JSON object / Python dictionary. Invalid values are rejected
451+
before the agent run starts. If the upstream provider does not support a field,
452+
the provider may reject the request. Provider thinking / reasoning modes may
453+
consume extra output budget, so raise `MAX_OUTPUT_TOKENS` or
454+
`max_output_tokens` when enabling them.
455+
430456
### Extending the Base Agent
431457

432458
The harness keeps the base system prompt focused on tool calling, local
@@ -500,6 +526,19 @@ Each `--images` path must exist. ResearchHarness copies every image into
500526
part, and includes each saved relative path in the user text so later rounds can
501527
recover images with `ReadImage`.
502528

529+
Pass provider-specific OpenAI-compatible request options when a backend exposes
530+
extra request fields:
531+
532+
```bash
533+
python3 run_agent.py "your prompt" \
534+
--llm-extra-body-json '{"enable_thinking": false}'
535+
```
536+
537+
ResearchHarness forwards this JSON object as the OpenAI SDK `extra_body`. It is
538+
not interpreted by ResearchHarness and should only contain fields supported by
539+
your model provider. Thinking / reasoning modes can require a larger output
540+
token budget than non-thinking calls.
541+
503542
In an interactive terminal, the CLI stays open after the final answer and asks
504543
for a follow-up prompt. The next run keeps the previous message history,
505544
including tool results and saved image path hints, so the agent can continue the
@@ -545,6 +584,7 @@ agent = create_agent(
545584
max_input_tokens=131072,
546585
max_output_tokens=4096,
547586
compact_trigger_tokens="96k",
587+
extra_body={"enable_thinking": False},
548588
)
549589

550590
answer = agent.run(
@@ -561,7 +601,9 @@ Runtime parameters passed to `create_agent(...)` or `run_agent(...)` override
561601
environment variables for that agent only. Use `max_input_tokens` to match the
562602
serving engine's context window, `max_output_tokens` to reserve response space,
563603
and `compact_trigger_tokens` to compact before the model server rejects an
564-
overlong request.
604+
overlong request. Use `extra_body={...}` only for provider-specific
605+
OpenAI-compatible request fields; ResearchHarness validates that it is a
606+
dictionary and forwards it unchanged.
565607

566608
`role_prompt` is for an inline prompt block. `role_prompt_files=[...]` accepts
567609
one or more files and appends them in order, matching the repeatable CLI
@@ -786,6 +828,25 @@ API request; it does not mutate environment variables and does not affect other
786828
concurrent requests. The agent run, enabled wrappers, and compaction all use the
787829
same selected backend model.
788830

831+
### API Provider Extra Body
832+
833+
Some OpenAI-compatible providers expose additional request fields. Pass them in
834+
the request-local `llm-extra-body` object:
835+
836+
```python
837+
response = client.chat.completions.create(
838+
model="RH--Qwen/Qwen3.5-9B",
839+
messages=[{"role": "user", "content": "Answer briefly."}],
840+
extra_body={"llm-extra-body": {"enable_thinking": False}},
841+
)
842+
```
843+
844+
ResearchHarness validates that `llm-extra-body` is a JSON object and forwards it
845+
unchanged as the OpenAI SDK `extra_body` for the underlying model call. The
846+
field is request-local and does not affect other concurrent API requests. If a
847+
provider's thinking / reasoning mode is enabled, reserve enough completion
848+
tokens for that mode.
849+
789850
### API Workspace Root
790851

791852
By default, each API request uses its own isolated `agent_workspace/` under

‎VERSION‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
v0.0.46
1+
v0.0.47

‎agent_base/react_agent.py‎

Lines changed: 48 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -630,9 +630,11 @@ def image_context_trace_text(result: Any) -> str:
630630
return text
631631

632632

633-
def default_llm_config(model_name: Optional[str] = None) -> dict:
633+
def default_llm_config(model_name: Optional[str] = None, extra_body: Optional[dict[str, Any]] = None) -> dict:
634634
selected_model = str(model_name or "").strip() or default_model_name()
635-
return {
635+
if extra_body is not None and not isinstance(extra_body, dict):
636+
raise ValueError("extra_body must be a dict.")
637+
config = {
636638
"model": selected_model,
637639
"api_key": os.environ.get("API_KEY", "EMPTY"),
638640
"api_base": os.environ.get("API_BASE"),
@@ -646,6 +648,9 @@ def default_llm_config(model_name: Optional[str] = None) -> dict:
646648
"presence_penalty": float(os.environ.get("PRESENCE_PENALTY", str(DEFAULT_PRESENCE_PENALTY))),
647649
},
648650
}
651+
if extra_body:
652+
config["extra_body"] = dict(extra_body)
653+
return config
649654

650655

651656
def execute_tool_by_name(tool_map: dict[str, Any], tool_name: str, tool_args: Any, **kwargs):
@@ -727,6 +732,13 @@ def __init__(
727732
raise ValueError('llm["model"] must be a non-empty string.')
728733
if "generate_cfg" not in llm or not isinstance(llm["generate_cfg"], dict):
729734
raise ValueError('llm["generate_cfg"] must be a dict.')
735+
llm_extra_body = llm.get("extra_body")
736+
if llm_extra_body is None:
737+
self.llm_extra_body: dict[str, Any] = {}
738+
elif isinstance(llm_extra_body, dict):
739+
self.llm_extra_body = dict(llm_extra_body)
740+
else:
741+
raise ValueError('llm["extra_body"] must be a dict.')
730742

731743
self.tool_map = {tool_name: tool_registry[tool_name] for tool_name in requested_tools}
732744
self.tool_names = list(self.tool_map.keys())
@@ -818,6 +830,8 @@ def _call_chat_completion(
818830
else self.llm_generate_cfg.get("presence_penalty", 1.1)
819831
),
820832
)
833+
if self.llm_extra_body:
834+
request_kwargs["extra_body"] = dict(self.llm_extra_body)
821835
if include_native_tools and self._native_tools:
822836
request_kwargs["tools"] = self._native_tools
823837
request_kwargs["tool_choice"] = "auto"
@@ -1477,7 +1491,20 @@ def resolve_agent_class_for_role_prompt_files(role_prompt_files: Sequence[str])
14771491
return MultiTurnReactAgent
14781492

14791493

1480-
def _parse_cli_args(argv: list[str]) -> tuple[str, Optional[str], Optional[str], str, list[str], list[str], Optional[bool], list[str], list[str]]:
1494+
def _parse_cli_args(
1495+
argv: list[str],
1496+
) -> tuple[
1497+
str,
1498+
Optional[str],
1499+
Optional[str],
1500+
str,
1501+
list[str],
1502+
list[str],
1503+
Optional[bool],
1504+
list[str],
1505+
list[str],
1506+
dict[str, Any],
1507+
]:
14811508
parser = argparse.ArgumentParser(description="Run the local agent directly from agent_base.react_agent.")
14821509
parser.add_argument("prompt", nargs="*", help="Prompt text.")
14831510
parser.add_argument("--prompt-file", help="Optional UTF-8 text file containing the prompt.")
@@ -1525,9 +1552,24 @@ def _parse_cli_args(argv: list[str]) -> tuple[str, Optional[str], Optional[str],
15251552
metavar="NAME",
15261553
help="Expose an explicit complete tool set for this run. May be passed multiple times. Cannot be combined with --extra-tool.",
15271554
)
1555+
parser.add_argument(
1556+
"--llm-extra-body-json",
1557+
default="",
1558+
metavar="JSON",
1559+
help="Provider-specific OpenAI-compatible request extra_body JSON object.",
1560+
)
15281561
args = parser.parse_args(argv)
15291562
if args.tool_names and args.extra_tools:
15301563
raise ValueError("--tool defines the complete tool set and cannot be combined with --extra-tool.")
1564+
llm_extra_body: dict[str, Any] = {}
1565+
if str(args.llm_extra_body_json).strip():
1566+
try:
1567+
parsed_extra_body = json.loads(str(args.llm_extra_body_json))
1568+
except json.JSONDecodeError as exc:
1569+
raise ValueError("--llm-extra-body-json must be a JSON object.") from exc
1570+
if not isinstance(parsed_extra_body, dict):
1571+
raise ValueError("--llm-extra-body-json must be a JSON object.")
1572+
llm_extra_body = parsed_extra_body
15311573

15321574
prompt_text = ""
15331575
if args.prompt_file:
@@ -1548,6 +1590,7 @@ def _parse_cli_args(argv: list[str]) -> tuple[str, Optional[str], Optional[str],
15481590
args.chat,
15491591
validate_named_tools(args.tool_names) if args.tool_names else [],
15501592
resolve_extra_tool_names(args.extra_tools),
1593+
llm_extra_body,
15511594
)
15521595

15531596

@@ -1565,6 +1608,7 @@ def main(argv: Optional[list[str]] = None) -> int:
15651608
chat_arg,
15661609
tool_names,
15671610
extra_tools,
1611+
llm_extra_body,
15681612
) = _parse_cli_args(argv or sys.argv[1:])
15691613
agent_cls = resolve_agent_class_for_role_prompt_files(role_prompt_files)
15701614
forbidden_tools = set(getattr(agent_cls, "forbidden_tool_names", set()))
@@ -1580,7 +1624,7 @@ def main(argv: Optional[list[str]] = None) -> int:
15801624
if extra_tools
15811625
else None
15821626
),
1583-
llm=default_llm_config(),
1627+
llm=default_llm_config(extra_body=llm_extra_body),
15841628
trace_dir=trace_dir,
15851629
role_prompt=role_prompt or None,
15861630
)

‎api/openai_server.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
"workspace_dir",
5151
"workspace",
5252
)
53+
REQUEST_LLM_EXTRA_BODY_FIELD = "llm-extra-body"
5354

5455
INPUT_WRAPPER_SYSTEM_PROMPT = """You are the ResearchHarness input wrapper.
5556
@@ -419,6 +420,15 @@ def request_parameter_warnings(payload: dict[str, Any]) -> list[dict[str, str]]:
419420
return warnings
420421

421422

423+
def request_llm_extra_body(payload: dict[str, Any]) -> dict[str, Any]:
424+
raw_value = payload.get(REQUEST_LLM_EXTRA_BODY_FIELD)
425+
if raw_value is None:
426+
return {}
427+
if not isinstance(raw_value, dict):
428+
raise OpenAICompatError(400, f"{REQUEST_LLM_EXTRA_BODY_FIELD} must be a JSON object.")
429+
return dict(raw_value)
430+
431+
422432
def resolve_request_workspace_root(payload: dict[str, Any], default_workspace_root: Path) -> tuple[Path, dict[str, Any]]:
423433
for alias in REQUEST_WORKSPACE_ROOT_ALIAS_FIELDS:
424434
if alias in payload:
@@ -471,6 +481,7 @@ def run_chat_completion(payload: dict[str, Any], config: ServerConfig) -> dict[s
471481
payload = validate_chat_payload(payload)
472482
requested_model_label, backend_model = resolve_api_model_selection(str(payload.get("model") or API_MODEL_ALIAS))
473483
payload["model"] = requested_model_label
484+
llm_extra_body = request_llm_extra_body(payload)
474485
request_id = "chatcmpl_" + uuid4().hex
475486
run_id = "run_" + datetime.datetime.now().astimezone().strftime("%Y%m%d_%H%M%S") + "_" + uuid4().hex[:8]
476487
run_root = config.api_runs_dir / run_id
@@ -491,7 +502,7 @@ def run_chat_completion(payload: dict[str, Any], config: ServerConfig) -> dict[s
491502
payload["messages"],
492503
agent_workspace,
493504
)
494-
llm_config = default_llm_config(model_name=backend_model)
505+
llm_config = default_llm_config(model_name=backend_model, extra_body=llm_extra_body)
495506
backend_model = str(llm_config.get("model", ""))
496507
append_api_event(
497508
trace_dir,

‎docs/tutorial_en.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,13 +138,25 @@ In Python import mode, `create_agent(...)` and `run_agent(...)` can override
138138
model/runtime settings for one agent instance, including `api_key`, `api_base`,
139139
`model_name`, `timeout_seconds`, `max_input_tokens`, `max_output_tokens`,
140140
`max_retries`, `temperature`, `top_p`, `presence_penalty`,
141-
`compact_trigger_tokens`, `max_rounds`, and
141+
`compact_trigger_tokens`, provider-specific `extra_body`, `max_rounds`, and
142142
`max_runtime_seconds`. Environment variables for these runtime settings use the
143143
upper-case form of the Python argument name, such as `MAX_ROUNDS`,
144144
`TIMEOUT_SECONDS`, `MAX_OUTPUT_TOKENS`, and `COMPACT_TRIGGER_TOKENS`. In CLI
145145
mode, model and sampling options stay compact and come from process environment
146146
variables or `.env`.
147147

148+
Provider-specific OpenAI-compatible fields use a single `extra_body` object.
149+
ResearchHarness validates that it is an object and forwards it unchanged to the
150+
underlying OpenAI SDK request. It does not interpret provider-specific keys.
151+
Thinking / reasoning provider modes can consume extra output budget, so raise
152+
`MAX_OUTPUT_TOKENS` or `max_output_tokens` when enabling them.
153+
154+
| Mode | How to pass provider-specific `extra_body` |
155+
| --- | --- |
156+
| Python import | `create_agent(..., extra_body={"enable_thinking": False})` |
157+
| CLI | `--llm-extra-body-json '{"enable_thinking": false}'` |
158+
| API server | OpenAI SDK `extra_body={"llm-extra-body": {"enable_thinking": false}}` |
159+
148160
Before real use, run:
149161

150162
```bash
@@ -244,6 +256,7 @@ agent = create_agent(
244256
max_input_tokens=131072,
245257
max_output_tokens=4096,
246258
compact_trigger_tokens="96k",
259+
extra_body={"enable_thinking": False},
247260
)
248261

249262
answer = agent.run(
@@ -554,6 +567,7 @@ Supported request fields:
554567
| `max_tokens` | no | Compatibility alias for `max_completion_tokens`; accepted with an API trace warning. |
555568
| `response_format` | no | Passed to the wrappers as an output-format hint. |
556569
| `workspace-root` | no | Absolute path to an existing workspace directory for this request. If missing or invalid, the default per-request `agent_workspace/` is used. |
570+
| `llm-extra-body` | no | Provider-specific JSON object forwarded unchanged as the underlying OpenAI SDK `extra_body` for this request. |
557571

558572
Supported message roles:
559573

‎docs/tutorial_zh.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,11 +135,23 @@ pip install -e . --no-deps
135135
agent 实例覆盖模型和运行时设置,包括 `api_key`、`api_base`、`model_name`、
136136
`timeout_seconds`、`max_input_tokens`、`max_output_tokens`、`max_retries`、
137137
`temperature`、`top_p`、`presence_penalty`、`compact_trigger_tokens`、
138-
`max_rounds` 和 `max_runtime_seconds`。这些运行时设置的环境变量使用
138+
provider-specific `extra_body`、`max_rounds` 和 `max_runtime_seconds`。这些运行时设置的环境变量使用
139139
Python 参数名的大写形式,例如 `MAX_ROUNDS`、`TIMEOUT_SECONDS`、
140140
`MAX_OUTPUT_TOKENS` 和 `COMPACT_TRIGGER_TOKENS`。CLI 模式保持命令行
141141
简洁,模型和采样设置主要来自进程环境变量或 `.env`。
142142

143+
provider-specific OpenAI-compatible 字段统一通过 `extra_body` object 传入。
144+
ResearchHarness 只校验它是 object,并原样转发给底层 OpenAI SDK request;
145+
不会解释 provider-specific key,也不会写死某个 provider 的字段。
146+
如果启用 provider 的 thinking / reasoning 类模式,需要为输出预留更多
147+
token 预算,例如调高 `MAX_OUTPUT_TOKENS` 或 `max_output_tokens`。
148+
149+
| 模式 | 如何传 provider-specific `extra_body` |
150+
| --- | --- |
151+
| Python 直接导入 | `create_agent(..., extra_body={"enable_thinking": False})` |
152+
| CLI | `--llm-extra-body-json '{"enable_thinking": false}'` |
153+
| API server | OpenAI SDK `extra_body={"llm-extra-body": {"enable_thinking": false}}` |
154+
143155
正式使用前,先运行:
144156

145157
```bash
@@ -232,6 +244,7 @@ agent = create_agent(
232244
max_input_tokens=131072,
233245
max_output_tokens=4096,
234246
compact_trigger_tokens="96k",
247+
extra_body={"enable_thinking": False},
235248
)
236249

237250
answer = agent.run(
@@ -520,6 +533,7 @@ agent loop 和 compaction,并且只对这个请求生效。
520533
| `max_tokens` | 否 | `max_completion_tokens` 的兼容别名;接受但会写入 API trace warning。 |
521534
| `response_format` | 否 | 作为输出格式提示传给 wrapper。 |
522535
| `workspace-root` | 否 | 本次请求使用的 workspace 绝对路径。只有指向已存在目录时才使用;缺失或无效时回退到默认 per-request `agent_workspace/`。 |
536+
| `llm-extra-body` | 否 | provider-specific JSON object,会在本次请求中原样转发为底层 OpenAI SDK `extra_body`。 |
523537

524538
支持的 message role:
525539

0 commit comments

Comments
 (0)