Skip to content

Fix: support tool call config - #14616

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b036
May 7, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
buua436:b036

Conversation

@buua436

@buua436 buua436 commented May 7, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

support tool call config

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@buua436
buua436 requested a review from Lynn-Inf May 7, 2026 04:01
@coderabbitai

coderabbitai Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4b1ad461-1765-422c-a9db-a994050f6b5b

📥 Commits

Reviewing files that changed from the base of the PR and between abe2ad7 and 1489201.

📒 Files selected for processing (1)
  • api/apps/llm_app.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/llm_app.py

📝 Walkthrough

Walkthrough

Adds opt-in "tool calling" metadata encoded with tenant LLM API keys, surfaces it through API endpoints and UI (add/edit LLM), decodes it when building model configs/instances, and refines agent streaming error handling to consistently emit fallback content on error deltas.

Changes

Tool-Calling Configuration & UI + Agent Error Handling

Layer / File(s) Summary
Data Shape / Encoding
api/db/services/tenant_llm_service.py
Adds _decode_api_key_config and _encode_api_key_config to interpret stored api_key as raw string or JSON (contains api_key and optional is_tools); get_model_config now injects api_key_payload and is_tools when decoded.
Model Config Normalization
api/db/joint_services/tenant_model_service.py
get_model_config_by_id and get_model_config_by_type_and_name decode/normalize api_key, optionally add api_key_payload and is_tools, and only derive is_tools from LLMService.query when missing.
Model Instantiation
api/db/services/tenant_llm_service.py
model_instance prefers api_key_payload over api_key when constructing model clients and continues wiring per-model kwargs.
API Endpoint Logic
api/apps/llm_app.py
/add_llm reuses an existing tenant LLM API key when request omits api_key, and re-encodes llm["api_key"] with is_tools when provided; /my_llms includes is_tools in details by decoding stored config or inferring from model metadata.
Agent Streaming Error Handling
agent/component/agent_with_tools.py
On "**ERROR**" stream deltas, now yields get_exception_default_value() via content and returns if available; otherwise sets _ERROR and content to the error delta and yields it.
Request Contract
web/src/interfaces/request/llm.ts
Adds optional is_tools?: boolean to IAddLlmRequestBody.
Frontend Init / Form Defaults
web/src/pages/user-setting/setting-model/hooks.tsx
useSubmitOllama includes is_tools (defaults to false) in modal initial values when editing.
Modal UI & Submission
web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx
Adds conditional is_tools Switch for chat and image2text types; default values and submit payload include is_tools when model type supports tool calling.
I18n
web/src/locales/en.ts, web/src/locales/zh.ts
Adds setting.enableToolCall and setting.enableToolCallTip translations.

Sequence Diagram(s)

sequenceDiagram
    participant Frontend
    participant API
    participant TenantService
    participant DB

    Frontend->>API: POST /add_llm (may omit api_key, may include is_tools)
    API->>TenantService: find existing TenantLLM by tenant/factory/name (if api_key missing)
    TenantService->>DB: read stored api_key
    DB-->>TenantService: stored api_key (raw or JSON)
    TenantService->>TenantService: _decode_api_key_config -> (api_key, is_tools?)
    TenantService-->>API: return decoded api_key / is_tools
    API->>DB: persist llm with api_key encoded via _encode_api_key_config(if is_tools provided)
    API-->>Frontend: 200 OK
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested labels

size:M

Suggested reviewers

  • Magicbook1108

"I nibble on keys, I stash 'is_tools' in tow,
JSON or plain, now the configs all know,
Frontend flips the switch, backend reads it right,
Streams hush on errors — fallback shining bright,
Hop, code deployed — a rabbit's tiny glow."

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: adding support for tool call configuration, which is the primary objective across all modified files.
Description check ✅ Passed The description provides the required problem statement and correctly identifies this as a bug fix, but lacks detail on how the issue is solved and what specifically changed.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@buua436 buua436 added the ci Continue Integration label May 7, 2026
@buua436
buua436 marked this pull request as ready for review May 7, 2026 04:01
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels May 7, 2026

@coderabbitai coderabbitai 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.

Actionable comments posted: 7

🧹 Nitpick comments (1)
api/apps/llm_app.py (1)

431-439: ⚡ Quick win

Per-row LLMService.query inside the loop is N+1; also duplicates logic.

