Skip to content

feat(provider): add response_format, max_tokens, and temperature to text_chat - #11616

Open
JosephTian876 wants to merge 1 commit into
AstrBotDevs:masterfrom
JosephTian876:feat/provider-text-chat-structured-output
Open

JosephTian876 wants to merge 1 commit into
AstrBotDevs:masterfrom
JosephTian876:feat/provider-text-chat-structured-output

Conversation

@JosephTian876

Copy link
Copy Markdown
Contributor

Summary

Adds optional per-request response_format, max_tokens, and temperature parameters to Provider.text_chat() and Provider.text_chat_stream(), with provider-native structured output translation, per-request override precedence over static custom_extra_body defaults, and fail-fast outer retry handling when request_max_retries is specified.

Motivation

Plugins and core workflows that invoke provider.text_chat(...) for structured JSON classification, extraction, or deterministic short replies currently have no uniform per-request way to specify response_format, max_tokens, or temperature across providers:

  • Provider.text_chat() and Provider.text_chat_stream() did not expose response_format, max_tokens, or temperature in their base contract.
  • Static defaults in custom_extra_body (such as high temperature or large max_tokens) could conflict with or override per-request structured calls.
  • Each provider expects a distinct wire representation for structured output (OpenAI Chat Completions response_format, OpenAI Responses text.format, Google Gemini response_mime_type + response_schema without additionalProperties, Anthropic forced emit_json tool / output_config.format without an OpenAI response_format key).
  • Outer retry loops in ProviderOpenAIOfficial and ProviderGoogleGenAI hardcoded 10 retries even when callers explicitly requested request_max_retries=1 for fail-fast structured calls.

Changes

  1. Base Provider Interface (astrbot/core/provider/provider.py)

    • Adds optional keyword arguments response_format: dict | None = None, max_tokens: int | None = None, and temperature: float | None = None to Provider.text_chat() and Provider.text_chat_stream() with docstrings, preserving full backward compatibility.
  2. OpenAI Chat Completions (astrbot/core/provider/sources/openai_source.py)

    • Forwards response_format, max_tokens, and temperature from text_chat() / text_chat_stream() through _prepare_chat_payload() into payloads.
    • Strips conflicting response_format, max_tokens, and temperature keys from extra_body in _query() and _query_stream() when explicitly provided per request.
    • Caps outer retry loops in text_chat() and text_chat_stream() to max(1, int(request_max_retries)) when request_max_retries is provided, and tracks stream completion cleanly so single-attempt calls fail fast on error and never falsely raise on attempt-1 success.
  3. OpenAI Responses API (astrbot/core/provider/sources/openai_responses_source.py)

    • Translates OpenAI Chat Completions response_format (json_schema, json_object, text) via _translate_response_format() into Responses API text.format.
    • Maps max_tokens to max_output_tokens and forwards temperature.
    • Adds _merge_request_overrides() in _query() and _query_stream() so explicit per-request text.format, max_output_tokens, and temperature take precedence over custom_extra_body while preserving non-conflicting custom_extra_body.text keys (e.g. verbosity).
  4. Google Gemini (astrbot/core/provider/sources/gemini_source.py)

    • Translates response_format in _prepare_query_config() via _apply_response_format():
      • json_object -> response_mime_type="application/json".
      • json_schema -> response_mime_type="application/json" + response_schema with _strip_additional_properties() recursively stripping unsupported schema keywords (additionalProperties, additional_properties, $schema) without mutating caller dicts or stripping property keys named "additionalProperties" inside "properties".
    • Forwards max_tokens (mapped to max_output_tokens) and temperature with per-request precedence over custom_extra_body.
    • Caps outer retry loops in text_chat() and text_chat_stream() to max(1, int(request_max_retries)) when request_max_retries is set.
  5. Anthropic Messages (astrbot/core/provider/sources/anthropic_source.py)

    • Never forwards an OpenAI response_format key (from either request kwargs or custom_extra_body) to Anthropic Messages API.
    • Translates response_format via _apply_response_format():
      • When no caller tools are active and the target is an object json_schema or json_object, injects a forced emit_json tool (tool_choice={"type": "tool", "name": "emit_json"}), disables conflicting thinking configuration (from both provider config and custom_extra_body), and unwraps the emit_json tool_use payload cleanly back into completion_text (preferring the structured JSON payload over any stray preamble text) across both _query() and _query_stream().
      • When caller tools are present or the root schema is non-object, falls back to output_config.format (merging with any non-conflicting custom_extra_body.output_config keys).
    • Routes SDK-unsupported request kwargs (such as temperature on anthropic>=2.x or output_config on older SDK versions) into extra_body via _route_unsupported_sdk_params() so wire payloads remain compatible across Anthropic SDK versions without raising TypeError.
  6. Tests (No New Standalone Test Files)

    • Adds focused unit and wire-level tests directly into existing suites (tests/test_openai_source.py, tests/test_openai_responses_source.py, tests/test_gemini_source.py, tests/test_anthropic_source.py), keeping zero new standalone test files in compliance with #11511.

