Skip to content

fix(py): OpenAI tool_choice after tool turns, integer topK, evaluator typing, static django __all__ - #6692

Closed
huangjeff5 wants to merge 4 commits into
genkit-ai:mainfrom
huangjeff5:fix/py-small-preexisting-fixes
Closed

huangjeff5 wants to merge 4 commits into
genkit-ai:mainfrom
huangjeff5:fix/py-small-preexisting-fixes

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Four small fixes for bugs that already exist on main: OpenAI honors tool_choice after a tool turn; Gemini and Anthropic now send topK as an integer; the Vertex evaluator lookup type-checks under pyrefly; and genkit_django.__all__ is a static list.

from genkit_google_genai import GeminiConfig

# 1. Ask for top-k sampling
config = GeminiConfig(top_k=40)

# 2. The generateContent body
# --- BEFORE ---
# => {"generationConfig": {"topK": 40.0}}
# --- AFTER ---
# => {"generationConfig": {"topK": 40}}
# 1. Chain two tools on OpenAI
response = await ai.generate(
    model='openai/gpt-4o',
    prompt='Is the pho in stock, and is it nut-free?',
    tools=['lookup_menu', 'check_allergens'],
)

# 2. The second chat.completions body, after lookup_menu returned
# --- BEFORE ---
# => {"tool_choice": "none", ...}   the model can't call check_allergens
# --- AFTER ---
# => no tool_choice, so the model chains check_allergens

Decisions

  • OpenAI sends the caller's tool_choice on every turn: the OpenAI model forced tool_choice='none' once history held any tool message, so after one tool result the model couldn't call another, and 'required' was dropped from the second turn on. The rule came in with the DeepSeek plugin (feat(py): Implemented deepseek plugin #4051) with no stated reason; it stopped a 'required' run from re-forcing tool calls forever. Core's max_turns already bounds that loop, as it does for Anthropic, Gemini and Go compat_oai, so we pass auto/required/none through unchanged. tool_choice now rides only with tools, because OpenAI rejects it without them. Vertex Model Garden's OpenAI-compatible models share this path.
  • Send the integer the API defines: google-genai 2.21 types GenerateContentConfig.top_k as Optional[float], though the Gemini API defines topK as int32. So GenerateContentConfig(**known) turned 40 into 40.0. Genkit's own GeminiConfig.top_k was already int. We assign the int back after building the SDK config. The SDK doesn't validate on assignment, so the int survives to the wire, on Google AI and Vertex. Anthropic had the same bug through AnthropicConfig.top_k: float, inherited from GenerationCommonConfig. _build_params now sends an integral float as int, the same way it already treats max_tokens. Vertex Model Garden Claude shares that path.
  • Look up evaluator metrics by value: pyrefly runs with python_version = "3.10", so StrEnum comes from the strenum backport. Its stub types __new__ as returning the base StrEnum, which made VertexAIEvaluationMetricType(name.upper()) a StrEnum. That didn't match create_vertex_evaluators(metrics: list[VertexAIEvaluationMetricType]). We find the member by iterating the enum, which yields the subclass type, so there's no cast or ignore, and matching is still by value. Behavior is unchanged.
  • Static __all__: genkit_django.__all__ built an entry from genkit_django_handler.__name__. pyright can't analyze that, and it was the only warning in pyright packages/*/src. The list is now literal; the runtime value is identical.

Verification

  • New tests:
    • openai_tool_choice_test.py: HTTP bodies for each of the 4 values with tools, 'required' and None across a two-tool chain, and tool_choice dropped with no tools. 5 of 9 fail without the fix.
    • gemini_int_config_wire_test.py: Google AI and Vertex × typed and dict config. Asserts type(...) is int for topK, maxOutputTokens, candidateCount, seed and logprobs in the real HTTP body.
    • An Anthropic top_k body test.
    • All 5 topK tests fail without the fix.
  • Ran ruff, pyrefly (0 errors), pyright packages/*/src (0 errors, 0 warnings), ty, generate_schema_typing --ci and uv lock --check: all clean. pytest: 5225 passed.
  • The Dev UI schema is unchanged.

google-genai types GenerateContentConfig.top_k as float, so building the
config coerced 40 to 40.0 and the generateContent body carried
"topK": 40.0 on both GoogleAI and Vertex. The API defines topK as int32.
Reassign the int after construction; the SDK doesn't validate on
assignment.

AnthropicConfig inherits top_k: float from ModelConfig, so the dumped
params sent "top_k": 40.0. Convert integral values to int, as max_tokens
already is.

Other int knobs (maxOutputTokens, candidateCount, seed, logprobs) were
already ints. Ollama coerces through ollama.Options; OpenAI drops top_k.

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request ensures that integer configuration parameters, specifically top_k, are correctly transmitted as integers rather than being coerced to floats by the underlying SDKs for Anthropic and Gemini models. It also resolves a Python 3.10 type-stub issue with StrEnum in the Google GenAI evaluator and cleans up the __all__ exports in the Django package. Feedback on the changes suggests making the top_k extraction in the Gemini model more robust by also handling float values that represent integers, aligning it with the Anthropic implementation.

Comment on lines +1986 to +1987
if isinstance(known.get('top_k'), int):
cfg.top_k = known['top_k']

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.

medium

To make the top_k extraction more robust and consistent with the Anthropic implementation, consider handling both int (excluding bool) and float values that represent integers (e.g., 40.0 passed via a raw dictionary config). This ensures that any integral float is correctly coerced to an integer before being assigned to cfg.top_k.

Suggested change
if isinstance(known.get('top_k'), int):
cfg.top_k = known['top_k']
top_k = known.get('top_k')
if isinstance(top_k, int) and not isinstance(top_k, bool):
cfg.top_k = top_k
elif isinstance(top_k, float) and top_k.is_integer():
cfg.top_k = int(top_k)

The OpenAI model forced tool_choice='none' whenever history held a tool
message, whatever the caller asked for. So after one tool result the
model couldn't call another tool: no multi-step chaining, and
tool_choice='required' was dropped from the second turn on. The rule
came in with the DeepSeek plugin (genkit-ai#4051) with no stated reason; it
stopped a 'required' run from re-forcing tool calls forever. Core's
max_turns already bounds that loop, as it does for Anthropic, Gemini
and Go compat_oai, which pass the value through.

Genkit's auto/required/none are OpenAI's values, so they go out
unchanged and None sends nothing. tool_choice now rides only with
tools: OpenAI rejects it without them.

Vertex AI Model Garden's OpenAI-compatible models build the same
OpenAIModel, so they get the fix too.
@huangjeff5 huangjeff5 changed the title fix(py): integer topK, Vertex evaluator metric typing, static django __all__ fix(py): OpenAI tool_choice after tool turns, integer topK, evaluator typing, static django __all__ Oct 8, 2026
@huangjeff5

Copy link
Copy Markdown
Contributor Author

Moved to #6696 so the branch lives in genkit-ai/genkit.

@huangjeff5 huangjeff5 closed this Oct 8, 2026
@huangjeff5
huangjeff5 deleted the fix/py-small-preexisting-fixes branch October 8, 2026 22:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant