Skip to content

feat(provider): add request-time templates for custom headers - #11120

Open
piexian wants to merge 8 commits into
AstrBotDevs:masterfrom
piexian:feat/10535-provider-request-header-templates
Open

piexian wants to merge 8 commits into
AstrBotDevs:masterfrom
piexian:feat/10535-provider-request-header-templates

Conversation

@piexian

@piexian piexian commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Refs #10535

为提供商自定义请求头增加请求时变量模板,使中转站可以按请求接收会话 ID、UMO、请求 ID、模型等动态值,并通过 SHA-256 或 UUID v5 转换满足上游的标识格式要求,同时保持鉴权头和普通静态配置不变。

Modifications / 改动点

  • 在 headers.py 和 provider.py 中实现变量渲染,支持 {conversation_id}、{umo}、{request_id}、{model}、{provider_id}、{version},以及 {sha256:<模板>} 和 {uuid5:<模板>} 转换。

  • UUID v5 使用固定命名空间和转换前的原始值,同一输入始终生成相同的标准 UUID;缺少变量的请求头会被省略并记录 warning,鉴权头始终按配置原样发送。

  • 在 Agent Runner 中传递稳定的请求 ID、会话 ID 和真实事件 UMO,覆盖工具多轮、工具重查询、传输重试、换 Key 和 fallback Provider。

  • 为 OpenAI Chat Completions、OpenAI Responses、Anthropic 和 Gemini 的普通及流式请求接入请求级头;Kimi Code、MiniMax 和 Xiaomi Token Plan 通过现有继承链路获得支持。

  • Gemini 使用请求级 http_options,避免修改共享客户端;传输层按不区分大小写的名称去重 User-Agent 等 SDK 默认头。

  • 修正主动回复的 UMO 来源,不再把平台会话 ID 作为 session_id 传入。

  • 更新默认配置和四语 WebUI hint,保留原有用法说明并链接到文档;在 docs/zh/providers/llm.md 和 docs/en/providers/llm.md 中补充变量、SHA-256、UUID v5、示例、安全边界和故障排查说明。

  • 扩展现有单元、协议集成、真实 HTTP 和并发回归测试,覆盖 UUID 稳定性、原始值转换、缺值省略及请求级分类。

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果


Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。

  • 📚 I checked the affected WebUI instructions and screenshots in docs/zh and docs/en against the changed navigation, page structure, and labels, and updated them in this PR (or explained why no documentation update is needed). For renamed, moved, or merged entry points, I included an old entry → new entry mapping in the documentation and changelog.
    / 我已对照变化后的 WebUI 入口、页面结构和术语,核对并在本 PR 中更新 docs/zh 和 docs/en 的相关操作说明与截图(或说明无需更新文档的原因)。入口改名、移动或合并时,已在文档和 changelog 中补充 旧入口 → 新入口 对照。

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
    / 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到 requirements.txt 和 pyproject.toml 文件相应位置。

  • 😮 My changes do not introduce malicious code.
    / 我的更改没有引入恶意代码。

Summary by Sourcery

Enable request-time custom header templates across supported LLM providers while preserving existing static configuration and authentication behavior.

New Features:

  • Add request-time custom header templates with conversation, origin, request, model, provider, and version variables plus SHA-256 and UUID v5 transformations.
  • Propagate stable request metadata across agent rounds, retries, key rotation, fallback providers, and supported streaming and non-streaming provider requests.

Bug Fixes:

  • Prevent platform session IDs from being incorrectly passed as request session identifiers.
  • Prevent duplicate SDK headers caused by case differences and avoid mutating shared Gemini client headers during concurrent requests.

Enhancements:

  • Preserve static and authentication headers while omitting templates with unavailable values and warning about omissions.
  • Maintain compatibility with custom context compressors while forwarding request metadata to the built-in compressor.

Documentation:

  • Document custom header variables, deterministic transformations, encoding behavior, security considerations, examples, and troubleshooting guidance in English and Chinese provider documentation.
  • Update configuration and WebUI hints to link users to the custom header template documentation.