Files Changed

  • astrbot/core/provider/provider.py
  • astrbot/core/provider/sources/openai_source.py
  • astrbot/core/provider/sources/openai_responses_source.py
  • astrbot/core/provider/sources/gemini_source.py
  • astrbot/core/provider/sources/anthropic_source.py
  • tests/test_openai_source.py
  • tests/test_openai_responses_source.py
  • tests/test_gemini_source.py
  • tests/test_anthropic_source.py

Verification

  • python -m py_compile on all 5 modified provider source files: passed.
  • ruff format --check .: passed (606 files already formatted).
  • ruff check .: passed (All checks passed!).
  • pytest tests/test_openai_source.py tests/test_openai_responses_source.py tests/test_gemini_source.py tests/test_anthropic_source.py -q: 145 passed, 0 failed (including real httpx.MockTransport wire SSE test on anthropic==2.16.0).
  • pytest tests/test_provider_user_agent.py -q: 44 passed, 1 skipped.
  • git merge-tree --write-tree against base 482f5b44a and all 8 sibling AstrBot PR branches: 0 conflicts.

建议合并顺序 (Recommended Merge Order)

  • Independent, zero-conflict feature PR (verified via git merge-tree --write-tree against base 482f5b44a and all sibling AstrBot PR branches):
    1. fix/plugin-service-closed-connector
    2. fix/t2i-local-skip-external-probe
    3. fix/aiocqhttp-at-member-fallback
    4. fix/system-one-decision-float32-softmax-tol
    5. fix/plugin-view-iframe-allow-popups
    6. fix/gemini-thinking-camelcase-and-safety
    7. fix/gemini-openai-extra-body-guard
    8. feat/provider-text-chat-structured-output (this PR) — lands cleanly in any order; placing it after the two Gemini/OpenAI config fixes keeps provider changes easy to review sequentially.

@sourcery-ai

sourcery-ai Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Sorry @JosephTian876, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 4 days and 10 hours by commenting @sourcery-ai review. Upgrade to get a review now.

…ext_chat

Add optional per-request response_format, max_tokens, and temperature
parameters to Provider.text_chat() and Provider.text_chat_stream(), and
implement provider-specific translation and override precedence across OpenAI
Chat Completions, OpenAI Responses, Google Gemini, and Anthropic Messages:

- Provider base (provider.py): expose optional response_format, max_tokens,
  and temperature kwargs on text_chat and text_chat_stream.
- OpenAI Chat Completions (openai_source.py): forward per-request params in
  payloads, strip conflicting defaults from custom_extra_body, and honor
  request_max_retries on outer retry loops so single-attempt callers fail fast.
- OpenAI Responses (openai_responses_source.py): translate Chat Completions
  response_format (json_schema / json_object / text) into text.format, map
  max_tokens to max_output_tokens, and preserve non-conflicting
  custom_extra_body.text keys (e.g. verbosity).
- Google Gemini (gemini_source.py): translate response_format into
  response_mime_type="application/json" and response_schema while stripping
  unsupported schema keys (additionalProperties, additional_properties,
  $schema), and honor request_max_retries on outer retry loops.
- Anthropic Messages (anthropic_source.py): never forward OpenAI
  response_format; use a forced emit_json tool (unwrapped back into
  completion_text in both sync and streaming paths, disabling conflicting
  thinking config) when no caller tools are active and root schema is an
  object, falling back to output_config.format otherwise; route SDK-unsupported
  kwargs such as temperature on anthropic v2 into extra_body.
- Tests: add concise unit and wire-level coverage directly in existing
  tests/test_{openai,openai_responses,gemini,anthropic}_source.py.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant