Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(agent): port Sofya search tool to Go (#20410)

Yusuf Gürdoğanc5abcc7d617a
diff --git a/docs/guides/agent/agent_workflow/tool_components.md b/docs/guides/agent/agent_workflow/tool_components.md
index bd9e45fef3..81d2125464 100644
--- a/docs/guides/agent/agent_workflow/tool_components.md
+++ b/docs/guides/agent/agent_workflow/tool_components.md
@@ -16,7 +16,7 @@ Tool components connect external search, databases, HTTP APIs, email sending, do
| Tool Category | Typical Components | Use Case |
| --- | --- | --- |
-| Web search | Tavily, Google, DuckDuckGo, SearXNG, Keenable | Retrieve web pages, news, public information, or content from specified sites. |
+| Web search | Tavily, Google, DuckDuckGo, SearXNG, Keenable, Sofya | Retrieve web pages, news, public information, or content from specified sites. |
| Academic search | Google Scholar, ArXiv, PubMed, BGPT | Retrieve papers, medical literature, and research materials. |
| Data and financial queries | Execute SQL, Yahoo Finance, WenCai | Query databases, market data, or financial screening results. |
| Content output | Email, Document Generator | Send emails or generate downloadable documents. |
@@ -225,6 +225,34 @@ The output contains search entries, summaries, and links returned by Keenable. I
![Keenable Search](https://raw.githubusercontent.com/infiniflow/ragflow-docs/main/images/keenable_search.jpg)
+### Sofya
+
+Sofya is a web search API for AI Agents. It returns the text of the result pages, not only a snippet, so results can be used without a separate fetch step. An API key is required and can be created at [sofya.co](https://sofya.co).
+
+#### Parameter Description
+
+| Field | Type | Required | Default Value | Description |
+| --- | --- | --- | --- | --- |
+| query | string | Yes | `{sys.query}` | Search keywords. |
+| topic | string | No | general | `general` for web search or `news` for current events. |
+| freshness | string | No | any | Limit results by recency: `day`, `week`, `month`, `year`, or `any`. |
+| api_key | string | Node configuration | Empty | Sofya API key. |
+| search_depth | string | Node configuration | basic | `basic` returns the content of the result pages. `snippets` returns search snippets only, which is faster and cheaper. |
+| top_n | integer | Node configuration | 10 | Maximum number of results, up to 20. |
+
+#### Configuration Example
+
+| Configuration Item | Example Value |
+| --- | --- |
+| Query | RAGFlow Go release |
+| API Key | `<your-sofya-api-key>` |
+| Search Depth | basic |
+| Top N | 10 |
+
+#### Output Result
+
+The output contains titles, links, and page content returned by Sofya. Results whose page could not be read fall back to the search snippet. It can be summarized by the Agent or passed to subsequent nodes.
+
### Wikipedia
The Wikipedia component searches encyclopedia entries and extracts entry summaries. It is suitable for querying clear entities, concepts, and historical events. Query terms should be as close as possible to the entry title.
diff --git a/internal/agent/component/tool_component.go b/internal/agent/component/tool_component.go
index 5682db87d0..d2a080a427 100644
--- a/internal/agent/component/tool_component.go
+++ b/internal/agent/component/tool_component.go
@@ -139,6 +139,7 @@ var toolComponentRegistrations = []struct {
{componentName: "QueritContents", toolName: "querit_contents"},
{componentName: "QueritSearch", toolName: "querit_search"},
{componentName: "SearXNG", toolName: "searxng"},
+ {componentName: "SofyaSearch", toolName: "sofya"},
{componentName: "TavilySearch", toolName: "tavily"},
{componentName: "TavilyExtract", toolName: "tavily_extract"},
{componentName: "WenCai", toolName: "wencai"},
diff --git a/internal/agent/component/tool_component_test.go b/internal/agent/component/tool_component_test.go
index 53eb8960ed..94be864393 100644
--- a/internal/agent/component/tool_component_test.go
+++ b/internal/agent/component/tool_component_test.go
@@ -145,6 +145,13 @@ func TestToolBackedComponentRegisteredFactories(t *testing.T) {
outputKey: "json",
inputKey: "query",
},
+ {
+ name: "SofyaSearch",
+ toolName: "SofyaSearch",
+ params: map[string]any{"api_key": "stored-key", "search_depth": "snippets", "top_n": float64(3), "outputs": map[string]any{"json": map[string]any{}}},
+ outputKey: "json",
+ inputKey: "query",
+ },
{
name: "PubMed",
toolName: "PubMed",
@@ -290,7 +297,7 @@ func TestToolBackedComponentWenCaiInvoke(t *testing.T) {
}
func TestToolBackedComponentRegisteredBuildWorkflow(t *testing.T) {
- for _, componentName := range []string{"ArXiv", "BGPT", "DuckDuckGo", "Email", "Google", "GoogleScholar", "KeenableSearch", "PubMed", "QueritContents", "QueritSearch", "SearXNG", "WenCai", "TavilyExtract", "TavilySearch", "Wikipedia", "YahooFinance"} {
+ for _, componentName := range []string{"ArXiv", "BGPT", "DuckDuckGo", "Email", "Google", "GoogleScholar", "KeenableSearch", "PubMed", "QueritContents", "QueritSearch", "SearXNG", "SofyaSearch", "WenCai", "TavilyExtract", "TavilySearch", "Wikipedia", "YahooFinance"} {
t.Run(componentName, func(t *testing.T) {
c := &canvas.Canvas{
Components: map[string]canvas.CanvasComponent{
diff --git a/internal/agent/tool/registry.go b/internal/agent/tool/registry.go
index 7781eadcaa..0a2f82c325 100644
--- a/internal/agent/tool/registry.go
+++ b/internal/agent/tool/registry.go
@@ -61,6 +61,7 @@ var registry = map[string]Factory{
"search_my_dataset": buildRetrievalTool,
"search_my_dateset": buildRetrievalTool,
"searxng": buildSearXNGTool,
+ "sofya": buildSofyaTool,
"tavily": buildTavilyTool,
"tavily_extract": buildTavilyExtractTool,
"tushare": noConfig("tushare", func() einotool.BaseTool { return NewTushareTool() }),
@@ -81,6 +82,7 @@ var canvasToolNames = map[string]string{
"keenablesearch": "keenable",
"queritcontents": "querit_contents",
"queritsearch": "querit_search",
+ "sofyasearch": "sofya",
"tavilyextract": "tavily_extract",
"tavilysearch": "tavily",
"yahoofinance": "yahoo_finance",
@@ -742,6 +744,33 @@ func buildKeenableTool(params map[string]any) (einotool.BaseTool, error) {
return newKeenableTool(nil, nil, apiKey, defaults), nil
}
+func buildSofyaTool(params map[string]any) (einotool.BaseTool, error) {
+ defaults := sofyaDefaults{}
+ apiKey := ""
+ if value, ok := params["api_key"]; ok {
+ var valid bool
+ apiKey, valid = value.(string)
+ if !valid {
+ return nil, fmt.Errorf("agent tool: tool %q requires string node-level param api_key", "sofya")
+ }
+ }
+ if value, ok := params["search_depth"]; ok {
+ searchDepth, valid := value.(string)
+ if !valid || (searchDepth != "basic" && searchDepth != "snippets") {
+ return nil, fmt.Errorf("agent tool: tool %q has unsupported search_depth %v", "sofya", value)
+ }
+ defaults.SearchDepth = searchDepth
+ }
+ if value, ok := params["top_n"]; ok {
+ topN, valid := strictInt(value)
+ if !valid || topN <= 0 {
+ return nil, fmt.Errorf("agent tool: tool %q requires positive integer node-level param top_n", "sofya")
+ }
+ defaults.TopN = topN
+ }
+ return newSofyaTool(nil, apiKey, defaults), nil
+}
+
func buildWikipediaTool(params map[string]any) (einotool.BaseTool, error) {
topN := defaultWikipediaTopN
language := defaultWikipediaLanguage
diff --git a/internal/agent/tool/registry_test.go b/internal/agent/tool/registry_test.go
index f7f39575bb..2c908f72ea 100644
--- a/internal/agent/tool/registry_test.go
+++ b/internal/agent/tool/registry_test.go
@@ -50,6 +50,7 @@ func TestBuildByName_CanvasComponentNames(t *testing.T) {
{name: "KeenableSearch", wantToolName: "keenable_search"},
{name: "QueritContents", wantToolName: "querit_contents"},
{name: "QueritSearch", wantToolName: "querit_search"},
+ {name: "SofyaSearch", wantToolName: "sofya_search"},
{name: "TavilyExtract", wantToolName: "tavily_extract"},
{name: "TavilySearch", wantToolName: "tavily_search"},
{name: "YahooFinance", wantToolName: "yahoo_finance"},
@@ -163,7 +164,7 @@ func TestBuildAll_AllRegisteredTools(t *testing.T) {
"duckduckgo", "email", "exesql", "execute_sql", "github", "google",
"google_scholar", "google_scholar_search", "jin10", "keenable", "pubmed", "qweather",
"querit", "querit_contents", "querit_search",
- "retrieval", "search_my_dataset", "search_my_dateset", "searxng",
+ "retrieval", "search_my_dataset", "search_my_dateset", "searxng", "sofya",
"tavily", "tavily_extract", "tushare", "web_crawler", "wencai", "wikipedia", "wikipedia_search",
"yahoo_finance",
}
@@ -227,7 +228,7 @@ func TestToolRegistry_SchemasAreComplete(t *testing.T) {
"duckduckgo", "email", "execute_sql", "exesql", "github", "google",
"google_scholar", "google_scholar_search", "jin10", "keenable", "pubmed", "qweather",
"querit", "querit_contents", "querit_search",
- "retrieval", "search_my_dataset", "search_my_dateset", "searxng",
+ "retrieval", "search_my_dataset", "search_my_dateset", "searxng", "sofya",
"tavily", "tavily_extract", "tushare", "web_crawler", "wencai", "wikipedia", "wikipedia_search",
"yahoo_finance",
}
diff --git a/internal/agent/tool/sofya.go b/internal/agent/tool/sofya.go
new file mode 100644
index 0000000000..9dbf52bcd0
--- /dev/null
+++ b/internal/agent/tool/sofya.go
@@ -0,0 +1,409 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package tool
+
+import (
+ "context"
+ "crypto/sha1"
+ "encoding/json"
+ "fmt"
+ "math/big"
+ "net/http"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/cloudwego/eino/components/tool"
+ "github.com/cloudwego/eino/schema"
+
+ "ragflow/internal/tokenizer"
+)
+
+const sofyaToolName = "sofya_search"
+
+const sofyaToolDescription = `Sofya is a web search API for AI agents. It returns the content of the result pages, not just a snippet, so results carry usable context without a separate fetch. When searching:
+ - Use a focused query of the most important terms (and synonyms).
+ - Use the news topic for current events, and the general topic otherwise.
+ - Optionally restrict results by how recently they were published.`
+
+// sofyaMaxResults is the most results Sofya returns for one search.
+const sofyaMaxResults = 20
+
+const sofyaPromptMaxTokens = 200000
+
+// "basic" reads the result pages and returns their content; "snippets"
+// returns the search snippets only, which is faster and cheaper.
+var sofyaSearchDepths = []string{"basic", "snippets"}
+
+var sofyaTopics = []string{"general", "news"}
+
+// Sofya also accepts a date range for freshness. Only the named windows are
+// offered, so the value can be checked against a fixed list. "any" means no
+// limit and is not sent.
+var sofyaFreshnessValues = []string{"any", "day", "week", "month", "year"}
+
+// sofyaEndpoint is the Sofya search URL. Exposed as a package var so tests
+// can substitute it through rewriteHostTransport.
+var sofyaEndpoint = "https://sofya.co/v1/search"
+
+// sofyaArgs is the JSON shape the model sends into InvokableRun.
+// max_results is decoded loosely: a missing, blank or non-numeric value means
+// "use the node's Top N" rather than failing the run.
+type sofyaArgs struct {
+ Query string `json:"query"`
+ Topic string `json:"topic"`
+ Freshness string `json:"freshness"`
+ MaxResults any `json:"max_results"`
+}
+
+// sofyaDefaults holds the node-level configuration.
+type sofyaDefaults struct {
+ SearchDepth string
+ TopN int
+}
+
+type sofyaRequestBody struct {
+ Query string `json:"query"`
+ SearchDepth string `json:"search_depth"`
+ MaxResults int `json:"max_results"`
+ Topic string `json:"topic"`
+ Freshness string `json:"freshness,omitempty"`
+}
+
+// sofyaResponse preserves every upstream result field because the Canvas json
+// output exposes the result list unchanged.
+type sofyaResponse struct {
+ Results []map[string]any `json:"results"`
+}
+
+type sofyaEnvelope struct {
+ Results []map[string]any `json:"results"`
+ Error string `json:"_ERROR,omitempty"`
+}
+
+// SofyaTool is the Sofya web search tool. It POSTs a search to
+// https://sofya.co/v1/search and returns the upstream `results` array.
+// The API key is node configuration only and never model-visible.
+type SofyaTool struct {
+ helper *HTTPHelper
+ apiKey string
+ defaults sofyaDefaults
+}
+
+var _ ToolComponent = (*SofyaTool)(nil)
+var _ ReferenceBuilder = (*SofyaTool)(nil)
+
+// NewSofyaTool returns a SofyaTool with no API key and the default HTTPHelper.
+func NewSofyaTool() *SofyaTool {
+ return newSofyaTool(nil, "", sofyaDefaults{})
+}
+
+// NewSofyaToolWith returns a SofyaTool that uses the provided HTTPHelper and
+// API key. Useful for tests that want to inject a custom transport.
+func NewSofyaToolWith(h *HTTPHelper, apiKey string) *SofyaTool {
+ return newSofyaTool(h, apiKey, sofyaDefaults{})
+}
+
+func newSofyaTool(h *HTTPHelper, apiKey string, defaults sofyaDefaults) *SofyaTool {
+ if h == nil {
+ h = NewHTTPHelper()
+ }
+ if defaults.SearchDepth == "" {
+ defaults.SearchDepth = "basic"
+ }
+ if defaults.TopN <= 0 {
+ defaults.TopN = 10
+ }
+ return &SofyaTool{helper: h, apiKey: strings.TrimSpace(apiKey), defaults: defaults}
+}
+
+// Info returns the tool's metadata for the chat model.
+func (s *SofyaTool) Info(_ context.Context) (*schema.ToolInfo, error) {
+ return &schema.ToolInfo{
+ Name: sofyaToolName,
+ Desc: sofyaToolDescription,
+ ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
+ "query": {
+ Type: schema.String,
+ Desc: "The search keywords to execute with Sofya. The most important words/terms (and synonyms) from the original request.",
+ Required: true,
+ },
+ "topic": {
+ Type: schema.String,
+ Desc: `Search category: "news" for current events, "general" (default) for a broader web search.`,
+ Enum: sofyaTopics,
+ Required: false,
+ },
+ "freshness": {
+ Type: schema.String,
+ Desc: `Restrict results by recency: "day", "week", "month", "year", or "any" (default) for no limit.`,
+ Enum: sofyaFreshnessValues,
+ Required: false,
+ },
+ "max_results": {
+ Type: schema.Integer,
+ Desc: "Number of results to return, 1 to 20. Leave it out to use the Top N set on the node.",
+ Required: false,
+ },
+ }),
+ }, nil
+}
+
+// InvokableRun performs the Sofya search.
+//
+// Recoverable errors (bad arguments, missing API key, API or network failures)
+// are returned as a JSON envelope with an _ERROR field and a nil Go error, so
+// the ReAct agent feeds them back to the model instead of failing the run,
+// matching TavilyTool.
+func (s *SofyaTool) InvokableRun(ctx context.Context, argsJSON string, _ ...tool.Option) (string, error) {
+ var args sofyaArgs
+ if err := json.Unmarshal([]byte(argsJSON), &args); err != nil {
+ return sofyaErrJSON(fmt.Errorf("sofya: parse arguments: %w", err)), nil
+ }
+ if strings.TrimSpace(args.Query) == "" {
+ return sofyaJSON(sofyaEnvelope{Results: []map[string]any{}}), nil
+ }
+ if s.apiKey == "" {
+ return sofyaErrJSON(fmt.Errorf("sofya: api_key is required")), nil
+ }
+
+ topic, err := sofyaEnumArg("topic", args.Topic, sofyaTopics, "general")
+ if err != nil {
+ return sofyaErrJSON(err), nil
+ }
+ freshness, err := sofyaEnumArg("freshness", args.Freshness, sofyaFreshnessValues, "any")
+ if err != nil {
+ return sofyaErrJSON(err), nil
+ }
+ if freshness == "any" {
+ freshness = ""
+ }
+ maxResults := sofyaMaxResultsArg(args.MaxResults, s.defaults.TopN)
+
+ body, _ := json.Marshal(sofyaRequestBody{
+ Query: args.Query,
+ SearchDepth: s.defaults.SearchDepth,
+ MaxResults: maxResults,
+ Topic: topic,
+ Freshness: freshness,
+ })
+ resp, err := s.helper.Do(ctx,
+ http.MethodPost, sofyaEndpoint, string(body), "application/json",
+ map[string]string{
+ "Authorization": "Bearer " + s.apiKey,
+ "Accept": "application/json",
+ // Identifies RAGFlow to Sofya.
+ "User-Agent": "RAGFlow sofya-integration/infiniflow-ragflow",
+ },
+ )
+ if err != nil {
+ return sofyaErrJSON(err), nil
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return sofyaErrJSON(fmt.Errorf("sofya: upstream returned %d", resp.StatusCode)), nil
+ }
+
+ var raw sofyaResponse
+ if err := json.NewDecoder(resp.Body).Decode(&raw); err != nil {
+ return sofyaErrJSON(fmt.Errorf("sofya: decode response: %w", err)), nil
+ }
+ results := raw.Results
+ if results == nil {
+ results = []map[string]any{}
+ }
+ if len(results) > maxResults {
+ results = results[:maxResults]
+ }
+ return sofyaJSON(sofyaEnvelope{Results: results}), nil
+}
+
+// sofyaEnumArg normalizes a model-supplied enum value. Blank means the
+// default; anything else must be a known value, because it is forwarded to
+// Sofya as-is.
+func sofyaEnumArg(name, value string, allowed []string, fallback string) (string, error) {
+ v := strings.ToLower(strings.TrimSpace(value))
+ if v == "" {
+ return fallback, nil
+ }
+ for _, a := range allowed {
+ if v == a {
+ return v, nil
+ }
+ }
+ return "", fmt.Errorf("sofya: %s %q is not supported, it should be one of %v", name, value, allowed)
+}
+
+// sofyaMaxResultsArg returns the model's result count if it gave a usable
+// one, else the node's Top N, clamped to [1, 20].
+func sofyaMaxResultsArg(value any, topN int) int {
+ n := topN
+ switch v := value.(type) {
+ case float64:
+ n = int(v)
+ case string:
+ if parsed, err := strconv.Atoi(strings.TrimSpace(v)); err == nil {
+ n = parsed
+ }
+ }
+ return min(max(n, 1), sofyaMaxResults)
+}
+
+// ComponentSpec returns the SofyaSearch Canvas surface.
+func (s *SofyaTool) ComponentSpec() ComponentSpec {
+ return ComponentSpec{
+ Inputs: map[string]string{
+ "query": "The search keywords to execute with Sofya.",
+ "topic": `Search topic: "general" or "news".`,
+ "freshness": `Recency limit: "day", "week", "month", "year" or "any".`,
+ },
+ Outputs: map[string]string{
+ "formalized_content": "Rendered Sofya references for downstream prompts.",
+ "json": "Raw Sofya result list.",
+ },
+ InputForm: map[string]any{
+ "query": map[string]any{"name": "Query", "type": "line"},
+ "topic": map[string]any{
+ "name": "Topic",
+ "type": "options",
+ "value": "general",
+ "options": sofyaTopics,
+ },
+ "freshness": map[string]any{
+ "name": "Freshness",
+ "type": "options",
+ "value": "any",
+ "options": sofyaFreshnessValues,
+ },
+ },
+ }
+}
+
+func (s *SofyaTool) BuildReferences(_ context.Context, envelope map[string]any) ([]map[string]any, []map[string]any) {
+ return buildSofyaReferences(envelope)
+}
+
+func (s *SofyaTool) BuildComponentOutputs(envelope map[string]any) map[string]any {
+ results := envelopeSlice(envelope, "results")
+ chunks, _ := buildSofyaReferences(envelope)
+ return map[string]any{
+ "formalized_content": renderSofyaReferences(chunks, sofyaPromptMaxTokens),
+ "json": results,
+ }
+}
+
+// buildSofyaReferences prefers a result's page content and falls back to its
+// search snippet. `content` is empty when the page was not read (and always in
+// snippets mode); `description` is the snippet. A result with neither is
+// dropped rather than stored as a blank chunk.
+func buildSofyaReferences(envelope map[string]any) ([]map[string]any, []map[string]any) {
+ results := envelopeSlice(envelope, "results")
+ chunks := make([]map[string]any, 0, len(results))
+ docAggs := make([]map[string]any, 0, len(results))
+ for _, item := range results {
+ result, ok := item.(map[string]any)
+ if !ok {
+ continue
+ }
+ content := sofyaText(result["content"])
+ if content == "" {
+ content = sofyaText(result["description"])
+ }
+ content = truncateSofyaRunes(strings.Join(strings.Fields(content), " "), 10000)
+ if content == "" {
+ continue
+ }
+ documentID := strconv.FormatInt(sofyaHashInt(content, 100000000), 10)
+ displayID := strconv.FormatInt(sofyaHashInt(documentID, 500), 10)
+ title := sofyaText(result["title"])
+ resultURL := sofyaText(result["url"])
+ chunks = append(chunks, map[string]any{
+ "id": displayID,
+ "chunk_id": documentID,
+ "content": content,
+ "doc_id": documentID,
+ "document_id": documentID,
+ "docnm_kwd": title,
+ "document_name": title,
+ "similarity": 1,
+ "score": 1,
+ "url": resultURL,
+ })
+ docAggs = append(docAggs, map[string]any{
+ "doc_name": title,
+ "doc_id": documentID,
+ "count": 1,
+ "url": resultURL,
+ })
+ }
+ return chunks, docAggs
+}
+
+func renderSofyaReferences(chunks []map[string]any, maxTokens int) string {
+ usedTokens := 0
+ blocks := make([]string, 0, len(chunks))
+ for _, chunk := range chunks {
+ content := sofyaText(chunk["content"])
+ usedTokens += tokenizer.NumTokensFromString(content)
+ blocks = append(blocks, strings.Join([]string{
+ "\nID: " + sofyaText(chunk["id"]),
+ "├── Title: " + strings.Join(strings.Fields(sofyaText(chunk["document_name"])), " "),
+ "├── URL: " + sofyaText(chunk["url"]),
+ "└── Content:\n" + content,
+ }, "\n"))
+ if maxTokens > 0 && float64(maxTokens)*0.97 < float64(usedTokens) {
+ break
+ }
+ }
+ return strings.Join(blocks, "\n")
+}
+
+func sofyaText(value any) string {
+ if value == nil {
+ return ""
+ }
+ if text, ok := value.(string); ok {
+ return strings.TrimSpace(text)
+ }
+ return strings.TrimSpace(fmt.Sprint(value))
+}
+
+func sofyaHashInt(value string, modulus int64) int64 {
+ digest := sha1.Sum([]byte(value))
+ number := new(big.Int).SetBytes(digest[:])
+ return new(big.Int).Mod(number, big.NewInt(modulus)).Int64()
+}
+
+func truncateSofyaRunes(value string, limit int) string {
+ if utf8.RuneCountInString(value) <= limit {
+ return value
+ }
+ return string([]rune(value)[:limit])
+}
+
+func sofyaJSON(env sofyaEnvelope) string {
+ b, err := json.Marshal(env)
+ if err != nil {
+ return fmt.Sprintf(`{"_ERROR":"sofya: marshal result: %s"}`, err)
+ }
+ return string(b)
+}
+
+func sofyaErrJSON(err error) string {
+ return sofyaJSON(sofyaEnvelope{Error: err.Error()})
+}
diff --git a/internal/agent/tool/sofya_test.go b/internal/agent/tool/sofya_test.go
new file mode 100644
index 0000000000..227963ee2e
--- /dev/null
+++ b/internal/agent/tool/sofya_test.go
@@ -0,0 +1,254 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package tool
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+)
+
+// sofyaTestServer records the last request and answers with the given
+// status and body.
+func sofyaTestServer(t *testing.T, status int, respBody string) (*HTTPHelper, *http.Request, *map[string]any, *atomic.Int32) {
+ t.Helper()
+ var gotReq http.Request
+ gotBody := map[string]any{}
+ calls := &atomic.Int32{}
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ calls.Add(1)
+ gotReq = *r.Clone(r.Context())
+ gotBody = map[string]any{}
+ _ = json.NewDecoder(r.Body).Decode(&gotBody)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(respBody))
+ }))
+ t.Cleanup(srv.Close)
+ helper := NewHTTPHelper().WithClient(&http.Client{Transport: rewriteHostTransport(srv.URL)})
+ return helper, &gotReq, &gotBody, calls
+}
+
+func decodeSofyaEnvelope(t *testing.T, out string) sofyaEnvelope {
+ t.Helper()
+ var env sofyaEnvelope
+ if err := json.Unmarshal([]byte(out), &env); err != nil {
+ t.Fatalf("decode envelope %q: %v", out, err)
+ }
+ return env
+}
+
+func TestSofya_BuildRequest(t *testing.T) {
+ t.Parallel()
+ helper, req, body, _ := sofyaTestServer(t, http.StatusOK, `{"results":[]}`)
+ tool := newSofyaTool(helper, " key-xyz ", sofyaDefaults{SearchDepth: "snippets", TopN: 5})
+
+ out, err := tool.InvokableRun(t.Context(), `{"query":"ragflow go","topic":"News","freshness":"week"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if env := decodeSofyaEnvelope(t, out); env.Error != "" {
+ t.Fatalf("unexpected _ERROR %q", env.Error)
+ }
+ if req.Method != http.MethodPost || req.URL.Path != "/v1/search" {
+ t.Errorf("request = %s %s, want POST /v1/search", req.Method, req.URL.Path)
+ }
+ if got := req.Header.Get("Authorization"); got != "Bearer key-xyz" {
+ t.Errorf("Authorization = %q, want trimmed bearer key", got)
+ }
+ if got := req.Header.Get("User-Agent"); got != "RAGFlow sofya-integration/infiniflow-ragflow" {
+ t.Errorf("User-Agent = %q", got)
+ }
+ want := map[string]any{
+ "query": "ragflow go", "search_depth": "snippets", "max_results": float64(5),
+ "topic": "news", "freshness": "week",
+ }
+ for k, v := range want {
+ if (*body)[k] != v {
+ t.Errorf("body.%s = %v, want %v", k, (*body)[k], v)
+ }
+ }
+}
+
+func TestSofya_DefaultsOmitFreshness(t *testing.T) {
+ t.Parallel()
+ helper, _, body, _ := sofyaTestServer(t, http.StatusOK, `{"results":[]}`)
+ tool := NewSofyaToolWith(helper, "key")
+
+ if _, err := tool.InvokableRun(t.Context(), `{"query":"q","freshness":"any"}`); err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if _, ok := (*body)["freshness"]; ok {
+ t.Errorf("freshness sent for \"any\": %v", (*body)["freshness"])
+ }
+ if (*body)["search_depth"] != "basic" || (*body)["topic"] != "general" || (*body)["max_results"] != float64(10) {
+ t.Errorf("defaults = %v, want basic/general/10", *body)
+ }
+}
+
+func TestSofya_MaxResultsArg(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ value any
+ want int
+ }{
+ {nil, 7}, // not given: node Top N
+ {"", 7}, // blank: node Top N
+ {"lots", 7}, // unparseable: node Top N
+ {float64(3), 3}, // model's value wins
+ {"4", 4}, // numeric string
+ {float64(0), 1}, // clamped low
+ {float64(99), 20}, // clamped to Sofya's max
+ }
+ for _, tc := range cases {
+ if got := sofyaMaxResultsArg(tc.value, 7); got != tc.want {
+ t.Errorf("sofyaMaxResultsArg(%#v, 7) = %d, want %d", tc.value, got, tc.want)
+ }
+ }
+}
+
+func TestSofya_ErrorsReachTheModel(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name, key, args, wantErr string
+ status int
+ wantCalls int32
+ }{
+ {"no api key", "", `{"query":"q"}`, "api_key is required", http.StatusOK, 0},
+ {"unknown topic", "key", `{"query":"q","topic":"sports"}`, `topic "sports" is not supported`, http.StatusOK, 0},
+ {"unknown freshness", "key", `{"query":"q","freshness":"decade"}`, `freshness "decade" is not supported`, http.StatusOK, 0},
+ {"bad arguments", "key", `{"query":`, "parse arguments", http.StatusOK, 0},
+ {"rejected key", "key", `{"query":"q"}`, "upstream returned 401", http.StatusUnauthorized, 1},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ helper, _, _, calls := sofyaTestServer(t, tc.status, `{"detail":"nope"}`)
+ out, err := NewSofyaToolWith(helper, tc.key).InvokableRun(t.Context(), tc.args)
+ if err != nil {
+ t.Fatalf("Go error %v: recoverable errors must go back to the model", err)
+ }
+ if env := decodeSofyaEnvelope(t, out); !strings.Contains(env.Error, tc.wantErr) {
+ t.Errorf("_ERROR = %q, want it to contain %q", env.Error, tc.wantErr)
+ }
+ if got := calls.Load(); got != tc.wantCalls {
+ t.Errorf("upstream calls = %d, want %d", got, tc.wantCalls)
+ }
+ })
+ }
+}
+
+func TestSofya_EmptyQueryReturnsEmptyResults(t *testing.T) {
+ t.Parallel()
+ helper, _, _, calls := sofyaTestServer(t, http.StatusOK, `{"results":[]}`)
+ out, err := NewSofyaToolWith(helper, "key").InvokableRun(t.Context(), `{"query":" "}`)
+ if err != nil || out != `{"results":[]}` {
+ t.Fatalf("out, err = %q, %v; want empty results", out, err)
+ }
+ if calls.Load() != 0 {
+ t.Error("an empty query must not reach the API")
+ }
+}
+
+func TestSofya_KeepsRawResultsUpToMaxResults(t *testing.T) {
+ t.Parallel()
+ helper, _, _, _ := sofyaTestServer(t, http.StatusOK,
+ `{"results":[{"title":"A","url":"https://a","fetched":true},{"title":"B"},{"title":"C"}],"credits_used":2}`)
+ out, err := NewSofyaToolWith(helper, "key").InvokableRun(t.Context(), `{"query":"q","max_results":2}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ env := decodeSofyaEnvelope(t, out)
+ if len(env.Results) != 2 || env.Results[0]["fetched"] != true {
+ t.Fatalf("results = %#v, want the first 2 results with fields intact", env.Results)
+ }
+}
+
+func TestSofya_ComponentReferencesAndOutputs(t *testing.T) {
+ t.Parallel()
+ envelope := map[string]any{"results": []any{
+ map[string]any{"title": "Page", "url": "https://p", "content": " page\n\n text ", "description": "snippet"},
+ map[string]any{"title": "Snippet only", "url": "https://s", "content": "", "description": "just a snippet"},
+ map[string]any{"title": "Empty", "url": "https://e"},
+ "not a result",
+ }}
+ tool := NewSofyaTool()
+
+ chunks, docAggs := tool.BuildReferences(t.Context(), envelope)
+ if len(chunks) != 2 || len(docAggs) != 2 {
+ t.Fatalf("got %d chunks / %d docs, want 2 / 2 (empty result dropped)", len(chunks), len(docAggs))
+ }
+ if chunks[0]["content"] != "page text" {
+ t.Errorf("chunk 0 content = %q, want page content with whitespace collapsed", chunks[0]["content"])
+ }
+ if chunks[1]["content"] != "just a snippet" {
+ t.Errorf("chunk 1 content = %q, want the snippet fallback", chunks[1]["content"])
+ }
+ if chunks[0]["url"] != "https://p" || docAggs[0]["doc_name"] != "Page" {
+ t.Errorf("chunk 0 = %#v / %#v", chunks[0], docAggs[0])
+ }
+
+ outputs := tool.BuildComponentOutputs(envelope)
+ rendered, _ := outputs["formalized_content"].(string)
+ for _, want := range []string{"├── Title: Page", "├── URL: https://p", "└── Content:\npage text", "just a snippet"} {
+ if !strings.Contains(rendered, want) {
+ t.Errorf("formalized_content missing %q:\n%s", want, rendered)
+ }
+ }
+ if raw, _ := outputs["json"].([]any); len(raw) != 4 {
+ t.Errorf("json output = %#v, want the raw result list", outputs["json"])
+ }
+}
+
+func TestSofya_BuildByNameUsesNodeConfig(t *testing.T) {
+ t.Parallel()
+ built, err := BuildByName("SofyaSearch", map[string]any{
+ "api_key": "stored-key", "search_depth": "snippets", "top_n": float64(4),
+ "query": "{sys.query}", "outputs": map[string]any{},
+ })
+ if err != nil {
+ t.Fatalf("BuildByName: %v", err)
+ }
+ tool, ok := built.(*SofyaTool)
+ if !ok {
+ t.Fatalf("built %T, want *SofyaTool", built)
+ }
+ if tool.apiKey != "stored-key" || tool.defaults != (sofyaDefaults{SearchDepth: "snippets", TopN: 4}) {
+ t.Errorf("tool = key %q defaults %+v", tool.apiKey, tool.defaults)
+ }
+ info, err := tool.Info(t.Context())
+ if err != nil || info.Name != sofyaToolName {
+ t.Fatalf("Info = %+v, %v", info, err)
+ }
+}
+
+func TestSofya_BuildByNameRejectsInvalidNodeConfig(t *testing.T) {
+ t.Parallel()
+ for name, params := range map[string]map[string]any{
+ "api_key not a string": {"api_key": 42},
+ "unknown search_depth": {"search_depth": "advanced"},
+ "zero top_n": {"top_n": float64(0)},
+ "fractional top_n": {"top_n": 2.5},
+ } {
+ if _, err := BuildByName("sofya", params); err == nil {
+ t.Errorf("%s: expected a config error", name)
+ }
+ }
+}