Tests:

  • Expand unit, provider integration, real HTTP, concurrency, and agent runner regression coverage for template rendering, metadata propagation, retries, fallbacks, header deduplication, and Gemini request isolation.

@sourcery-ai

sourcery-ai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit 6f04568

No linked issues found.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="astrbot/core/provider/headers.py" line_range="28-30" />
<code_context>
+)
+# Authentication headers carry API keys, which are never a template variable.
+# They are always sent exactly as configured.
+_FIXED_HEADERS = frozenset(
+    {"authorization", "proxy-authorization", "x-api-key", "api-key", "x-goog-api-key"}
+)
+
+
</code_context>
<issue_to_address>
**Configured credentials are altered**

When a provider uses `X-Auth-Token` and its credential contains a recognized placeholder or references a missing value, `split_provider_headers` treats `X-Auth-Token` as a template because it is absent from `_FIXED_HEADERS`, so `resolve_request_headers` substitutes request data or omits the header when a referenced value is empty; the provider receives a changed credential or authentication fails.

Add `x-auth-token` to `_FIXED_HEADERS` so the configured credential is sent as written.
</issue_to_address>

### Comment 2
<location path="astrbot/core/provider/headers.py" line_range="14" />
<code_context>
 DEFAULT_USER_AGENT = f"astrbot/{__version__}"
 CONVERSATION_ID_HEADER = "x-astrbot-conversation-id"

+_VARIABLES = "conversation_id|umo|request_id|model|provider_id|version"
+# Only known placeholders are replaced. Any other text, including other braces,
+# is sent exactly as configured.
</code_context>
<issue_to_address>
**Missing session_id template**

The issue's suggested context variables include `{session_id}`. The renderer does not recognize that variable or resolve it from the request, so a configured `{session_id}` remains literal rather than providing the session value.
</issue_to_address>

### Comment 3
<location path="astrbot/core/agent/runners/tool_loop_agent_runner.py" line_range="683" />
<code_context>
             "session_id": self.req.session_id,
+            "umo": self._umo,
+            "request_id": self._request_id,
             "conversation_id": (
                 self.req.conversation.cid if self.req.conversation else None
             ),
</code_context>
<issue_to_address>
**Compression requests lose run context**

When context compression invokes the LLM during an agent run, `LLMSummaryCompressor` calls its provider directly without the runner’s `request_id`, `umo`, or `conversation_id`, so headers rendered for a compression request get a fresh request ID and omit the run’s message origin and conversation ID.

Forward the run’s header context into compression-provider calls so they use the same request ID, UMO, and conversation ID.
</issue_to_address>

### Comment 4
<location path="tests/test_provider_header_templates.py" line_range="1-650" />
<code_context>
+import asyncio
</code_context>
<issue_to_address>
**Regression tests are added**

When the PR adds or extends the cited tests, the PR adds new regression tests and extends existing test cases despite the repository instruction not to generate test files, so these changes expand the test suite contrary to that guidance.

Remove the added test cases and test files to follow the repository guidance.

Also at `tests/unit/test_provider_headers.py:1-128`, `tests/test_anthropic_source.py:546-576`, `tests/test_gemini_source.py:353-401`, `tests/test_provider_user_agent.py:135-199`, `tests/test_tool_loop_agent_runner.py:2652-2762`, `tests/unit/test_group_chat_context_wiring.py:129-167`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and a configured {umo} template can put platform, group, or user identifiers into outbound provider headers. Reverting or removing the template stops future requests, but cannot undo identifiers already sent to a third party.

Blocking findings: astrbot/core/provider/headers.py:30, astrbot/core/provider/headers.py:14, astrbot/core/agent/runners/tool_loop_agent_runner.py:683


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread astrbot/core/provider/headers.py Resolved
Comment thread astrbot/core/provider/headers.py Resolved
Comment on lines +1 to +650
import asyncio
import hashlib
from types import SimpleNamespace

