-
Notifications
You must be signed in to change notification settings - Fork 535
functiontool: support non-struct inputs from LLM function calls #377
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 2 commits
3b95531
d94e302
b028e99
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| # Changelog | ||
|
|
||
| ## Unreleased | ||
|
|
||
| - functiontool: support non-struct inputs from LLM function calls | ||
| - Automatically wraps function tools whose input type is a non-struct (e.g. `string`, `int`) so they accept LLM function-call arguments of the form `{ "input": <value> }`. | ||
| - Adds `nonStructInputWrapper` implementation, unit + integration tests, and documentation. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| // Copyright 2025 Google LLC | ||
| // | ||
| // 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 functiontool provides a tool that wraps a Go function. | ||
| // | ||
| // Special behavior for non-struct inputs: | ||
| // | ||
| // The LLM `genai.FunctionCall.Args` is always represented as `map[string]any`. | ||
| // For Go handlers whose input type (`TArgs`) is a non-struct (for example | ||
| // `string`, `int`, or `bool`), ADK's `functiontool.New` wraps the handler with | ||
| // a small decorator that: | ||
| // - exposes a function declaration whose `parameters` JSON schema is an | ||
| // `object` with a single required property `"input"` whose schema is the | ||
| // schema inferred for `TArgs`; | ||
| // - at runtime accepts `map[string]any{"input": <value>}` from the model, | ||
| // extracts the `input` value, converts it to `TArgs`, calls the original | ||
| // handler, and converts the result back to `map[string]any` (wrapping | ||
| // primitive outputs as `{ "result": <value> }` when necessary). | ||
| // | ||
| // This automatic wrapping makes it seamless to author function tools that | ||
| // accept primitive arguments while keeping the function-call declaration and | ||
| // runtime conversion consistent with the model's map-based function call | ||
| // format. | ||
| package functiontool |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| // Copyright 2025 Google LLC | ||
| // | ||
| // 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 functiontool | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "reflect" | ||
|
|
||
| "github.com/google/jsonschema-go/jsonschema" | ||
| "google.golang.org/genai" | ||
|
|
||
| "google.golang.org/adk/internal/toolinternal/toolutils" | ||
| "google.golang.org/adk/internal/typeutil" | ||
| "google.golang.org/adk/model" | ||
| "google.golang.org/adk/tool" | ||
| ) | ||
|
|
||
| // nonStructInputWrapper wraps a functionTool with a non-struct input type, | ||
| // converting the LLM-provided map[string]any with an "input" key to the expected type. | ||
| type nonStructInputWrapper[TArgs, TResults any] struct { | ||
| cfg Config | ||
| inputSchema *jsonschema.Resolved | ||
| outputSchema *jsonschema.Resolved | ||
| handler Func[TArgs, TResults] | ||
| innerTool *functionTool[TArgs, TResults] | ||
| } | ||
|
|
||
| // wrapNonStructInput wraps a functionTool if its input type is not a struct. | ||
| // This is necessary for llmagent compatibility, as the LLM always provides arguments | ||
| // as map[string]any with an "input" key for non-struct types. | ||
| func wrapNonStructInput[TArgs, TResults any]( | ||
| cfg Config, | ||
| inputSchema *jsonschema.Resolved, | ||
| outputSchema *jsonschema.Resolved, | ||
| handler Func[TArgs, TResults], | ||
| ) (tool.Tool, error) { | ||
| // Check if TArgs is a struct type | ||
| var zeroArgs TArgs | ||
| if reflect.TypeOf(zeroArgs).Kind() != reflect.Struct { | ||
| // Non-struct type: wrap it | ||
| return &nonStructInputWrapper[TArgs, TResults]{ | ||
| cfg: cfg, | ||
| inputSchema: inputSchema, | ||
| outputSchema: outputSchema, | ||
| handler: handler, | ||
| innerTool: &functionTool[TArgs, TResults]{ | ||
| cfg: cfg, | ||
| inputSchema: inputSchema, | ||
| outputSchema: outputSchema, | ||
| handler: handler, | ||
| }, | ||
| }, nil | ||
| } | ||
|
|
||
| // Struct type: return the regular functionTool | ||
| return &functionTool[TArgs, TResults]{ | ||
| cfg: cfg, | ||
| inputSchema: inputSchema, | ||
| outputSchema: outputSchema, | ||
| handler: handler, | ||
| }, nil | ||
| } | ||
|
|
||
| // Description implements tool.Tool. | ||
| func (w *nonStructInputWrapper[TArgs, TResults]) Description() string { | ||
| return w.cfg.Description | ||
| } | ||
|
|
||
| // Name implements tool.Tool. | ||
| func (w *nonStructInputWrapper[TArgs, TResults]) Name() string { | ||
| return w.cfg.Name | ||
| } | ||
|
|
||
| // IsLongRunning implements tool.Tool. | ||
| func (w *nonStructInputWrapper[TArgs, TResults]) IsLongRunning() bool { | ||
| return w.cfg.IsLongRunning | ||
| } | ||
|
|
||
| // ProcessRequest implements tool.Tool. | ||
| func (w *nonStructInputWrapper[TArgs, TResults]) ProcessRequest(ctx tool.Context, req *model.LLMRequest) error { | ||
| return toolutils.PackTool(req, w) | ||
| } | ||
|
|
||
| // Declaration implements FunctionTool interface. | ||
| // It modifies the schema to expect {"input": <value>} format. | ||
| func (w *nonStructInputWrapper[TArgs, TResults]) Declaration() *genai.FunctionDeclaration { | ||
| decl := &genai.FunctionDeclaration{ | ||
| Name: w.Name(), | ||
| Description: w.Description(), | ||
| } | ||
|
|
||
| // Create a wrapper schema that expects {"input": <value>} format | ||
| wrappedSchema := &jsonschema.Schema{ | ||
| Type: "object", | ||
| Properties: map[string]*jsonschema.Schema{ | ||
| "input": {}, | ||
| }, | ||
| Required: []string{"input"}, | ||
| } | ||
|
|
||
| // Copy the original input schema properties to the "input" property | ||
| if w.inputSchema != nil { | ||
| wrappedSchema.Properties["input"] = w.inputSchema.Schema() | ||
| } else { | ||
| // Use string as default if no schema | ||
| wrappedSchema.Properties["input"] = &jsonschema.Schema{Type: "string"} | ||
| } | ||
|
||
|
|
||
| if wrappedSchema != nil { | ||
| decl.ParametersJsonSchema = wrappedSchema | ||
| } | ||
|
||
| if w.outputSchema != nil { | ||
| decl.ResponseJsonSchema = w.outputSchema.Schema() | ||
| } | ||
|
|
||
| if w.cfg.IsLongRunning { | ||
| instruction := "NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status." | ||
| if decl.Description != "" { | ||
| decl.Description += "\n\n" + instruction | ||
| } else { | ||
| decl.Description = instruction | ||
| } | ||
| } | ||
|
|
||
| return decl | ||
| } | ||
|
|
||
| // Run implements FunctionTool. | ||
| // It unwraps the {"input": <value>} format and calls the handler. | ||
| func (w *nonStructInputWrapper[TArgs, TResults]) Run(ctx tool.Context, args any) (map[string]any, error) { | ||
| // Extract the map | ||
| m, ok := args.(map[string]any) | ||
| if !ok { | ||
| return nil, fmt.Errorf("unexpected args type, got: %T", args) | ||
| } | ||
|
|
||
| // Extract the "input" key | ||
| inputVal, ok := m["input"] | ||
| if !ok { | ||
| return nil, fmt.Errorf("missing required 'input' argument") | ||
| } | ||
|
|
||
| // Convert to TArgs - use JSON marshaling to handle the conversion. | ||
| // Do NOT pass the original resolved input schema to ConvertToWithJSONSchema here, | ||
| // because resolvedSchema validation expects a map[string]any and will fail for | ||
| // primitive JSON values (e.g. string). Validation is handled by the declaration | ||
| // schema sent to the model; at runtime we only need to convert the value. | ||
| input, err := typeutil.ConvertToWithJSONSchema[any, TArgs](inputVal, nil) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to convert input: %w", err) | ||
| } | ||
|
|
||
| // Call the handler | ||
| output, err := w.handler(ctx, input) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| // Convert output to map[string]any | ||
| resp, err := typeutil.ConvertToWithJSONSchema[TResults, map[string]any](output, w.outputSchema) | ||
| if err == nil { | ||
| return resp, nil | ||
| } | ||
|
|
||
| // If conversion fails and outputSchema is set, validate and return with wrapped error | ||
| if w.outputSchema != nil { | ||
| if err1 := w.outputSchema.Validate(output); err1 != nil { | ||
| return resp, err // if it fails propagate original err. | ||
| } | ||
|
Comment on lines
166
to
168
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There's an issue with the error handling in this block. If if err1 := w.outputSchema.Validate(output); err1 != nil {
return nil, fmt.Errorf("output validation failed: %w", err1)
} |
||
| } | ||
| wrappedOutput := map[string]any{"result": output} | ||
| return wrappedOutput, nil | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
innerToolfield is declared here but appears to be unused throughout thenonStructInputWrapper's methods. To improve code clarity and maintainability, it's best to remove this unused field and its corresponding initialization in thewrapNonStructInputfunction.