For each tenant LLM in objs, this resolves is_tools by potentially issuing two LLMService.query calls. With many configured models, this scales poorly. Two improvements:

  1. Pre-fetch all LLMService rows once (e.g., LLMService.get_all() / a batched query) and look up by (llm_name, fid) in memory.
  2. The decode-and-fallback dance is the same as in TenantLLMService.get_model_config and tenant_model_service.py — fold it into the shared helper proposed in the other comment so the three sites stay consistent.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/llm_app.py` around lines 431 - 439, The per-row logic using
TenantLLMService._decode_api_key_config +
TenantLLMService.split_model_name_and_factory that calls LLMService.query causes
an N+1; replace it by pre-fetching all LLMService rows once (e.g.,
LLMService.get_all() or a batched query), build an in-memory lookup keyed by
(llm_name, fid) and consult that for is_tools instead of calling
LLMService.query inside the loop, and then move the decode+fallback logic into
the shared helper used by TenantLLMService.get_model_config /
tenant_model_service.py so the same resolution (decode api key,
split_model_name_and_factory, fallback by base_name) is reused across sites.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@agent/component/agent_with_tools.py`:
- Around line 278-287: The streaming branch that detects "**ERROR**" currently
yields a fallback or the raw delta but does not log the error; update the branch
inside Agent._chat (the block using delta.find("**ERROR**") and calling
self.get_exception_default_value(), self.set_output(...), yield ...) to emit a
log entry (e.g., logging.error with context like f"Agent._chat got error.
response: {delta}") before setting outputs/yielding so behavior matches the
non-streaming path; keep existing calls to get_exception_default_value(),
set_output("_ERROR"/"content"), and yield unchanged aside from adding the log
call.

In `@api/apps/llm_app.py`:
- Around line 369-371: The current logic mutates composite credential JSON by
inserting "is_tools" into llm["api_key"] via
TenantLLMService._encode_api_key_config which causes that extra field to be
passed to provider constructors through model_instance -> api_key_payload; fix
by avoiding mutation of the original credentials: update _encode_api_key_config
to return a wrapper that keeps metadata separate (e.g., { "credentials":
<original dict>, "meta": { "is_tools": bool } }) or deep-copy the credential
dict before adding "is_tools", and update model_instance/api_key_payload
handling to unwrap the wrapper so provider constructors only receive the
original credential keys; ensure references to llm["api_key"],
_encode_api_key_config, model_instance, and api_key_payload are adjusted
accordingly.
- Around line 232-243: The fallback that sets api_key to "x" unconditionally
when req.get("api_key") is None clobbers factory-specific keys built from other
request fields (e.g., VolcEngine, Bedrock, BaiduYiyan, Fish Audio, Google Cloud,
XunFei Spark); update the logic around TenantLLMService.query and the api_key
assignment so you only fall back to existing_api_key (or "x" for validation)
when the request contains no direct api_key AND none of the factory-specific
source fields (ark_api_key, endpoint_id, bedrock_ak, spark_api_password, etc.)
were provided for the current factory, preserving the JSON constructed earlier
for those factories; replace the cross-module private call to
TenantLLMService._decode_api_key_config with the service's public decode API (or
add a public wrapper) when extracting existing_api_key; and remove the N+1 by
moving the LLMService.query out of the for o in objs loop (collect IDs, run one
bulk query, build a map and then iterate objs using that map).

In `@api/db/joint_services/tenant_model_service.py`:
- Around line 29-38: Duplicate decoding/normalization logic for API key handling
should be extracted into a single helper on TenantLLMService; implement a
classmethod like TenantLLMService.normalize_api_key_config(config_dict) that
performs the sequence: call _decode_api_key_config to get (api_key, is_tools,
api_key_payload), set config_dict["api_key"] = api_key, conditionally set
config_dict["api_key_payload"] and config_dict["is_tools"] when non-None, and if
"is_tools" is still missing consult
LLMService.query(llm_name=config_dict["llm_name"]) to set it from
llm[0].is_tools; then replace the duplicated 6-line blocks in
get_model_config_by_id, get_model_config_by_type_and_name, and
TenantLLMService.get_model_config to call this new helper and return its result.