import httpx
import pytest
from anthropic.types import Message as AnthropicMessage
from google.genai import types as genai_types
from openai.types.chat.chat_completion import ChatCompletion
from openai.types.chat.chat_completion_chunk import ChatCompletionChunk
from openai.types.responses import Response as OpenAIResponse

import astrbot.core.provider.sources.request_retry as request_retry
from astrbot import __version__
from astrbot.core.provider.entities import LLMResponse
from astrbot.core.provider.sources.anthropic_source import ProviderAnthropic
from astrbot.core.provider.sources.gemini_source import ProviderGoogleGenAI
from astrbot.core.provider.sources.openai_responses_source import (
ProviderOpenAIResponses,
)
from astrbot.core.provider.sources.openai_source import ProviderOpenAIOfficial

UMO = "aiocqhttp:GroupMessage:100"
CUSTOM_HEADERS = {
"x-session": "{sha256:{conversation_id}}",
"x-umo": "{umo}",
"x-request": "{request_id}",
"x-model": "{model}",
"x-provider": "{provider_id}",
"x-version": "{version}",
"X-Astrbot-Conversation-Id": "spoofed",
}


def _expected_headers(conversation_id="cid-1", model="gpt-4o", request_id="rid-1"):
return {
"x-session": hashlib.sha256(conversation_id.encode()).hexdigest(),
"x-umo": UMO,
"x-request": request_id,
"x-model": model,
"x-provider": "provider-1",
"x-version": __version__,
"x-astrbot-conversation-id": conversation_id,
}


def _sent_headers(static_headers, request_headers):
"""Merge SDK default headers with per-request headers like the SDK does."""
sent = {**static_headers, **request_headers}
sent.pop("User-Agent", None)
return sent


def _chat_completion(text="ok"):
return ChatCompletion.model_validate(
{
"id": "chatcmpl-test",
"object": "chat.completion",
"created": 0,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": text},
"finish_reason": "stop",
}
],
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
}
)


def _chat_chunks(text="ok"):
return [
ChatCompletionChunk.model_validate(
{
"id": "chatcmpl-stream",
"object": "chat.completion.chunk",
"created": 0,
"model": "gpt-4o",
"choices": [
{
"index": 0,
"delta": {"role": "assistant", "content": text},
"finish_reason": None,
}
],
}
),
ChatCompletionChunk.model_validate(
{
"id": "chatcmpl-stream",
"object": "chat.completion.chunk",
"created": 0,
"model": "gpt-4o",
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
}
),
]


def _openai_provider():
return ProviderOpenAIOfficial(
{
"id": "provider-1",
"type": "openai_chat_completion",
"model": "gpt-4o-mini",
"key": ["test-key"],
"custom_headers": dict(CUSTOM_HEADERS),
},
{},
)


async def _openai_text_chat_with_capture(monkeypatch, **chat_kwargs):
provider = _openai_provider()
captured: list[dict] = []

async def fake_create(**kwargs):
captured.append(kwargs)
return _chat_completion()

monkeypatch.setattr(provider.client.chat.completions, "create", fake_create)
try:
response = await provider.text_chat(prompt="hi", **chat_kwargs)
finally:
await provider.terminate()
return provider, captured, response


@pytest.mark.asyncio
async def test_openai_text_chat_sends_rendered_request_headers(monkeypatch):
provider, captured, response = await _openai_text_chat_with_capture(
monkeypatch,
umo=UMO,
conversation_id="cid-1",
request_id="rid-1",
model="gpt-4o",
)

assert response.completion_text == "ok"
assert _sent_headers(provider.custom_headers, captured[0]["extra_headers"]) == (
_expected_headers()
)
# Dynamic templates must never reach SDK default headers.
assert "x-session" not in provider.custom_headers
assert "x-astrbot-conversation-id" not in provider.custom_headers


@pytest.mark.asyncio
async def test_openai_text_chat_omits_headers_with_missing_values(monkeypatch):
provider = _openai_provider()
captured: list[dict] = []

async def fake_create(**kwargs):
captured.append(kwargs)
return _chat_completion()

