generated from SAP/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 15
feat: [OpenAI] Tool Definition and Call Parsing V2 (Incl Execution) #418
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
Merged
newtork
merged 45 commits into
main
from
feat/openai/tool-definition-and-call-parsing-v2
May 14, 2025
Merged
Changes from 31 commits
Commits
Show all changes
45 commits
Select commit
Hold shift + click to select a range
6ebb2db
feat: add methods to convert function call arguments to Map and speci…
rpanackal f7e9088
feat: introduce OpenAiFunctionTool and enhance OpenAiChatCompletionRe…
rpanackal 75fe7dd
docs: enhance OpenAiFunctionTool and related classes documentation
rpanackal e726226
Merge remote-tracking branch 'refs/remotes/origin/main' into feat/ope…
rpanackal 484c14d
docs: add @since 1.7.0 annotations to relevant methods for version tr…
rpanackal 58792c6
ci
rpanackal cd03dac
fix unintentional javadoc change
rpanackal c92954a
test: update Javadoc to include exception details and enhance test co…
rpanackal 03453a4
refactor: enhance JSON parsing methods in OpenAiFunctionCall and remo…
rpanackal 36ed5bd
refactor: simplify JSON parsing in OpenAiFunctionCall and add unit te…
rpanackal 33f2ca8
refactor: update OpenAiFunctionTool to improve argument parsing and e…
rpanackal 87faa45
Merge branch 'main' into feat/openai/tool-definition-and-call-parsing
CharlesDuboisSAP 7ce6aef
part done
rpanackal bfce048
Merge remote-tracking branch 'origin/feat/openai/tool-definition-and-…
CharlesDuboisSAP 57ba2a1
finito
CharlesDuboisSAP 36b0189
Formatting
bot-sdk-js bcb42c8
With purely generics
rpanackal c52fafa
With purely explicit types
rpanackal 66cef01
refactor: enhance response serialization and improve schema generatio…
rpanackal 3038eb3
Introduce OpenAiToolExecutor
rpanackal c53b04e
CI
rpanackal 27fa975
test: OpenAiToolExecutor and improve error messages
rpanackal e8764c8
docs: update release notes to include tool execution in OpenAI functi…
rpanackal 9d3684d
Merge remote-tracking branch 'refs/remotes/origin/main' into feat/ope…
rpanackal ad89753
fix: use the same schema generation dependency as in orchestration mo…
rpanackal f8e3645
refactor: rename generic type parameter from I to InputT in OpenAiTool
rpanackal 2da40a0
Merge branch 'refs/heads/main' into feat/openai/tool-definition-and-c…
rpanackal c4bfa20
fix shadowing problem
rpanackal d15ee63
Change `withOpenAiTools` to `withToolsExecutable`; Change `OpenAiTool…
a-d 91433a2
Merge remote-tracking branch 'origin/main' into feat/openai/tool-defi…
a-d 2239ad7
Merge branch 'main' into feat/openai/tool-definition-and-call-parsing-v2
newtork f297fed
Update sample-code/spring-app/src/main/java/com/sap/ai/sdk/app/servic…
newtork 7baf530
Merge branch 'feat/openai/tool-definition-and-call-parsing-v2' of htt…
a-d 9f96e1a
Remove generic type argument from OpenAiTool class; Migrate error-pro…
a-d ce3ba95
Remove unnecessary throws declaration
a-d 3667b1e
Reverted the intermediate result class; `OpenAiTool#execute` will dir…
a-d 2de2592
Merge remote-tracking branch 'origin/main' into feat/openai/tool-defi…
a-d 454f7c5
Remove unused code
a-d ed01c22
Add convenience method OpenAiChatCompletionResponse#executeTools
a-d 1f4d2a2
Formatting
bot-sdk-js 6bd64ff
Hide getter
a-d ca7fc25
Fix PMD
a-d 3e69967
Fix tests
a-d 8f2346d
Make inaccessible method private
newtork c21ef75
Reduce visibility of OpenAiTool#execute
newtork 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
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
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
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
192 changes: 192 additions & 0 deletions
192
...dation-models/openai/src/main/java/com/sap/ai/sdk/foundationmodels/openai/OpenAiTool.java
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,192 @@ | ||
| package com.sap.ai.sdk.foundationmodels.openai; | ||
|
|
||
| import static com.sap.ai.sdk.foundationmodels.openai.generated.model.ChatCompletionTool.TypeEnum.FUNCTION; | ||
| import static java.util.function.UnaryOperator.identity; | ||
|
|
||
| import com.fasterxml.jackson.core.JsonProcessingException; | ||
| import com.fasterxml.jackson.core.type.TypeReference; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.github.victools.jsonschema.generator.Option; | ||
| import com.github.victools.jsonschema.generator.OptionPreset; | ||
| import com.github.victools.jsonschema.generator.SchemaGenerator; | ||
| import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder; | ||
| import com.github.victools.jsonschema.generator.SchemaVersion; | ||
| import com.github.victools.jsonschema.module.jackson.JacksonModule; | ||
| import com.github.victools.jsonschema.module.jackson.JacksonOption; | ||
| import com.google.common.annotations.Beta; | ||
| import com.sap.ai.sdk.foundationmodels.openai.generated.model.ChatCompletionTool; | ||
| import com.sap.ai.sdk.foundationmodels.openai.generated.model.FunctionObject; | ||
| import java.util.ArrayList; | ||
| import java.util.LinkedHashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.function.Function; | ||
| import java.util.stream.Collectors; | ||
| import javax.annotation.Nonnull; | ||
| import javax.annotation.Nullable; | ||
| import lombok.AccessLevel; | ||
| import lombok.AllArgsConstructor; | ||
| import lombok.Data; | ||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.experimental.Accessors; | ||
| import lombok.extern.slf4j.Slf4j; | ||
|
|
||
| /** | ||
| * Represents an OpenAI tool that can be used to define a function call in an OpenAI Chat Completion | ||
| * request. This tool generates a JSON schema based on the provided class representing the | ||
| * function's request structure. | ||
| * | ||
| * @param <InputT> the type of the input argument for the function | ||
| * @see <a href="https://platform.openai.com/docs/guides/gpt/function-calling"/>OpenAI Function | ||
| * @since 1.7.0 | ||
| */ | ||
| @Slf4j | ||
| @Beta | ||
| @Data | ||
| @Getter(AccessLevel.PACKAGE) | ||
| @Accessors(chain = true) | ||
| @AllArgsConstructor(access = AccessLevel.PRIVATE) | ||
| public class OpenAiTool<InputT> { | ||
|
|
||
| private static final ObjectMapper JACKSON = new ObjectMapper(); | ||
|
|
||
| /** The schema generator used to create JSON schemas. */ | ||
| @Nonnull private static final SchemaGenerator GENERATOR = createSchemaGenerator(); | ||
|
|
||
| /** The name of the function. */ | ||
| @Nonnull private String name; | ||
|
|
||
| /** The model class for function request. */ | ||
| @Nonnull private Class<InputT> requestClass; | ||
|
|
||
| /** An optional description of the function. */ | ||
| @Nullable private String description; | ||
|
|
||
| /** An optional flag indicating whether the function parameters should be treated strictly. */ | ||
| @Nullable private Boolean strict; | ||
|
|
||
| /** The function to be called. */ | ||
| @Nullable private Function<InputT, ?> function; | ||
|
|
||
| /** | ||
| * Constructs an {@code OpenAiFunctionTool} with the specified name and a model class that | ||
| * captures the request to the function. | ||
| * | ||
| * @param name the name of the function | ||
| * @param requestClass the model class for function request | ||
| */ | ||
| public OpenAiTool(@Nonnull final String name, @Nonnull final Class<InputT> requestClass) { | ||
| this(name, requestClass, null, null, null); | ||
| } | ||
|
|
||
| @Nonnull | ||
| Object execute(@Nonnull final InputT argument) { | ||
| if (getFunction() == null) { | ||
| throw new IllegalStateException( | ||
| "Tool " + name + " is missing a method reference to execute."); | ||
newtork marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| return getFunction().apply(argument); | ||
| } | ||
|
|
||
| ChatCompletionTool createChatCompletionTool() { | ||
| final var schema = GENERATOR.generateSchema(getRequestClass()); | ||
| final var schemaMap = | ||
| OpenAiUtils.getOpenAiObjectMapper() | ||
| .convertValue(schema, new TypeReference<Map<String, Object>>() {}); | ||
|
|
||
| return new ChatCompletionTool() | ||
| .type(FUNCTION) | ||
| .function( | ||
| new FunctionObject() | ||
| .name(getName()) | ||
| .description(getDescription()) | ||
| .parameters(schemaMap) | ||
| .strict(getStrict())); | ||
| } | ||
|
|
||
| private static SchemaGenerator createSchemaGenerator() { | ||
| final var module = | ||
| new JacksonModule( | ||
| JacksonOption.RESPECT_JSONPROPERTY_REQUIRED, JacksonOption.RESPECT_JSONPROPERTY_ORDER); | ||
| return new SchemaGenerator( | ||
| new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON) | ||
| .without(Option.SCHEMA_VERSION_INDICATOR) | ||
| .with(module) | ||
| .build()); | ||
| } | ||
|
|
||
| /** | ||
| * Executes the given tool calls with the provided tools and returns the results as a list of | ||
| * {@link OpenAiToolMessage} containing execution results encoded as JSON string. | ||
| * | ||
| * @param tools the list of tools to execute | ||
| * @param msg the assistant message containing a list of tool calls with arguments | ||
| * @return a result object that contains the list of tool messages with the results | ||
| * @throws IllegalStateException if a tool is missing a method reference for function execution. | ||
| */ | ||
| @Beta | ||
| @Nonnull | ||
| public static Execution execute( | ||
| @Nonnull final List<OpenAiTool<?>> tools, @Nonnull final OpenAiAssistantMessage msg) | ||
| throws IllegalArgumentException { | ||
| final var result = new LinkedHashMap<OpenAiFunctionCall, Object>(); | ||
|
|
||
| final var toolMap = tools.stream().collect(Collectors.toMap(OpenAiTool::getName, identity())); | ||
| for (final OpenAiToolCall toolCall : msg.toolCalls()) { | ||
| if (toolCall instanceof OpenAiFunctionCall functionCall) { | ||
| final var tool = toolMap.get(functionCall.getName()); | ||
| if (tool == null) { | ||
| log.warn("Tool not found for function call: {}", functionCall.getName()); | ||
| continue; | ||
| } | ||
| final var toolResult = executeFunction(tool, functionCall); | ||
| result.put(functionCall, toolResult); | ||
| } | ||
| } | ||
| return new Execution(result); | ||
| } | ||
|
|
||
| @Nonnull | ||
| private static <I> Object executeFunction( | ||
| @Nonnull final OpenAiTool<I> tool, @Nonnull final OpenAiFunctionCall toolCall) { | ||
| final I arguments = toolCall.getArgumentsAsObject(tool.getRequestClass()); | ||
| return tool.execute(arguments); | ||
| } | ||
|
|
||
| @Nonnull | ||
| private static String serializeObject(@Nonnull final Object obj) throws IllegalArgumentException { | ||
| try { | ||
| return JACKSON.writeValueAsString(obj); | ||
| } catch (JsonProcessingException e) { | ||
| throw new IllegalArgumentException("Failed to serialize object to JSON", e); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Represents the result of executing a tool call, containing the results of the function calls. | ||
| */ | ||
| @RequiredArgsConstructor | ||
| @Beta | ||
| public static class Execution { | ||
| @Getter @Beta @Nonnull private final Map<OpenAiFunctionCall, Object> results; | ||
|
|
||
| /** | ||
| * Creates a new list of serialized OpenAI tool messages. | ||
| * | ||
| * @return the list of serialized OpenAI tool messages. | ||
| * @throws IllegalArgumentException if the tool results cannot be serialized to JSON | ||
| */ | ||
| @Beta | ||
| @Nonnull | ||
| public List<OpenAiToolMessage> getMessages() { | ||
| final var result = new ArrayList<OpenAiToolMessage>(); | ||
| for (final var entry : getResults().entrySet()) { | ||
| final var functionCall = entry.getKey().getId(); | ||
| final var serializedValue = serializeObject(entry.getValue()); | ||
| result.add(OpenAiMessage.tool(serializedValue, functionCall)); | ||
| } | ||
| return result; | ||
| } | ||
| } | ||
| } | ||
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.
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.