In `@api/db/services/tenant_llm_service.py`:
- Around line 37-71: The helper functions _decode_api_key_config and
_encode_api_key_config are used across modules but are named as private; rename
them to decode_api_key_config and encode_api_key_config and update all callers
to use the new names (references in tenant_model_service.py and
api/apps/llm_app.py). Change the function definitions in tenant_llm_service.py
(remove leading underscores) and update any imports or from ... import ... lines
to import the new names; also update any module-level exports (e.g., __all__) or
type hints if present to reflect the public names so the cross-module contract
is consistent.
- Around line 56-71: The _encode_api_key_config function mutates composite
credential dicts by injecting "is_tools", which can break strict provider
validation; change it so that for dict payloads and non-dict raw_api_key you do
not mutate the original credentials but wrap them in a container like
{"api_key_payload": <original_payload_or_string>, "is_tools": bool(is_tools)};
specifically, in _encode_api_key_config replace the logic that sets
payload["is_tools"] with building and returning a wrapper dict containing
api_key_payload set to the original parsed dict (or the raw_api_key string when
parsed is not a dict) and is_tools as a boolean, serializing that wrapper to
JSON.

In `@web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx`:
- Line 118: The fields useMemo that defines defaultToolCallEnabled (reading
initialValues?.is_tools) must include initialValues in its dependency array so
the memo recomputes when switching edited items; update the dependency list for
the memo that declares defaultToolCallEnabled (and any other memo at the second
occurrence around the is_tools field) to reference initialValues (or
initialValues.is_tools) along with existing deps so the defaultValue for the
is_tools field is not stale.

---

Nitpick comments:
In `@api/apps/llm_app.py`:
- Around line 431-439: The per-row logic using
TenantLLMService._decode_api_key_config +
TenantLLMService.split_model_name_and_factory that calls LLMService.query causes
an N+1; replace it by pre-fetching all LLMService rows once (e.g.,
LLMService.get_all() or a batched query), build an in-memory lookup keyed by
(llm_name, fid) and consult that for is_tools instead of calling
LLMService.query inside the loop, and then move the decode+fallback logic into
the shared helper used by TenantLLMService.get_model_config /
tenant_model_service.py so the same resolution (decode api key,
split_model_name_and_factory, fallback by base_name) is reused across sites.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 35dd9333-cc57-4ee2-96a2-f264f26b2c48

📥 Commits

Reviewing files that changed from the base of the PR and between 86fe78c and 863c7f9.

📒 Files selected for processing (9)
  • agent/component/agent_with_tools.py
  • api/apps/llm_app.py
  • api/db/joint_services/tenant_model_service.py
  • api/db/services/tenant_llm_service.py
  • web/src/interfaces/request/llm.ts
  • web/src/locales/en.ts
  • web/src/locales/zh.ts
  • web/src/pages/user-setting/setting-model/hooks.tsx
  • web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx

Comment on lines 278 to 287
if delta.find("**ERROR**") >= 0:
if self.get_exception_default_value():
self.set_output("content", self.get_exception_default_value())
yield self.get_exception_default_value()
fallback = self.get_exception_default_value()
self.set_output("content", fallback)
yield fallback
else:
self.set_output("_ERROR", delta)
self.set_output("content", delta)
yield delta
return

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add an error log for the streaming error branch.

The non-streaming path at line 229 calls logging.error(f"Agent._chat got error. response: {ans}") when **ERROR** is detected, but this streaming branch silently swallows the error before yielding fallback. Adding a log here keeps behavior symmetric and makes failed tool runs diagnosable.

📝 Proposed fix to log the streaming error
             if delta.find("**ERROR**") >= 0:
+                logging.error(f"Agent.stream_output_with_tools_async got error. delta: {delta}")
                 if self.get_exception_default_value():
                     fallback = self.get_exception_default_value()
                     self.set_output("content", fallback)
                     yield fallback
                 else:
                     self.set_output("_ERROR", delta)
                     self.set_output("content", delta)
                     yield delta
                 return

As per coding guidelines, "Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@agent/component/agent_with_tools.py` around lines 278 - 287, The streaming
branch that detects "**ERROR**" currently yields a fallback or the raw delta but
does not log the error; update the branch inside Agent._chat (the block using
delta.find("**ERROR**") and calling self.get_exception_default_value(),
self.set_output(...), yield ...) to emit a log entry (e.g., logging.error with
context like f"Agent._chat got error. response: {delta}") before setting
outputs/yielding so behavior matches the non-streaming path; keep existing calls
to get_exception_default_value(), set_output("_ERROR"/"content"), and yield
unchanged aside from adding the log call.

