Skip to content

fix: unable to use agent in agent - #16910

Merged
yuzhichang merged 3 commits into
infiniflow:mainfrom
Haruko386:make
Jul 15, 2026
Merged

yuzhichang merged 3 commits into
infiniflow:mainfrom
Haruko386:make

Conversation

@Haruko386

Copy link
Copy Markdown
Member

Summary

As title

Agent:

image

Data_operations

image

@Haruko386 Haruko386 added 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration labels Jul 14, 2026
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 14, 2026
@Haruko386
Haruko386 marked this pull request as draft July 14, 2026 11:30
@Haruko386
Haruko386 marked this pull request as ready for review July 14, 2026 11:30
@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

AgentComponent.Invoke resolves bare tenant chat models and applies their configuration. DataOperationsComponent parses query references into input definitions but currently returns an empty map. DebugComponent records invocation elapsed time.

Changes

Tenant chat model resolution

Layer / File(s) Summary
Tenant model lookup and credential resolution
internal/agent/component/llm_credentials.go
Adds direct and instance-based tenant chat-model lookup, active-model validation, and API key/base URL extraction.
Invocation configuration integration
internal/agent/component/agent.go
Applies resolved model, driver, API key, and base URL values before LLM configuration resolution.

Component input and debug observability

Layer / File(s) Summary
Dynamic data-operation input forms
internal/agent/component/data_operations.go
Parses query variable references and builds line-input definitions locally, but returns an empty map.
Debug invocation timing
internal/handler/agent_component.go
Wraps component invocation with runtime.TrackElapsed while retaining outputs and error handling.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AgentComponent
  participant TenantModel
  participant TenantModelInstance
  AgentComponent->>TenantModel: resolve tenant chat model by ID
  TenantModel-->>AgentComponent: return configuration or not found
  AgentComponent->>TenantModelInstance: resolve instance fallback
  TenantModelInstance-->>AgentComponent: return active model and credentials
  AgentComponent->>AgentComponent: apply model, driver, API key, and base URL
Loading

Possibly related PRs

  • infiniflow/ragflow#16606: Sets the tenant state used by tenant chat-model resolution during debug component invocation.

Suggested reviewers: paulhuiseismic

Poem

A rabbit hops through models bright,
Finding tenant keys just right.
Query refs line up neat,
Timed calls tap their feet.
Empty forms still greet the night.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description only says "As title" and depends on screenshots, so it lacks the required summary and background context. Replace "As title" with a brief summary of the issue, what changed, and any important context or caveats.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and matches the main fix: enabling an agent to be used inside another agent.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

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.

@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: 2

🧹 Nitpick comments (3)
internal/agent/component/data_operations.go (1)

298-312: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Simplify redundant string concatenation.

The logic slicing exp around @ to compute cpnID and varName and then reconstructing them via cpnID + "@" + varName evaluates to the exact original exp string. This can be simplified to improve readability.

♻️ Proposed fix
-		cpnID, varName := "", exp
-		if at := strings.Index(exp, "@"); at > 0 {
-			cpnID = exp[:at]
-			varName = exp[at+1:]
-		}
-		name := exp
-		if cpnID != "" {
-			name = cpnID + "@" + varName
-		}
-		res[exp] = map[string]any{
-			"name":       name,
-			"value":      nil,
-			"_retrieval": nil,
-			"_cpn_id":    cpnID,
-		}
+		cpnID := ""
+		if at := strings.Index(exp, "@"); at > 0 {
+			cpnID = exp[:at]
+		}
+		res[exp] = map[string]any{
+			"name":       exp,
+			"value":      nil,
+			"_retrieval": nil,
+			"_cpn_id":    cpnID,
+		}
🤖 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 `@internal/agent/component/data_operations.go` around lines 298 - 312, In the
expression-processing block, simplify the conditional name assignment by using
the original exp value directly instead of reconstructing it from cpnID and
varName. Preserve the existing cpnID parsing and _cpn_id field behavior, and
remove only the redundant name concatenation logic.
internal/agent/component/llm_credentials.go (1)

208-213: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid shadowing the imported models package.