monkeypatch.setattr(provider.client.chat.completions, "create", fake_create)
try:
await provider.text_chat(prompt="hi", request_id="rid-1")
finally:
await provider.terminate()

headers = captured[0]["extra_headers"]
assert "x-umo" not in headers
assert "x-astrbot-conversation-id" not in headers
assert headers["x-request"] == "rid-1"
# {conversation_id} falls back to the request ID.
assert headers["x-session"] == hashlib.sha256(b"rid-1").hexdigest()
assert provider._omitted_header_logs == {"x-umo"}


@pytest.mark.asyncio
async def test_openai_text_chat_reuses_headers_across_transport_retries(monkeypatch):
monkeypatch.setattr(request_retry, "REQUEST_RETRY_WAIT_MIN_S", 0)
monkeypatch.setattr(request_retry, "REQUEST_RETRY_WAIT_MAX_S", 0)

provider = _openai_provider()
captured: list[dict] = []
attempts = 0

async def fake_create(**kwargs):
nonlocal attempts
attempts += 1
captured.append(kwargs)
if attempts == 1:
raise httpx.ConnectError("temporary connection failure")
return _chat_completion()

monkeypatch.setattr(provider.client.chat.completions, "create", fake_create)
try:
await provider.text_chat(
prompt="hi",
umo=UMO,
conversation_id="cid-1",
request_id="rid-1",
request_max_retries=2,
)
finally:
await provider.terminate()

assert attempts == 2
assert captured[0]["extra_headers"] == captured[1]["extra_headers"]
assert _sent_headers(provider.custom_headers, captured[1]["extra_headers"]) == (
_expected_headers(model="gpt-4o-mini")
)


@pytest.mark.asyncio
async def test_openai_text_chat_generates_distinct_request_ids_without_one(monkeypatch):
provider = _openai_provider()
captured: list[dict] = []

async def fake_create(**kwargs):
captured.append(kwargs)
return _chat_completion()

monkeypatch.setattr(provider.client.chat.completions, "create", fake_create)
try:
await provider.text_chat(prompt="hi", session_id=UMO)
await provider.text_chat(prompt="hi again", session_id=UMO)
finally:
await provider.terminate()

first, second = (item["extra_headers"]["x-request"] for item in captured)
assert first != second
for item in captured:
headers = item["extra_headers"]
assert "x-astrbot-conversation-id" not in headers
# The deprecated session_id parameter must not leak as {umo}.
assert "x-umo" not in headers
assert (
headers["x-session"]
== hashlib.sha256(headers["x-request"].encode()).hexdigest()
)


@pytest.mark.asyncio
async def test_openai_text_chat_stream_sends_rendered_request_headers(monkeypatch):
provider = _openai_provider()
captured: list[dict] = []

async def fake_stream():
for chunk in _chat_chunks():
yield chunk

async def fake_create(**kwargs):
captured.append(kwargs)
return fake_stream()

monkeypatch.setattr(provider.client.chat.completions, "create", fake_create)
try:
responses = [
response
async for response in provider.text_chat_stream(
prompt="hi",
umo=UMO,
conversation_id="cid-1",
request_id="rid-1",
model="gpt-4o",
)
]
finally:
await provider.terminate()

assert responses[-1].completion_text == "ok"
assert _sent_headers(provider.custom_headers, captured[0]["extra_headers"]) == (
_expected_headers()
)


@pytest.mark.asyncio
async def test_openai_responses_sends_rendered_request_headers(monkeypatch):
provider = ProviderOpenAIResponses(
{
"id": "provider-1",
"type": "openai_responses",
"model": "gpt-5",
"key": ["test-key"],
"custom_headers": dict(CUSTOM_HEADERS),
},
{},
)
captured: list[dict] = []

