-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[AI] Add automatic function calling support #15653
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
Draft
paulb777
wants to merge
13
commits into
pb-gen-object-streamable
Choose a base branch
from
pb-auto-function-calling
base: pb-gen-object-streamable
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
150f141
Add automatic function calling support
paulb777 20fd2ba
review
paulb777 3329fd5
checkpoint
paulb777 665a8cd
JSONSchema enums and more tests
paulb777 be66707
review
paulb777 2d65b88
JSON Schema format
paulb777 1476ea9
JSON schema nullable attribute and more testing
paulb777 5a88e14
review
paulb777 f8e8b0d
review
paulb777 1a27f36
review
paulb777 17c06c2
review
paulb777 3c276fa
review
paulb777 f2d478f
review
paulb777 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| // 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. | ||
|
|
||
| import Foundation | ||
|
|
||
| /// A wrapper for a function declaration and its executable logic. | ||
| @available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *) | ||
| public struct AutomaticFunction: Sendable { | ||
| /// The declaration of the function, describing it to the model. | ||
| public let declaration: FunctionDeclaration | ||
|
|
||
| /// The closure to execute when the function is called. | ||
| public let execute: @Sendable ([String: JSONValue]) async throws -> JSONObject | ||
|
|
||
| /// Creates a new `AutomaticFunction`. | ||
| /// - Parameters: | ||
| /// - declaration: The function declaration. | ||
| /// - execute: The execution logic. | ||
| public init(declaration: FunctionDeclaration, | ||
| execute: @escaping @Sendable ([String: JSONValue]) async throws -> JSONObject) { | ||
| self.declaration = declaration | ||
| self.execute = execute | ||
| } | ||
|
|
||
| /// Creates a new `AutomaticFunction` with a simplified declaration. | ||
| /// - Parameters: | ||
| /// - name: The name of the function. | ||
| /// - description: A brief description of the function. | ||
| /// - parameters: Describes the parameters to this function. | ||
| /// - optionalParameters: The names of parameters that may be omitted by the model. | ||
| /// - execute: The execution logic. | ||
| public init(name: String, | ||
| description: String, | ||
| parameters: [String: Schema] = [:], | ||
| optionalParameters: [String] = [], | ||
| execute: @escaping @Sendable ([String: JSONValue]) async throws -> JSONObject) { | ||
| declaration = FunctionDeclaration(name: name, | ||
| description: description, | ||
| parameters: parameters, | ||
| optionalParameters: optionalParameters) | ||
| self.execute = execute | ||
| } | ||
| } | ||
|
|
||
| #if canImport(FoundationModels) | ||
| import FoundationModels | ||
|
|
||
| @available(iOS 26.0, macOS 26.0, *) | ||
| @available(tvOS, unavailable) | ||
| @available(watchOS, unavailable) | ||
| public extension AutomaticFunction { | ||
| /// Creates an `AutomaticFunction` from a `FoundationModels.Tool`. | ||
| /// | ||
| /// - Parameter tool: The `FoundationModels.Tool` instance to wrap. | ||
| init<T: FoundationModels.Tool>(_ tool: T) throws { | ||
| // Convert FoundationModels.GenerationSchema to FirebaseAI.Schema (via JSONSchema) | ||
| // Tool.parameters is a GenerationSchema instance. | ||
| // We encode it to JSON and decode it as our JSONSchema type. | ||
| let data = try JSONEncoder().encode(tool.parameters) | ||
| let jsonSchema = try JSONDecoder().decode(JSONSchema.self, from: data) | ||
| let firebaseSchema = try jsonSchema.asSchema() | ||
|
|
||
| // Extract parameter properties | ||
| let properties = firebaseSchema.properties ?? [:] | ||
| let required = firebaseSchema.requiredProperties ?? [] | ||
| let requiredSet = Set(required) | ||
|
|
||
| self.init( | ||
| name: tool.name, | ||
| description: tool.description, | ||
| parameters: properties, | ||
| optionalParameters: properties.keys.filter { !requiredSet.contains($0) } | ||
| ) { args in | ||
| // Convert [String: JSONValue] -> JSONObject (ModelOutput) -> GeneratedContent -> | ||
| // T.Arguments | ||
| let modelOutput = ModelOutput(jsonValue: .object(args)) | ||
|
|
||
| let generatedContent = modelOutput.generatedContent | ||
| let toolArgs = try T.Arguments(generatedContent) | ||
|
|
||
| // Execute the tool | ||
| let result = try await tool.call(arguments: toolArgs) | ||
|
|
||
| // Convert result -> JSON | ||
| // We assume the output is Encodable (common for Generable/PromptRepresentable types that | ||
| // are data). | ||
| // If it's just a String, we wrap it. | ||
| if let encodableResult = result as? Encodable { | ||
| let encoder = JSONEncoder() | ||
| let data = try encoder.encode(encodableResult) | ||
| let jsonValue = try JSONDecoder().decode(JSONValue.self, from: data) | ||
| if case let .object(jsonObject) = jsonValue { | ||
| return jsonObject | ||
| } else { | ||
| return ["result": jsonValue] | ||
| } | ||
| } | ||
|
|
||
| // Fallback for non-Encodable or other types: String description | ||
| return ["result": .string(String(describing: result))] | ||
| } | ||
| } | ||
| } | ||
| #endif | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.