Comment thread api/apps/llm_app.py
Comment on lines +232 to +243
existing_llm = None
existing_api_key = None
if req.get("api_key") is None:
existing_llms = TenantLLMService.query(tenant_id=current_user.id, llm_factory=factory, llm_name=llm_name)
if existing_llms:
existing_llm = existing_llms[0]
existing_api_key, _, existing_api_key_payload = TenantLLMService._decode_api_key_config(existing_llm.api_key)
if existing_api_key_payload is not None:
existing_api_key = existing_api_key_payload

if req.get("api_key") is None:
api_key = existing_api_key if existing_api_key is not None else "x"

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.

⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm which factories never receive a top-level `api_key` in the add_llm request — those are the ones broken by the new fallback.
rg -nP --type=py -C2 '\bfactory\s*==\s*"[^"]+"' api/apps/llm_app.py | rg -nC2 'api_key|apikey_json'

Repository: infiniflow/ragflow

Length of output: 2067


🏁 Script executed:

sed -n '232,243p' api/apps/llm_app.py

Repository: infiniflow/ragflow

Length of output: 680


🏁 Script executed:

sed -n '261,280p' api/apps/llm_app.py

Repository: infiniflow/ragflow

Length of output: 1042


🏁 Script executed:

sed -n '431,438p' api/apps/llm_app.py

Repository: infiniflow/ragflow

Length of output: 657


🏁 Script executed:

sed -n '165,175p' api/apps/llm_app.py

Repository: infiniflow/ragflow

Length of output: 471


🏁 Script executed:

# Check if there's any comment or documentation about the fallback logic
sed -n '225,250p' api/apps/llm_app.py

Repository: infiniflow/ragflow

Length of output: 1075


Critical: this fallback clobbers the API key built for special factories.

Several factories (VolcEngine, Bedrock, BaiduYiyan, Fish Audio, Google Cloud, XunFei Spark) construct api_key from other request fields (e.g., ark_api_key, endpoint_id, bedrock_ak, spark_api_password, …) and don't carry a top-level api_key in the request. For those:

  • req.get("api_key") is None → True
  • The carefully built JSON from lines 176-230 is discarded at line 243
  • New registration → api_key = "x" (verification at lines 261+ fails with dummy key; storage broken)
  • Edit → api_key = existing stored value (user edits to ark_api_key/endpoint_id/etc. are silently lost)

Only fall back to the existing stored key when none of the factory-specific source fields were provided. At minimum, restrict the fallback to factories that actually use a direct api_key field.

Additionally, lines 431-438 query LLMService inside the for o in objs: loop, causing N+1 queries. Batch these lookups outside the loop.

Also fix the cross-module private API call to TenantLLMService._decode_api_key_config() at line 238 (same pattern flagged elsewhere).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/llm_app.py` around lines 232 - 243, The fallback that sets api_key
to "x" unconditionally when req.get("api_key") is None clobbers factory-specific
keys built from other request fields (e.g., VolcEngine, Bedrock, BaiduYiyan,
Fish Audio, Google Cloud, XunFei Spark); update the logic around
TenantLLMService.query and the api_key assignment so you only fall back to
existing_api_key (or "x" for validation) when the request contains no direct
api_key AND none of the factory-specific source fields (ark_api_key,
endpoint_id, bedrock_ak, spark_api_password, etc.) were provided for the current
factory, preserving the JSON constructed earlier for those factories; replace
the cross-module private call to TenantLLMService._decode_api_key_config with
the service's public decode API (or add a public wrapper) when extracting
existing_api_key; and remove the N+1 by moving the LLMService.query out of the
for o in objs loop (collect IDs, run one bulk query, build a map and then
iterate objs using that map).

Comment thread api/apps/llm_app.py Resolved
Comment on lines +29 to 38
api_key, is_tools, api_key_payload = TenantLLMService._decode_api_key_config(config_dict.get("api_key", ""))
config_dict["api_key"] = api_key
if api_key_payload is not None:
config_dict["api_key_payload"] = api_key_payload
if is_tools is not None:
config_dict["is_tools"] = is_tools
llm = LLMService.query(llm_name=config_dict["llm_name"])
if llm:
if "is_tools" not in config_dict and llm:
config_dict["is_tools"] = llm[0].is_tools
return config_dict

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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Extract the duplicated decode-and-normalize block.

The same 6-line decoding logic (decode → overwrite api_key → conditionally set api_key_payload / is_tools → fallback is_tools from LLMService) appears in get_model_config_by_id, get_model_config_by_type_and_name, and TenantLLMService.get_model_config (lines 162-178 in tenant_llm_service.py). Extract a single helper (e.g., TenantLLMService.normalize_api_key_config(config_dict)) so behavior stays consistent across all three call sites.

Also applies to: 82-99

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/db/joint_services/tenant_model_service.py` around lines 29 - 38,
Duplicate decoding/normalization logic for API key handling should be extracted
into a single helper on TenantLLMService; implement a classmethod like
TenantLLMService.normalize_api_key_config(config_dict) that performs the
sequence: call _decode_api_key_config to get (api_key, is_tools,
api_key_payload), set config_dict["api_key"] = api_key, conditionally set
config_dict["api_key_payload"] and config_dict["is_tools"] when non-None, and if
"is_tools" is still missing consult
LLMService.query(llm_name=config_dict["llm_name"]) to set it from
llm[0].is_tools; then replace the duplicated 6-line blocks in
get_model_config_by_id, get_model_config_by_type_and_name, and
TenantLLMService.get_model_config to call this new helper and return its result.

