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
11 changes: 9 additions & 2 deletions src/bub/builtin/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ class CustomProvider(BaseModel):
type: str
api_key: str | None = None
api_base: str | None = None
headers: dict[str, str] = Field(default_factory=dict)

@field_validator("type")
@classmethod
Expand Down Expand Up @@ -161,8 +162,14 @@ def model_client_kwargs(self, provider: str) -> dict[str, Any]:
custom = self.providers.get(provider)
provider = provider if custom else provider.lower()
options = dict(self.client_args)
# Headers from client_args, including a User-Agent, take precedence.
options["headers"] = {"User-Agent": USER_AGENT, **(options.get("headers") or {})}
headers = {"user-agent": ("User-Agent", USER_AGENT)}
for overrides in (options.get("headers") or {}, custom.headers if custom else {}):
for name, value in overrides.items():
key = name.lower()
# Keep the first spelling, in particular Republic's expected "User-Agent".
original_name = headers[key][0] if key in headers else name
headers[key] = (original_name, value)
options["headers"] = dict(headers.values())
prefix = _provider_env_name(provider)
options.setdefault("env_prefix", f"BUB_{prefix}")
return {
Expand Down
49 changes: 49 additions & 0 deletions tests/test_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,55 @@ async def test_client_options_resolve_provider_names(
assert provider_transport.requests[0].headers["authorization"] == "Bearer environment-key"


@pytest.mark.asyncio
async def test_provider_headers_are_scoped_and_override_global_headers(
load_config, tmp_path: Path, provider_transport: ProviderService
) -> None:
load_config(
"""
api_key:
openrouter: sk-openrouter
openai: sk-openai
other: sk-other
client_args:
api_format: chat
headers:
user-agent: GlobalAgent
X-Shared: global
X-Common: kept
providers:
openrouter:
type: openrouter
headers:
HTTP-Referer: https://example.com
X-OpenRouter-Title: Example App
x-shared: scoped
USER-AGENT: ScopedAgent
other:
type: openrouter
""".strip(),
)
settings = load_settings()
for provider in ("openrouter", "openai", "other"):
provider_transport.reply_chat()
settings.model = f"{provider}:model"
assert await _run(settings, tmp_path) == "done"

attributed, *unrelated = (request.headers for request in provider_transport.requests)
assert attributed["http-referer"] == "https://example.com"
assert attributed["x-openrouter-title"] == "Example App"
assert attributed.get_list("x-shared") == ["scoped"]
assert attributed.get_list("user-agent") == ["ScopedAgent"]
assert attributed["x-common"] == "kept"
assert attributed["authorization"] == "Bearer sk-openrouter"
for headers in unrelated:
assert "http-referer" not in headers
assert "x-openrouter-title" not in headers
assert headers.get_list("x-shared") == ["global"]
assert headers.get_list("user-agent") == ["GlobalAgent"]
assert headers["x-common"] == "kept"


@pytest.mark.asyncio
@pytest.mark.parametrize(
"provider,header", [("google", "x-goog-api-key"), ("azure-openai", "api-key"), ("openrouter", "authorization")]
Expand Down
14 changes: 13 additions & 1 deletion website/src/content/docs/docs/reference/settings.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ Common `client_args` keys:

| Key | Description |
| --- | --- |
| `headers` | Merged with the default `User-Agent: bub/<version>` header (explicit headers win) |
| `headers` | Shared by all providers. Overrides the default `User-Agent: bub/<version>`; [provider-specific headers](#custom-providers) take precedence. |
| `api_format` | Set to `"chat"` for OpenAI-compatible `/v1/chat/completions` endpoints |
| `timeout` / `max_retries` | HTTP client request timeout and retry count (overall call timeout is controlled by `model_timeout_seconds`) |

Expand Down Expand Up @@ -189,6 +189,18 @@ providers:
| `type` | Yes | Underlying Republic provider protocol name (e.g. `openai`, `anthropic`) |
| `api_base` | No | Endpoint URL; falls back to `api_base` mapping or `BUB_<NAME>_API_BASE` |
| `api_key` | No | Endpoint API key; falls back to `api_key` mapping or `BUB_<NAME>_API_KEY` |
| `headers` | No | Request headers for this provider name only. Overrides matching `client_args.headers` and the default `User-Agent`, ignoring case. |

Set [OpenRouter app attribution](https://openrouter.ai/docs/app-attribution) for the `openrouter:` prefix:

```yaml
providers:
openrouter:
type: openrouter
headers:
HTTP-Referer: https://example.com
X-OpenRouter-Title: Example App
```

## ChannelSettings {#channel-settings}

Expand Down
14 changes: 13 additions & 1 deletion website/src/content/docs/zh-cn/docs/reference/settings.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ class AgentSettings(Settings):

| 键名 | 说明 |
| --- | --- |
| `headers` | 与默认 `User-Agent: bub/<version>` 合并(同名头显式传入优先) |
| `headers` | 所有提供商共用的请求头,可覆盖默认的 `User-Agent: bub/<version>`;[提供商专属请求头](#custom-providers)优先。 |
| `api_format` | 连接 OpenAI 兼容 `/v1/chat/completions` 端点时通常设为 `"chat"` |
| `timeout` / `max_retries` | 底层 HTTP 客户端的单次请求超时与重试次数(整次调用总时限由 `model_timeout_seconds` 控制) |

Expand Down Expand Up @@ -189,6 +189,18 @@ providers:
| `type` | 是 | 遵循的底层 Republic 提供商协议名(如 `openai`、`anthropic`) |
| `api_base` | 否 | 服务 URL;省略时回退读取 `api_base` 映射或 `BUB_<NAME>_API_BASE` |
| `api_key` | 否 | API Key;省略时回退读取 `api_key` 映射或 `BUB_<NAME>_API_KEY` |
| `headers` | 否 | 仅发送给此名称对应的提供商。覆盖 `client_args.headers` 中的同名请求头和默认的 `User-Agent`,匹配时不区分大小写。 |

为 `openrouter:` 前缀设置 [OpenRouter 应用归因](https://openrouter.ai/docs/app-attribution):

```yaml
providers:
openrouter:
type: openrouter
headers:
HTTP-Referer: https://example.com
X-OpenRouter-Title: Example App
```

## ChannelSettings {#channel-settings}

Expand Down
Loading