async def fake_create(**kwargs):
captured.append(kwargs)
return OpenAIResponse.model_validate(
{
"id": "resp-1",
"object": "response",
"created_at": 0,
"status": "completed",
"model": "gpt-5",
"parallel_tool_calls": False,
"tool_choice": "auto",
"tools": [],
"output": [
{
"type": "message",
"id": "msg-1",
"role": "assistant",
"status": "completed",
"content": [
{"type": "output_text", "text": "ok", "annotations": []}
],
}
],
}
)

monkeypatch.setattr(provider.client.responses, "create", fake_create)
try:
response = await provider.text_chat(
prompt="hi",
umo=UMO,
conversation_id="cid-1",
request_id="rid-1",
)
finally:
await provider.terminate()

assert response.completion_text == "ok"
assert _sent_headers(provider.custom_headers, captured[0]["extra_headers"]) == (
_expected_headers(model="gpt-5")
)
assert "x-session" not in provider.custom_headers


@pytest.mark.asyncio
async def test_openai_responses_stream_sends_rendered_request_headers(monkeypatch):
provider = ProviderOpenAIResponses(
{
"id": "provider-1",
"type": "openai_responses",
"model": "gpt-5",
"key": ["test-key"],
"custom_headers": dict(CUSTOM_HEADERS),
},
{},
)
captured: list[dict] = []
final_response = OpenAIResponse.model_validate(
{
"id": "resp-1",
"object": "response",
"created_at": 0,
"status": "completed",
"model": "gpt-5-mini",
"parallel_tool_calls": False,
"tool_choice": "auto",
"tools": [],
"output": [
{
"type": "message",
"id": "msg-1",
"role": "assistant",
"status": "completed",
"content": [
{"type": "output_text", "text": "ok", "annotations": []}
],
}
],
}
)

async def fake_stream():
yield SimpleNamespace(
type="response.created",
response=SimpleNamespace(id="resp-1"),
)
yield SimpleNamespace(type="response.output_text.delta", delta="ok")
yield SimpleNamespace(type="response.completed", response=final_response)

async def fake_create(**kwargs):
captured.append(kwargs)
return fake_stream()

monkeypatch.setattr(provider.client.responses, "create", fake_create)
try:
responses = [
response
async for response in provider.text_chat_stream(
prompt="hi",
umo=UMO,
conversation_id="cid-1",
request_id="rid-1",
model="gpt-5-mini",
)
]
finally:
await provider.terminate()

assert responses[-1].completion_text == "ok"
assert captured[0]["stream"] is True
assert _sent_headers(provider.custom_headers, captured[0]["extra_headers"]) == (
_expected_headers(model="gpt-5-mini")
)


@pytest.mark.asyncio
async def test_openai_key_rotation_reuses_rendered_headers(monkeypatch):
provider = ProviderOpenAIOfficial(
{
"id": "provider-1",
"type": "openai_chat_completion",
"model": "gpt-4o-mini",
"key": ["key-a", "key-b"],
"custom_headers": dict(CUSTOM_HEADERS),
},
{},
)
captured: list[tuple[str, dict]] = []

async def fake_create(**kwargs):
captured.append((provider.client.api_key, kwargs["extra_headers"]))
if len(captured) == 1:
raise Exception("429 too many requests, slow down")
return _chat_completion()

monkeypatch.setattr(provider.client.chat.completions, "create", fake_create)
try:
response = await provider.text_chat(
prompt="hi",
umo=UMO,
conversation_id="cid-1",
request_id="rid-1",
)
finally:
await provider.terminate()

assert response.completion_text == "ok"
assert len(captured) == 2
assert captured[0][0] != captured[1][0]
assert captured[0][1] == captured[1][1]
assert _sent_headers(provider.custom_headers, captured[1][1]) == _expected_headers(
model="gpt-4o-mini"
)


@pytest.mark.asyncio
async def test_anthropic_text_chat_sends_rendered_request_headers(monkeypatch):
provider = ProviderAnthropic(
{
"id": "provider-1",
"type": "anthropic_chat_completion",
"model": "claude-sonnet-4",
"key": ["test-key"],
"custom_headers": dict(CUSTOM_HEADERS),
},
{},
)
captured: list[dict] = []