Comment on lines +37 to +71
@staticmethod
def _decode_api_key_config(raw_api_key: str) -> tuple[str, bool | None, str | None]:
if not raw_api_key:
return raw_api_key, None, None

try:
parsed = json.loads(raw_api_key)
except Exception:
return raw_api_key, None, None

if not isinstance(parsed, dict):
return raw_api_key, None, None

is_tools = bool(parsed["is_tools"]) if "is_tools" in parsed else None
if set(parsed.keys()) <= {"api_key", "is_tools"}:
return parsed.get("api_key", ""), is_tools, None

return parsed.get("api_key", raw_api_key), is_tools, raw_api_key

@staticmethod
def _encode_api_key_config(raw_api_key: str, is_tools: bool | None) -> str:
if is_tools is None:
return raw_api_key

try:
parsed = json.loads(raw_api_key or "{}")
except Exception:
parsed = None

if isinstance(parsed, dict):
payload = dict(parsed)
payload["is_tools"] = bool(is_tools)
return json.dumps(payload)

return json.dumps({"api_key": raw_api_key or "", "is_tools": bool(is_tools)})

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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Promote these helpers to a public API.

_decode_api_key_config / _encode_api_key_config carry a leading underscore (private-by-convention) but are imported and called from api/db/joint_services/tenant_model_service.py and api/apps/llm_app.py. If they're part of the cross-module contract, drop the underscore (e.g., decode_api_key_config / encode_api_key_config) so callers aren't reaching into "private" surface area.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/db/services/tenant_llm_service.py` around lines 37 - 71, The helper
functions _decode_api_key_config and _encode_api_key_config are used across
modules but are named as private; rename them to decode_api_key_config and
encode_api_key_config and update all callers to use the new names (references in
tenant_model_service.py and api/apps/llm_app.py). Change the function
definitions in tenant_llm_service.py (remove leading underscores) and update any
imports or from ... import ... lines to import the new names; also update any
module-level exports (e.g., __all__) or type hints if present to reflect the
public names so the cross-module contract is consistent.

Comment on lines +56 to +71
@staticmethod
def _encode_api_key_config(raw_api_key: str, is_tools: bool | None) -> str:
if is_tools is None:
return raw_api_key

try:
parsed = json.loads(raw_api_key or "{}")
except Exception:
parsed = None

if isinstance(parsed, dict):
payload = dict(parsed)
payload["is_tools"] = bool(is_tools)
return json.dumps(payload)

return json.dumps({"api_key": raw_api_key or "", "is_tools": bool(is_tools)})

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find all ChatModel constructors that parse a JSON-formatted api_key, to assess robustness against an extra is_tools field.
rg -nP --type=py -C5 '\bjson\.loads\s*\(\s*(self\.)?(api_key|key)' rag/llm/

Repository: infiniflow/ragflow

Length of output: 16367


🏁 Script executed:

# Find all usages of _encode_api_key_config
rg -n '_encode_api_key_config' --type=py

Repository: infiniflow/ragflow

Length of output: 311


🏁 Script executed:

# Find where api_key_payload is used or decoded in the read path
rg -n 'api_key_payload|model_instance' api/db/services/ --type=py -A 3 -B 3

Repository: infiniflow/ragflow

Length of output: 2812


🏁 Script executed:

# Check if any constructor performs strict key validation
rg -n 'json\.loads.*\{' rag/llm/chat_model.py -A 10 | head -100

Repository: infiniflow/ragflow

Length of output: 44


🏁 Script executed:

# Find the _decode_api_key_config method to understand the decode logic
rg -n '_decode_api_key_config' api/db/services/tenant_llm_service.py -A 20

Repository: infiniflow/ragflow

Length of output: 2179


🏁 Script executed:

# Verify the complete flow by viewing the relevant section of tenant_llm_service.py
sed -n '56,100p' api/db/services/tenant_llm_service.py

Repository: infiniflow/ragflow

Length of output: 1689


🏁 Script executed:

# Also check the decode method more thoroughly
sed -n '72,130p' api/db/services/tenant_llm_service.py

Repository: infiniflow/ragflow

Length of output: 2454


Separate is_tools from composite credential payloads to avoid future breakage.

For factories whose api_key is stored as composite JSON (e.g., VolcEngine: {"ark_api_key", "endpoint_id"}; Bedrock: {"auth_mode", "bedrock_ak", ...}), _encode_api_key_config injects is_tools into the credential dict. On the read path (model_instance), the contaminated JSON is passed directly to provider constructors. While current constructors use .get() to extract only known fields and tolerate the extra key, this design is fragile — any future provider adding strict validation would break. Consider wrapping as {"api_key_payload": <original>, "is_tools": <bool>} to keep credentials unmutated.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/db/services/tenant_llm_service.py` around lines 56 - 71, The
_encode_api_key_config function mutates composite credential dicts by injecting
"is_tools", which can break strict provider validation; change it so that for
dict payloads and non-dict raw_api_key you do not mutate the original
credentials but wrap them in a container like {"api_key_payload":
<original_payload_or_string>, "is_tools": bool(is_tools)}; specifically, in
_encode_api_key_config replace the logic that sets payload["is_tools"] with
building and returning a wrapper dict containing api_key_payload set to the
original parsed dict (or the raw_api_key string when parsed is not a dict) and
is_tools as a boolean, serializing that wrapper to JSON.