The local variable models shadows the imported package "ragflow/internal/entity/models". Consider renaming it (e.g., to tenantModels) to prevent confusion and potential compilation errors if the package is referenced later in the function.

♻️ Proposed refactor
-	models, err := dao.NewTenantModelDAO().GetModelsByInstanceID(instance.ID)
+	tenantModels, err := dao.NewTenantModelDAO().GetModelsByInstanceID(instance.ID)
 	if err != nil {
 		return "", "", apiKey, baseURL, false, fmt.Errorf("resolve models for tenant model instance id %q: %w", instanceID, err)
 	}
-	candidates := make([]*entity.TenantModel, 0, len(models))
-	for _, model := range models {
+	candidates := make([]*entity.TenantModel, 0, len(tenantModels))
+	for _, model := range tenantModels {
🤖 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 `@internal/agent/component/llm_credentials.go` around lines 208 - 213, Rename
the local result variable in the model-resolution flow around
GetModelsByInstanceID from models to tenantModels, and update its length and
iteration references accordingly, preserving the existing behavior and imported
models package access.
internal/agent/component/agent.go (1)

461-478: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Merge redundant conditional checks.

The condition if p.Driver == "" && p.ModelID != "" is evaluated twice consecutively. Assuming agentProviderLastSegmentSplit populates p.Driver on success, the second block can be merged into an else branch of the first condition's inner if to simplify the flow and avoid redundant checks.

♻️ Proposed refactor
 	if p.Driver == "" && p.ModelID != "" {
 		if m, prov, ok := agentProviderLastSegmentSplit(p.ModelID); ok {
 			p.Driver = prov
 			p.ModelID = m
-		}
-	}
-	if p.Driver == "" && p.ModelID != "" {
-		modelID, driver, apiKey, baseURL, ok, err := resolveTenantChatModelByID(ctx, p.ModelID, p.APIKey, p.BaseURL)
-		if err != nil {
-			return nil, err
-		}
-		if ok {
-			p.ModelID = modelID
-			p.Driver = driver
-			p.APIKey = apiKey
-			p.BaseURL = baseURL
-		}
+		} else {
+			modelID, driver, apiKey, baseURL, ok, err := resolveTenantChatModelByID(ctx, p.ModelID, p.APIKey, p.BaseURL)
+			if err != nil {
+				return nil, err
+			}
+			if ok {
+				p.ModelID = modelID
+				p.Driver = driver
+				p.APIKey = apiKey
+				p.BaseURL = baseURL
+			}
+		}
 	}
🤖 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 `@internal/agent/component/agent.go` around lines 461 - 478, Merge the
consecutive conditionals in the model/provider resolution flow: within the outer
`p.Driver == "" && p.ModelID != ""` check, run `resolveTenantChatModelByID` in
an else branch when `agentProviderLastSegmentSplit` does not succeed. Preserve
the existing assignments and error return behavior.
🤖 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 `@internal/agent/component/data_operations.go`:
- Around line 272-284: Update DataOperationsComponent.GetInputForm to initialize
an output map, add each matched variable reference and its corresponding
name/type entry while iterating through all query inputs, and return the
accumulated map only after both loops complete; preserve the empty-map result
when no inputs match.
- Around line 286-287: Remove the TODO comment and its accompanying explanation
about moving the logic later from the affected data-operations code, leaving the
implementation unchanged.

---

Nitpick comments:
In `@internal/agent/component/agent.go`:
- Around line 461-478: Merge the consecutive conditionals in the model/provider
resolution flow: within the outer `p.Driver == "" && p.ModelID != ""` check, run
`resolveTenantChatModelByID` in an else branch when
`agentProviderLastSegmentSplit` does not succeed. Preserve the existing
assignments and error return behavior.

In `@internal/agent/component/data_operations.go`:
- Around line 298-312: In the expression-processing block, simplify the
conditional name assignment by using the original exp value directly instead of
reconstructing it from cpnID and varName. Preserve the existing cpnID parsing
and _cpn_id field behavior, and remove only the redundant name concatenation
logic.

In `@internal/agent/component/llm_credentials.go`:
- Around line 208-213: Rename the local result variable in the model-resolution
flow around GetModelsByInstanceID from models to tenantModels, and update its
length and iteration references accordingly, preserving the existing behavior
and imported models package access.
🪄 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: ddef2013-2ef7-4c93-b367-28bb608baf28

📥 Commits

Reviewing files that changed from the base of the PR and between 26161ce and 7ea0439.

📒 Files selected for processing (4)
  • internal/agent/component/agent.go
  • internal/agent/component/data_operations.go
  • internal/agent/component/llm_credentials.go
  • internal/handler/agent_component.go

@Haruko386
Haruko386 marked this pull request as draft July 14, 2026 12:29
@Haruko386
Haruko386 marked this pull request as ready for review July 15, 2026 01:36

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/agent/component/data_operations.go (1)

272-283: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Return the accumulated map instead of an empty map.

The function populates the res map with input elements but discards it by returning an empty map at the end. This completely nullifies the fix made to the loop and will cause the data operations component to expose an empty input form.

🐛 Proposed fix
 func (d *DataOperationsComponent) GetInputForm() map[string]any {
 	res := make(map[string]any)
 	for _, input := range d.param.Query {
 		for k, v := range getInputElementsFromText(input) {
 			res[k] = map[string]any{
 				"name": v["name"],
 				"type": "line",
 			}
 		}
 	}
-	return map[string]any{}
+	return res
 }
🤖 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 `@internal/agent/component/data_operations.go` around lines 272 - 283, Update
DataOperationsComponent.GetInputForm to return the populated res map instead of
creating and returning a new empty map, preserving the accumulated input
elements from the loop.
🤖 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.

Outside diff comments:
In `@internal/agent/component/data_operations.go`:
- Around line 272-283: Update DataOperationsComponent.GetInputForm to return the
populated res map instead of creating and returning a new empty map, preserving
the accumulated input elements from the loop.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fd754ab4-0068-45ad-9d28-b269fd66455b

📥 Commits

Reviewing files that changed from the base of the PR and between 7ea0439 and b25931d.

📒 Files selected for processing (1)
  • internal/agent/component/data_operations.go

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/agent/component/llm_credentials.go (1)

272-275: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Prevent silent JSON unmarshaling failures for mixed-type objects.

If instance.Extra contains non-string values (e.g., numbers, booleans, or nested configurations like {"timeout": 30, "base_url": "..."}), unmarshaling it directly into a map[string]string will fail. Because the error is ignored, this will silently leave baseURL empty even if the "base_url" key is present.

Use map[string]any to safely parse arbitrary JSON and perform a type assertion for base_url.

🛠️ Proposed fix
-		var extra map[string]string
-		if err := json.Unmarshal([]byte(instance.Extra), &extra); err == nil {
-			baseURL = extra["base_url"]
-		}
+		var extra map[string]any
+		if err := json.Unmarshal([]byte(instance.Extra), &extra); err == nil {
+			if val, ok := extra["base_url"].(string); ok {
+				baseURL = val
+			}
+		}
🤖 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 `@internal/agent/component/llm_credentials.go` around lines 272 - 275, Update
the Extra parsing in the credential-loading flow to unmarshal into
map[string]any instead of map[string]string, allowing mixed-type JSON fields.
Then retrieve extra["base_url"] with a string type assertion and assign baseURL
only when the assertion succeeds, preserving the existing behavior for valid
string values.
🤖 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.

Outside diff comments:
In `@internal/agent/component/llm_credentials.go`:
- Around line 272-275: Update the Extra parsing in the credential-loading flow
to unmarshal into map[string]any instead of map[string]string, allowing
mixed-type JSON fields. Then retrieve extra["base_url"] with a string type
assertion and assign baseURL only when the assertion succeeds, preserving the
existing behavior for valid string values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 538169d8-d6b6-4592-87b7-27393bc34c9e

📥 Commits

Reviewing files that changed from the base of the PR and between b25931d and 8cc71de.

📒 Files selected for processing (1)
  • internal/agent/component/llm_credentials.go

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

fixed

@yuzhichang

Copy link
Copy Markdown
Member

LGTM

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.

2 participants