async def fake_create(**kwargs):
captured.append(kwargs)
return AnthropicMessage.model_validate(
{
"id": "msg-1",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-4",
"content": [{"type": "text", "text": "ok"}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 1, "output_tokens": 1},
}
)

monkeypatch.setattr(provider.client.messages, "create", fake_create)
try:
response = await provider.text_chat(
prompt="hi",
umo=UMO,
conversation_id="cid-1",
request_id="rid-1",
)
finally:
await provider.terminate()

assert response.completion_text == "ok"
assert _sent_headers(provider.custom_headers, captured[0]["extra_headers"]) == (
_expected_headers(model="claude-sonnet-4")
)
assert "x-session" not in provider.custom_headers


@pytest.mark.asyncio
async def test_anthropic_text_chat_stream_forwards_rendered_headers(monkeypatch):
provider = ProviderAnthropic(
{
"id": "provider-1",
"type": "anthropic_chat_completion",
"model": "claude-sonnet-4",
"key": ["test-key"],
"custom_headers": dict(CUSTOM_HEADERS),
},
{},
)
captured: list[dict] = []

async def fake_query_stream(payloads, tools, **kwargs):
captured.append(kwargs)
yield LLMResponse(role="assistant", completion_text="ok")

monkeypatch.setattr(provider, "_query_stream", fake_query_stream)
try:
responses = [
response
async for response in provider.text_chat_stream(
prompt="hi",
umo=UMO,
conversation_id="cid-1",
request_id="rid-1",
)
]
finally:
await provider.terminate()

assert responses[-1].completion_text == "ok"
assert _sent_headers(provider.custom_headers, captured[0]["request_headers"]) == (
_expected_headers(model="claude-sonnet-4")
)


def _gemini_provider():
return ProviderGoogleGenAI(
{
"id": "provider-1",
"type": "googlegenai_chat_completion",
"model": "gemini-2.5-flash",
"api_base": "https://gemini.example.test",
"key": ["test-key"],
"custom_headers": dict(CUSTOM_HEADERS),
},
{},
)


def _gemini_response(text="ok"):
candidate = SimpleNamespace(
content=SimpleNamespace(parts=[genai_types.Part.from_text(text=text)]),
finish_reason=genai_types.FinishReason.STOP,
)
return SimpleNamespace(
candidates=[candidate], response_id="resp-1", usage_metadata=None
)


@pytest.mark.asyncio
async def test_gemini_text_chat_sends_rendered_request_headers(monkeypatch):
provider = _gemini_provider()
captured: list[dict] = []

async def fake_generate_content(**kwargs):
captured.append(kwargs)
return _gemini_response()

monkeypatch.setattr(
provider.client.models, "generate_content", fake_generate_content
)
try:
response = await provider.text_chat(
prompt="hi",
umo=UMO,
model="gemini-2.5-pro",
conversation_id="cid-1",
request_id="rid-1",
)
client_headers = dict(provider.client._api_client._http_options.headers)
finally:
await provider.terminate()

assert response.completion_text == "ok"
config = captured[0]["config"]
assert config.http_options is not None
expected = _expected_headers(model="gemini-2.5-pro")
assert config.http_options.headers == {
name: value
for name, value in expected.items()
if name not in {"x-provider", "x-version"}
}
sent = _sent_headers(client_headers, config.http_options.headers)
for name, value in expected.items():
assert sent[name] == value
# The shared client keeps only static headers.
assert "x-astrbot-conversation-id" not in client_headers
assert "x-session" not in client_headers


@pytest.mark.asyncio
async def test_gemini_streams_do_not_block_each_other(monkeypatch):
provider = _gemini_provider()
entered: list[dict] = []
release = asyncio.Event()

async def fake_generate_stream(**kwargs):
entered.append(kwargs["config"].http_options.headers)
if len(entered) == 2:
release.set()
await asyncio.wait_for(release.wait(), timeout=5)