const getOptions = (factory: string) => {
return optionsMap[factory as LLMFactory] || optionsMap.Default;
};
const defaultToolCallEnabled = initialValues?.is_tools ?? false;

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

find . -path "*web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx"

Repository: infiniflow/ragflow

Length of output: 134


🏁 Script executed:

wc -l web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx

Repository: infiniflow/ragflow

Length of output: 136


🏁 Script executed:

sed -n '100,150p' web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx

Repository: infiniflow/ragflow

Length of output: 1522


🏁 Script executed:

sed -n '200,240p' web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx

Repository: infiniflow/ragflow

Length of output: 1377


🏁 Script executed:

sed -n '110,230p' web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx

Repository: infiniflow/ragflow

Length of output: 3682


🏁 Script executed:

rg -n "defaultToolCallEnabled" web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx

Repository: infiniflow/ragflow

Length of output: 183


Add initialValues to the fields memo dependencies.

defaultToolCallEnabled reads from initialValues?.is_tools and is used as the defaultValue for the is_tools field. Without initialValues in the dependency array, the memo won't recompute when switching between different items in edit mode, leaving stale switch defaults.

Suggested fix
-  }, [llmFactory, t]);
+  }, [llmFactory, t, initialValues]);

Also applies to: 220-220

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx` at
line 118, The fields useMemo that defines defaultToolCallEnabled (reading
initialValues?.is_tools) must include initialValues in its dependency array so
the memo recomputes when switching edited items; update the dependency list for
the memo that declares defaultToolCallEnabled (and any other memo at the second
occurrence around the is_tools field) to reference initialValues (or
initialValues.is_tools) along with existing deps so the defaultValue for the
is_tools field is not stale.

@codecov

codecov Bot commented May 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (12f80f1) to head (1489201).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14616   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Lynn-Inf Lynn-Inf 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.

LGTM

@wangq8
wangq8 merged commit 0501134 into infiniflow:main May 7, 2026
1 check passed
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### What problem does this PR solve?
support tool call config

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants