Skip to content

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

fix(agent): resolve DeepL and QWeather credentials from node config or DEEPL_API_KEY/QWEATHER_API_KEY instead of model-visible params (#21735)

ciele37ea7ec03ac
diff --git a/internal/agent/tool/deepl.go b/internal/agent/tool/deepl.go
index a9df7f0185..c11b9ed033 100644
--- a/internal/agent/tool/deepl.go
+++ b/internal/agent/tool/deepl.go
@@ -26,6 +26,8 @@ import (
"github.com/cloudwego/eino/components/tool"
"github.com/cloudwego/eino/schema"
+
+ "ragflow/internal/common"
)
const deeplToolName = "deepl"
@@ -34,7 +36,6 @@ const deeplToolDescription = "Translate text via the DeepL API. Returns translat
// deeplParams is the JSON shape the model sends into InvokableRun.
type deeplParams struct {
- APIKey string `json:"api_key"`
Text string `json:"text"`
SourceLang string `json:"source_lang"`
TargetLang string `json:"target_lang"`
@@ -68,23 +69,33 @@ var deeplProEndpoint = "https://api.deepl.com/v2/translate"
// DeepLTool is the DeepL
// translation tool. It POSTs
// a translation request to the DeepL /v2/translate endpoint via the
-// shared HTTPHelper.
+// shared HTTPHelper. The API key is a server-side credential: it never
+// appears in the model-facing tool params.
type DeepLTool struct {
helper *HTTPHelper
+ apiKey string
}
-// NewDeepLTool returns a DeepLTool using the default HTTPHelper.
+// NewDeepLTool returns a DeepLTool using the default HTTPHelper and the
+// DEEPL_API_KEY env var for credential resolution.
func NewDeepLTool() *DeepLTool {
- return NewDeepLToolWith(NewHTTPHelper())
+ return NewDeepLToolWith(nil, "")
}
-// NewDeepLToolWith returns a DeepLTool that uses the provided
-// HTTPHelper. Useful for tests.
-func NewDeepLToolWith(h *HTTPHelper) *DeepLTool {
+func NewDeepLToolWith(h *HTTPHelper, apiKey string) *DeepLTool {
if h == nil {
h = NewHTTPHelper()
}
- return &DeepLTool{helper: h}
+ return &DeepLTool{helper: h, apiKey: strings.TrimSpace(apiKey)}
+}
+
+// resolveAPIKey returns the node-level credential, or DEEPL_API_KEY when
+// the node does not carry one.
+func (d *DeepLTool) resolveAPIKey() string {
+ if d.apiKey != "" {
+ return d.apiKey
+ }
+ return strings.TrimSpace(common.GetEnv(common.EnvDeepLAPIKey))
}
// Info returns the tool's metadata for the chat model.
@@ -93,11 +104,6 @@ func (d *DeepLTool) Info(_ context.Context) (*schema.ToolInfo, error) {
Name: deeplToolName,
Desc: deeplToolDescription,
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
- "api_key": {
- Type: schema.String,
- Desc: "DeepL API authentication key. Free keys end in ':fx'.",
- Required: true,
- },
"text": {
Type: schema.String,
Desc: "Text to translate.",
@@ -139,9 +145,10 @@ func (d *DeepLTool) InvokableRun(ctx context.Context, argsJSON string, _ ...tool
return deeplErrJSON(fmt.Errorf("deepl: parse arguments: %w", err)),
fmt.Errorf("deepl: parse arguments: %w", err)
}
- if p.APIKey == "" {
- return deeplErrJSON(fmt.Errorf("api_key is required")),
- fmt.Errorf("deepl: api_key is required")
+ apiKey := d.resolveAPIKey()
+ if apiKey == "" {
+ return deeplErrJSON(fmt.Errorf("api_key is not configured")),
+ fmt.Errorf("deepl: api_key is not configured (set the node-level api_key or DEEPL_API_KEY)")
}
if strings.TrimSpace(p.Text) == "" {
return deeplErrJSON(fmt.Errorf("text is required")),
@@ -155,14 +162,14 @@ func (d *DeepLTool) InvokableRun(ctx context.Context, argsJSON string, _ ...tool
}
endpoint := deeplFreeEndpoint
- if !strings.HasSuffix(p.APIKey, ":fx") {
+ if !strings.HasSuffix(apiKey, ":fx") {
// non-:fx keys are pro plan keys; route to the pro endpoint.
endpoint = deeplProEndpoint
}
body := buildDeepLFormBody(p.Text, p.SourceLang, p.TargetLang)
headers := map[string]string{
- "Authorization": "DeepL-Auth-Key " + p.APIKey,
+ "Authorization": "DeepL-Auth-Key " + apiKey,
}
resp, err := d.helper.Do(ctx, http.MethodPost, endpoint, body,
diff --git a/internal/agent/tool/deepl_test.go b/internal/agent/tool/deepl_test.go
index bf15c868ca..f962550f48 100644
--- a/internal/agent/tool/deepl_test.go
+++ b/internal/agent/tool/deepl_test.go
@@ -51,9 +51,9 @@ func TestDeepL_BuildRequest(t *testing.T) {
helper := NewHTTPHelper().WithClient(&http.Client{
Transport: rewriteHostTransport(srv.URL),
})
- tool := NewDeepLToolWith(helper)
+ tool := NewDeepLToolWith(helper, "key-xyz:fx")
out, err := tool.InvokableRun(ctx,
- `{"api_key":"key-xyz:fx","text":"Hello world","source_lang":"en","target_lang":"de"}`)
+ `{"text":"Hello world","source_lang":"en","target_lang":"de"}`)
if err != nil {
t.Fatalf("InvokableRun: %v", err)
}
@@ -112,9 +112,9 @@ func TestDeepL_DefaultLanguages(t *testing.T) {
helper := NewHTTPHelper().WithClient(&http.Client{
Transport: rewriteHostTransport(srv.URL),
})
- tool := NewDeepLToolWith(helper)
+ tool := NewDeepLToolWith(helper, "x:fx")
if _, err := tool.InvokableRun(ctx,
- `{"api_key":"x:fx","text":"Hello"}`); err != nil {
+ `{"text":"Hello"}`); err != nil {
t.Fatalf("InvokableRun: %v", err)
}
if gotForm.Get("source_lang") != "EN" {
@@ -125,21 +125,71 @@ func TestDeepL_DefaultLanguages(t *testing.T) {
}
}
-func TestDeepL_RequiresAPIKeyAndText(t *testing.T) {
- t.Parallel()
+// TestDeepL_RejectsMissingCredentialAndText pins that the credential is a
+// server-side setting: an unconfigured tool fails before any request, and the
+// model cannot inject one through its arguments.
+func TestDeepL_RejectsMissingCredentialAndText(t *testing.T) {
+ t.Setenv("DEEPL_API_KEY", "")
ctx := t.Context()
tool := NewDeepLTool()
- if _, err := tool.InvokableRun(ctx,
- `{"api_key":"","text":"Hello"}`); err == nil {
- t.Error("expected error for missing api_key")
+ out, err := tool.InvokableRun(ctx,
+ `{"api_key":"model-supplied","text":"Hello"}`)
+ if err == nil {
+ t.Fatal("expected error for unconfigured api_key")
}
- if _, err := tool.InvokableRun(ctx,
- `{"api_key":"x","text":""}`); err == nil {
+ if !strings.Contains(err.Error(), "api_key is not configured") {
+ t.Errorf("err = %v, want to mention api_key is not configured", err)
+ }
+ if !strings.Contains(out, "_ERROR") {
+ t.Errorf("out = %q, want _ERROR envelope", out)
+ }
+
+ configured := NewDeepLToolWith(nil, "x:fx")
+ if _, err := configured.InvokableRun(ctx, `{"text":""}`); err == nil {
t.Error("expected error for empty text")
}
}
+func TestDeepL_UsesEnvCredential(t *testing.T) {
+ t.Setenv("DEEPL_API_KEY", "env-key:fx")
+ ctx := t.Context()
+
+ var gotAuth string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotAuth = r.Header.Get("Authorization")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"translations":[{"text":"你好","detected_source_language":"EN"}]}`))
+ }))
+ defer srv.Close()
+
+ helper := NewHTTPHelper().WithClient(&http.Client{
+ Transport: rewriteHostTransport(srv.URL),
+ })
+ if _, err := NewDeepLToolWith(helper, "").InvokableRun(ctx, `{"text":"Hello"}`); err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if gotAuth != "DeepL-Auth-Key env-key:fx" {
+ t.Errorf("Authorization = %q, want DeepL-Auth-Key env-key:fx", gotAuth)
+ }
+}
+
+func TestDeepL_BuildByNameUsesNodeCredential(t *testing.T) {
+ t.Parallel()
+
+ built, err := BuildByName("deepl", map[string]any{"api_key": "node-key:fx"})
+ if err != nil {
+ t.Fatalf("BuildByName: %v", err)
+ }
+ tool, ok := built.(*DeepLTool)
+ if !ok {
+ t.Fatalf("BuildByName returned %T, want *DeepLTool", built)
+ }
+ if tool.apiKey != "node-key:fx" {
+ t.Errorf("apiKey = %q, want node-key:fx", tool.apiKey)
+ }
+}
+
func TestDeepL_Info(t *testing.T) {
t.Parallel()
ctx := t.Context()
@@ -155,6 +205,17 @@ func TestDeepL_Info(t *testing.T) {
if !strings.Contains(info.Desc, "DeepL") {
t.Errorf("Desc = %q, want to mention DeepL", info.Desc)
}
+ params, err := info.ParamsOneOf.ToJSONSchema()
+ if err != nil {
+ t.Fatalf("ToJSONSchema: %v", err)
+ }
+ raw, err := json.Marshal(params)
+ if err != nil {
+ t.Fatalf("marshal params schema: %v", err)
+ }
+ if strings.Contains(string(raw), `"api_key"`) {
+ t.Fatalf("schema exposes api_key; the credential must stay server-side: %s", raw)
+ }
}
// TestBeOutput_MirrorsPythonContract guards the Go-side
@@ -192,9 +253,9 @@ func TestDeepL_TranslationFailureReturnsError(t *testing.T) {
helper := NewHTTPHelper().WithClient(&http.Client{
Transport: rewriteHostTransport(srv.URL),
})
- tool := NewDeepLToolWith(helper)
+ tool := NewDeepLToolWith(helper, "key-xyz:fx")
out, err := tool.InvokableRun(ctx,
- `{"api_key":"key-xyz:fx","text":"hello","source_lang":"EN","target_lang":"ZH"}`)
+ `{"text":"hello","source_lang":"EN","target_lang":"ZH"}`)
if err == nil {
t.Fatalf("expected non-nil error, got nil; out=%s", out)
}
diff --git a/internal/agent/tool/qweather.go b/internal/agent/tool/qweather.go
index 0ad2e9c58c..5d27f59ead 100644
--- a/internal/agent/tool/qweather.go
+++ b/internal/agent/tool/qweather.go
@@ -26,6 +26,8 @@ import (
"github.com/cloudwego/eino/components/tool"
"github.com/cloudwego/eino/schema"
+
+ "ragflow/internal/common"
)
const qweatherToolName = "qweather"
@@ -39,13 +41,11 @@ var qweatherEndpoint = "https://devapi.qweather.com/v7/weather/now"
// qweatherParams is the JSON shape the model sends into InvokableRun.
//
-// - APIKey (required): the QWeather API key (Console → Project → Credentials).
// - Location (required): the location code, e.g. "101010100" (Beijing)
// or a lat,lon string "39.904,116.405".
// - Lang (optional): language code for `text` and `windDir`. Defaults
// to "zh" per the inbox spec.
type qweatherParams struct {
- APIKey string `json:"api_key"`
Location string `json:"location"`
Lang string `json:"lang,omitempty"`
}
@@ -77,7 +77,6 @@ type qweatherEnvelope struct {
Error string `json:"_ERROR,omitempty"`
}
-// QWeatherTool is the 和风天气
// (QWeather) current-conditions tool (
// batch 4). It performs a GET against devapi.qweather.com/v7/weather/now
// and returns the parsed now.{temp, feelsLike, text, windDir, humidity}.
@@ -86,20 +85,29 @@ type qweatherEnvelope struct {
// propagation.
type QWeatherTool struct {
helper *HTTPHelper
+ apiKey string
}
-// NewQWeatherTool returns a QWeatherTool using the default HTTPHelper.
+// NewQWeatherTool returns a QWeatherTool using the default HTTPHelper
+// and the QWEATHER_API_KEY env var for credential resolution.
func NewQWeatherTool() *QWeatherTool {
- return NewQWeatherToolWith(NewHTTPHelper())
+ return NewQWeatherToolWith(nil, "")
}
-// NewQWeatherToolWith returns a QWeatherTool that uses the provided
-// HTTPHelper. Useful for tests.
-func NewQWeatherToolWith(h *HTTPHelper) *QWeatherTool {
+func NewQWeatherToolWith(h *HTTPHelper, apiKey string) *QWeatherTool {
if h == nil {
h = NewHTTPHelper()
}
- return &QWeatherTool{helper: h}
+ return &QWeatherTool{helper: h, apiKey: strings.TrimSpace(apiKey)}
+}
+
+// resolveAPIKey returns the node-level credential, or QWEATHER_API_KEY
+// when the node does not carry one.
+func (q *QWeatherTool) resolveAPIKey() string {
+ if q.apiKey != "" {
+ return q.apiKey
+ }
+ return strings.TrimSpace(common.GetEnv(common.EnvQWeatherAPIKey))
}
// Info returns the tool's metadata for the chat model.
@@ -108,11 +116,6 @@ func (q *QWeatherTool) Info(_ context.Context) (*schema.ToolInfo, error) {
Name: qweatherToolName,
Desc: qweatherToolDescription,
ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{
- "api_key": {
- Type: schema.String,
- Desc: "QWeather API key (Console → 项目 → 凭据).",
- Required: true,
- },
"location": {
Type: schema.String,
Desc: "Location code (e.g. 101010100 for Beijing) or \"lat,lon\" (e.g. \"39.904,116.405\").",
@@ -129,10 +132,10 @@ func (q *QWeatherTool) Info(_ context.Context) (*schema.ToolInfo, error) {
// buildQWeatherURL composes the devapi.qweather.com URL. Centralized
// for testability.
-func buildQWeatherURL(p qweatherParams) string {
+func buildQWeatherURL(apiKey string, p qweatherParams) string {
q := url.Values{}
q.Set("location", p.Location)
- q.Set("key", p.APIKey)
+ q.Set("key", apiKey)
if p.Lang == "" {
p.Lang = "zh"
}
@@ -147,22 +150,24 @@ func (q *QWeatherTool) InvokableRun(ctx context.Context, argsJSON string, _ ...t
return qweatherErrJSON(fmt.Errorf("qweather: parse arguments: %w", err)),
fmt.Errorf("qweather: parse arguments: %w", err)
}
- if p.APIKey == "" {
- return qweatherErrJSON(fmt.Errorf("qweather: api_key is required")),
- fmt.Errorf("qweather: api_key is required")
+ apiKey := q.resolveAPIKey()
+ if apiKey == "" {
+ return qweatherErrJSON(fmt.Errorf("qweather: api_key is not configured")),
+ fmt.Errorf("qweather: api_key is not configured (set the node-level api_key or QWEATHER_API_KEY)")
}
if p.Location == "" {
return qweatherErrJSON(fmt.Errorf("qweather: location is required")),
fmt.Errorf("qweather: location is required")
}
- endpoint := buildQWeatherURL(p)
+ endpoint := buildQWeatherURL(apiKey, p)
headers := map[string]string{
"Accept": "application/json",
}
resp, err := q.helper.Do(ctx, http.MethodGet, endpoint, "", "", headers)
if err != nil {
+ err = redactQWeatherError(err, apiKey)
return qweatherErrJSON(err), err
}
defer resp.Body.Close()
@@ -193,6 +198,32 @@ func (q *QWeatherTool) InvokableRun(ctx context.Context, argsJSON string, _ ...t
}), nil
}
+// redactQWeatherError replaces the API key inside a request error message. The
+// key travels in the request URL's query string and Go's *url.Error prints that
+// URL, so the unredacted message would hand the node-level or QWEATHER_API_KEY
+// credential to the model (_ERROR) and to the logs. The wrapped error stays
+// reachable through Unwrap, so errors.Is still reports context cancellation and
+// deadline exceeded.
+func redactQWeatherError(err error, apiKey string) error {
+ if err == nil || apiKey == "" {
+ return err
+ }
+ msg := strings.ReplaceAll(err.Error(), apiKey, "REDACTED")
+ if msg == err.Error() {
+ return err
+ }
+ return &qweatherRedactedError{msg: msg, err: err}
+}
+
+type qweatherRedactedError struct {
+ msg string
+ err error
+}
+
+func (e *qweatherRedactedError) Error() string { return e.msg }
+
+func (e *qweatherRedactedError) Unwrap() error { return e.err }
+
func qweatherJSON(env qweatherEnvelope) string {
b, err := json.Marshal(env)
if err != nil {
@@ -204,12 +235,3 @@ func qweatherJSON(env qweatherEnvelope) string {
func qweatherErrJSON(err error) string {
return qweatherJSON(qweatherEnvelope{Error: err.Error()})
}
-
-// formatQWeatherError joins a non-2xx status with the upstream code so
-// the model can see both signals. Exposed for testability.
-func formatQWeatherError(status int, upstreamCode string) string {
- if strings.TrimSpace(upstreamCode) == "" {
- return fmt.Sprintf("qweather: upstream returned %d", status)
- }
- return fmt.Sprintf("qweather: upstream returned %d (code=%s)", status, upstreamCode)
-}
diff --git a/internal/agent/tool/qweather_test.go b/internal/agent/tool/qweather_test.go
index 84e7990ce3..1c605cc30f 100644
--- a/internal/agent/tool/qweather_test.go
+++ b/internal/agent/tool/qweather_test.go
@@ -32,6 +32,7 @@ func TestQWeather_BuildURL(t *testing.T) {
cases := []struct {
name string
+ apiKey string
params qweatherParams
wantLoc string
wantKey string
@@ -41,7 +42,8 @@ func TestQWeather_BuildURL(t *testing.T) {
}{
{
name: "Beijing, default lang",
- params: qweatherParams{APIKey: "K-abc", Location: "101010100"},
+ apiKey: "K-abc",
+ params: qweatherParams{Location: "101010100"},
wantLoc: "101010100",
wantKey: "K-abc",
wantLang: "zh",
@@ -50,7 +52,8 @@ func TestQWeather_BuildURL(t *testing.T) {
},
{
name: "lat,lon with explicit English",
- params: qweatherParams{APIKey: "K-xyz", Location: "39.904,116.405", Lang: "en"},
+ apiKey: "K-xyz",
+ params: qweatherParams{Location: "39.904,116.405", Lang: "en"},
wantLoc: "39.904,116.405",
wantKey: "K-xyz",
wantLang: "en",
@@ -61,7 +64,7 @@ func TestQWeather_BuildURL(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
- got := buildQWeatherURL(tc.params)
+ got := buildQWeatherURL(tc.apiKey, tc.params)
u, err := url.Parse(got)
if err != nil {
t.Fatalf("url.Parse(%q): %v", got, err)
@@ -115,10 +118,10 @@ func TestQWeather_ParseResponse(t *testing.T) {
helper := NewHTTPHelper().WithClient(&http.Client{
Transport: rewriteHostTransport(srv.URL),
})
- tool := NewQWeatherToolWith(helper)
+ tool := NewQWeatherToolWith(helper, "K-abc")
out, err := tool.InvokableRun(ctx,
- `{"api_key":"K-abc","location":"101010100"}`)
+ `{"location":"101010100"}`)
if err != nil {
t.Fatalf("InvokableRun: %v", err)
}
@@ -173,10 +176,10 @@ func TestQWeather_UpstreamBusinessError(t *testing.T) {
helper := NewHTTPHelper().WithClient(&http.Client{
Transport: rewriteHostTransport(srv.URL),
})
- tool := NewQWeatherToolWith(helper)
+ tool := NewQWeatherToolWith(helper, "K-abc")
_, err := tool.InvokableRun(ctx,
- `{"api_key":"K-abc","location":"000000000"}`)
+ `{"location":"000000000"}`)
if err == nil {
t.Fatal("expected error for non-200 upstream code, got nil")
}
@@ -185,18 +188,99 @@ func TestQWeather_UpstreamBusinessError(t *testing.T) {
}
}
-func TestQWeather_RejectsMissingAPIKey(t *testing.T) {
+// TestQWeather_NetworkErrorRedactsCredential pins that a transport failure
+// never echoes the node-level or environment API key. The key travels in the
+// request URL's query string and Go's *url.Error prints that URL, so the raw
+// error would both reach the model through _ERROR and land in the logs.
+func TestQWeather_NetworkErrorRedactsCredential(t *testing.T) {
+ // Not t.Parallel(): this test replaces the package-level qweatherEndpoint.
+ prev := qweatherEndpoint
+ // 127.0.0.1:1 refuses connections, so HTTPHelper exhausts its retries.
+ qweatherEndpoint = "http://127.0.0.1:1/v7/weather/now"
+ t.Cleanup(func() { qweatherEndpoint = prev })
+
+ const secret = "secret-node-key"
+ out, err := NewQWeatherToolWith(nil, secret).InvokableRun(t.Context(), `{"location":"101010100"}`)
+ if err == nil {
+ t.Fatal("expected a transport error, got nil")
+ }
+ if strings.Contains(err.Error(), secret) {
+ t.Errorf("returned error leaks the API key: %v", err)
+ }
+ if strings.Contains(out, secret) {
+ t.Errorf("tool output leaks the API key: %s", out)
+ }
+ if !strings.Contains(err.Error(), "REDACTED") {
+ t.Errorf("err = %v, want the redacted key marker", err)
+ }
+
+ var env qweatherEnvelope
+ if jerr := json.Unmarshal([]byte(out), &env); jerr != nil {
+ t.Fatalf("output is not valid JSON: %v (raw=%s)", jerr, out)
+ }
+ if env.Error == "" {
+ t.Error("expected _ERROR to describe the transport failure")
+ }
+}
+
+// TestQWeather_RejectsMissingCredential pins that the credential is a
+// server-side setting: an unconfigured tool fails before any request, and the
+// model cannot inject one through its arguments.
+func TestQWeather_RejectsMissingCredential(t *testing.T) {
+ t.Setenv("QWEATHER_API_KEY", "")
ctx := t.Context()
- t.Parallel()
tool := NewQWeatherTool()
_, err := tool.InvokableRun(ctx,
- `{"location":"101010100"}`)
+ `{"api_key":"model-supplied","location":"101010100"}`)
if err == nil {
- t.Fatal("expected error for missing api_key")
+ t.Fatal("expected error for unconfigured api_key")
+ }
+ if !strings.Contains(err.Error(), "api_key is not configured") {
+ t.Errorf("err = %v, want to mention api_key is not configured", err)
+ }
+}
+
+func TestQWeather_UsesEnvCredential(t *testing.T) {
+ t.Setenv("QWEATHER_API_KEY", "env-key")
+ ctx := t.Context()
+
+ var gotKey string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotKey = r.URL.Query().Get("key")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"code":"200","now":{"temp":"23"}}`))
+ }))
+ defer srv.Close()
+
+ prev := qweatherEndpoint
+ qweatherEndpoint = srv.URL + "/v7/weather/now"
+ t.Cleanup(func() { qweatherEndpoint = prev })
+
+ helper := NewHTTPHelper().WithClient(&http.Client{
+ Transport: rewriteHostTransport(srv.URL),
+ })
+ if _, err := NewQWeatherToolWith(helper, "").InvokableRun(ctx, `{"location":"101010100"}`); err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if gotKey != "env-key" {
+ t.Errorf("server saw key = %q, want env-key", gotKey)
}
- if !strings.Contains(err.Error(), "api_key") {
- t.Errorf("err = %v, want to mention api_key", err)
+}
+
+func TestQWeather_BuildByNameUsesNodeCredential(t *testing.T) {
+ t.Parallel()
+
+ built, err := BuildByName("qweather", map[string]any{"api_key": "node-key"})
+ if err != nil {
+ t.Fatalf("BuildByName: %v", err)
+ }
+ tool, ok := built.(*QWeatherTool)
+ if !ok {
+ t.Fatalf("BuildByName returned %T, want *QWeatherTool", built)
+ }
+ if tool.apiKey != "node-key" {
+ t.Errorf("apiKey = %q, want node-key", tool.apiKey)
}
}
@@ -204,9 +288,9 @@ func TestQWeather_RejectsMissingLocation(t *testing.T) {
ctx := t.Context()
t.Parallel()
- tool := NewQWeatherTool()
+ tool := NewQWeatherToolWith(nil, "K-abc")
_, err := tool.InvokableRun(ctx,
- `{"api_key":"K-abc"}`)
+ `{}`)
if err == nil {
t.Fatal("expected error for missing location")
}
@@ -230,4 +314,15 @@ func TestQWeather_Info(t *testing.T) {
if !strings.Contains(info.Desc, "QWeather") && !strings.Contains(info.Desc, "和风") {
t.Errorf("Desc = %q, want to mention QWeather", info.Desc)
}
+ params, err := info.ParamsOneOf.ToJSONSchema()
+ if err != nil {
+ t.Fatalf("ToJSONSchema: %v", err)
+ }
+ raw, err := json.Marshal(params)
+ if err != nil {
+ t.Fatalf("marshal params schema: %v", err)
+ }
+ if strings.Contains(string(raw), `"api_key"`) {
+ t.Fatalf("schema exposes api_key; the credential must stay server-side: %s", raw)
+ }
}
diff --git a/internal/agent/tool/registry.go b/internal/agent/tool/registry.go
index eb5969ea6e..92eacd2a4b 100644
--- a/internal/agent/tool/registry.go
+++ b/internal/agent/tool/registry.go
@@ -44,7 +44,7 @@ var registry = map[string]Factory{
"vector_search": noConfig("vector_search", func() einotool.BaseTool { return NewAgenticSearchTool(toolVectorSearch) }),
"bm25_search": noConfig("bm25_search", func() einotool.BaseTool { return NewAgenticSearchTool(toolBM25Search) }),
"wiki_query": noConfig("wiki_query", func() einotool.BaseTool { return NewWikiQueryTool() }),
- "deepl": noConfig("deepl", func() einotool.BaseTool { return NewDeepLTool() }),
+ "deepl": buildDeepLTool,
"duckduckgo": buildDuckDuckGoTool,
"email": buildEmailTool,
"execute_sql": buildExeSQLTool,
@@ -56,7 +56,7 @@ var registry = map[string]Factory{
"jin10": noConfig("jin10", func() einotool.BaseTool { return NewJin10Tool() }),
"keenable": buildKeenableTool,
"pubmed": buildPubMedTool,
- "qweather": noConfig("qweather", func() einotool.BaseTool { return NewQWeatherTool() }),
+ "qweather": buildQWeatherTool,
"querit": buildQueritTool,
"querit_contents": buildQueritContentsTool,
"querit_search": buildQueritTool,
@@ -869,6 +869,19 @@ func buildSearch1APICrawlTool(params map[string]any) (einotool.BaseTool, error)
return newSearch1APICrawlTool(nil, apiKey, defaultURL), nil
}
+// buildDeepLTool and buildQWeatherTool take the node-level api_key without
+// type enforcement: an unusable value is left out, so the tool falls back to
+// DEEPL_API_KEY / QWEATHER_API_KEY and reports the missing credential itself.
+func buildDeepLTool(params map[string]any) (einotool.BaseTool, error) {
+ apiKey, _ := stringParam(params, "api_key")
+ return NewDeepLToolWith(nil, apiKey), nil
+}
+
+func buildQWeatherTool(params map[string]any) (einotool.BaseTool, error) {
+ apiKey, _ := stringParam(params, "api_key")
+ return NewQWeatherToolWith(nil, apiKey), nil
+}
+
func buildTushareTool(params map[string]any) (einotool.BaseTool, error) {
var token string
if value, exists := params["token"]; exists {
diff --git a/internal/common/environments.go b/internal/common/environments.go
index ee6006eb5d..d3f907e61c 100644
--- a/internal/common/environments.go
+++ b/internal/common/environments.go
@@ -192,6 +192,8 @@ const (
EnvAllowAnyHost = "ALLOW_ANY_HOST"
EnvTavilyAPIKey = "TAVILY_API_KEY"
EnvQueritAPIKey = "QUERIT_API_KEY"
+ EnvDeepLAPIKey = "DEEPL_API_KEY"
+ EnvQWeatherAPIKey = "QWEATHER_API_KEY"
EnvHome = "HOME"
EnvUserProfile = "USERPROFILE"
EnvHTTPProxy = "http_proxy"