async def generator():
yield SimpleNamespace(
candidates=[
SimpleNamespace(
content=SimpleNamespace(
parts=[genai_types.Part.from_text(text="ok")]
),
finish_reason=genai_types.FinishReason.STOP,
)
],
text="ok",
response_id="resp-1",
usage_metadata=None,
)

return generator()

monkeypatch.setattr(
provider.client.models, "generate_content_stream", fake_generate_stream
)

async def drain(conversation_id):
return [
response
async for response in provider._query_stream(
payloads={
"messages": [{"role": "user", "content": "hi"}],
"model": "gemini-2.5-flash",
},
tools=None,
conversation_id=conversation_id,
request_headers={
"x-astrbot-conversation-id": conversation_id,
"x-session": conversation_id,
},
)
]

try:
await asyncio.wait_for(
asyncio.gather(drain("cid-1"), drain("cid-2")), timeout=10
)
client_headers = dict(provider.client._api_client._http_options.headers)
finally:
await provider.terminate()

assert [headers["x-session"] for headers in entered] == ["cid-1", "cid-2"]
assert "x-astrbot-conversation-id" not in client_headers

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Regression tests are added

When the PR adds or extends the cited tests, the PR adds new regression tests and extends existing test cases despite the repository instruction not to generate test files, so these changes expand the test suite contrary to that guidance.

Remove the added test cases and test files to follow the repository guidance.

Also at tests/unit/test_provider_headers.py:1-128, tests/test_anthropic_source.py:546-576, tests/test_gemini_source.py:353-401, tests/test_provider_user_agent.py:135-199, tests/test_tool_loop_agent_runner.py:2652-2762, tests/unit/test_group_chat_context_wiring.py:129-167.

Prompt for AI agents
In `tests/test_provider_header_templates.py` at lines 1-650:

**Regression tests are added**

When the PR adds or extends the cited tests, the PR adds new regression tests and extends existing test cases despite the repository instruction not to generate test files, so these changes expand the test suite contrary to that guidance.

Remove the added test cases and test files to follow the repository guidance.

Also at `tests/unit/test_provider_headers.py:1-128`, `tests/test_anthropic_source.py:546-576`, `tests/test_gemini_source.py:353-401`, `tests/test_provider_user_agent.py:135-199`, `tests/test_tool_loop_agent_runner.py:2652-2762`, `tests/unit/test_group_chat_context_wiring.py:129-167`.

From .github/copilot-instructions.md L27:

Do not generate test files for now.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1c8215811c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/test_provider_header_templates.py Resolved
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-26T15:04:10.819219Z 6f04568 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bbb8722cdf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/test_provider_header_templates.py Resolved
@codecov-commenter

codecov-commenter commented Nov 13, 2026 •

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

❌ Patch coverage is 93.50000% with 13 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
astrbot/core/provider/sources/gemini_source.py 84.05% 11 Missing ⚠️
astrbot/core/provider/headers.py 97.10% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New gaps against the linked issues

Comment thread astrbot/core/provider/headers.py Resolved
@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

…-request-header-templates

# Conflicts:
#	astrbot/core/provider/sources/gemini_source.py
#	tests/test_gemini_source.py
#	tests/test_tool_loop_agent_runner.py
@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6f04568369

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

conversation_id=conversation_id,
umo=umo,
request_id=request_id,
model=str(payloads.get("model", "")),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor custom-body model overrides when rendering headers

When custom_extra_body overrides model, a header such as x-model: {model} is rendered from the original model here, but _query() subsequently passes the override through extra_body, which replaces the SDK's top-level JSON field. The outgoing body and header therefore identify different models, making the new variable incorrect for proxies that use it for per-model routing or accounting. Render the header from the effective model after custom-body overrides; the streaming, inherited Responses, and Anthropic paths have the same ordering.

Useful? React with 👍 / 👎.

@mantoujun12 mantoujun12 added enhancement New feature or request area:provider The bug / feature is about AI Provider, Models, LLM Agent, LLM Agent Runner. labels Nov 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:provider The bug / feature is about AI Provider, Models, LLM Agent, LLM Agent Runner. enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants