generated from SAP/repository-template
-
Notifications
You must be signed in to change notification settings - Fork 11
feat: [OpenAI] Sample code for Agentic Workflow tutorial #466
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
Open
Jonas-Isr
wants to merge
6
commits into
main
Choose a base branch
from
agent-workflow-examples
base: main
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.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9ff262b
first draft
b14d70c
Align with docs
b32b999
Codestyle
32d1bb2
Merge branch 'main' into agent-workflow-examples
5720581
Merge branch 'main' into agent-workflow-examples
Jonas-Isr 64c8b0e
Merge branch 'main' into agent-workflow-examples
Jonas-Isr 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
36 changes: 36 additions & 0 deletions
36
...g-app/src/main/java/com/sap/ai/sdk/app/controllers/SpringAiAgenticWorkflowController.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,36 @@ | ||
package com.sap.ai.sdk.app.controllers; | ||
|
||
import com.sap.ai.sdk.app.services.SpringAiAgenticWorkflowService; | ||
import com.sap.ai.sdk.orchestration.spring.OrchestrationSpringChatResponse; | ||
import javax.annotation.Nullable; | ||
import lombok.extern.slf4j.Slf4j; | ||
import lombok.val; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.web.bind.annotation.GetMapping; | ||
import org.springframework.web.bind.annotation.RequestMapping; | ||
import org.springframework.web.bind.annotation.RequestParam; | ||
import org.springframework.web.bind.annotation.RestController; | ||
|
||
/** Endpoints for the AgenticWorkflow Service */ | ||
@SuppressWarnings("unused") | ||
@RestController | ||
@Slf4j | ||
@RequestMapping("/spring-ai-agentic") | ||
public class SpringAiAgenticWorkflowController { | ||
|
||
@Autowired private SpringAiAgenticWorkflowService service; | ||
|
||
@GetMapping("/chain") | ||
Object completion( | ||
@Nullable @RequestParam(value = "format", required = false) final String format) { | ||
val response = | ||
service.runAgent("I want to do a one-day trip to Paris. Help me make an itinerary, please"); | ||
|
||
if ("json".equals(format)) { | ||
return ((OrchestrationSpringChatResponse) response) | ||
.getOrchestrationResponse() | ||
.getOriginalResponse(); | ||
} | ||
return response.getResult().getOutput().getText(); | ||
} | ||
} |
44 changes: 44 additions & 0 deletions
44
sample-code/spring-app/src/main/java/com/sap/ai/sdk/app/services/RestaurantMethod.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,44 @@ | ||
package com.sap.ai.sdk.app.services; | ||
|
||
import java.util.List; | ||
import java.util.Locale; | ||
import java.util.Map; | ||
import javax.annotation.Nonnull; | ||
import lombok.val; | ||
import org.springframework.ai.tool.annotation.Tool; | ||
import org.springframework.ai.tool.annotation.ToolParam; | ||
|
||
/** Mock tool for agentic workflow */ | ||
class RestaurantMethod { | ||
|
||
/** | ||
* Request for list of restaurants | ||
* | ||
* @param location the city | ||
*/ | ||
record Request(String location) {} | ||
|
||
/** | ||
* Response for restaurant recommendations | ||
* | ||
* @param restaurants the list of restaurants | ||
*/ | ||
record Response(List<String> restaurants) {} | ||
|
||
@Nonnull | ||
@SuppressWarnings("unused") | ||
@Tool(description = "Get recommended restaurants for a location") | ||
static RestaurantMethod.Response getRestaurants( | ||
@ToolParam @Nonnull final RestaurantMethod.Request request) { | ||
val recommendations = | ||
Map.of( | ||
"paris", | ||
List.of("Le Comptoir du Relais", "L'As du Fallafel", "Breizh Café"), | ||
"reykjavik", | ||
List.of("Dill Restaurant", "Fish Market", "Grillmarkaðurinn")); | ||
return new RestaurantMethod.Response( | ||
recommendations.getOrDefault( | ||
request.location.toLowerCase(Locale.ROOT), | ||
List.of("No recommendations for this city."))); | ||
} | ||
} |
76 changes: 76 additions & 0 deletions
76
.../spring-app/src/main/java/com/sap/ai/sdk/app/services/SpringAiAgenticWorkflowService.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,76 @@ | ||
package com.sap.ai.sdk.app.services; | ||
|
||
import static com.sap.ai.sdk.orchestration.OrchestrationAiModel.GPT_4O_MINI; | ||
|
||
import com.sap.ai.sdk.orchestration.OrchestrationModuleConfig; | ||
import com.sap.ai.sdk.orchestration.spring.OrchestrationChatModel; | ||
import com.sap.ai.sdk.orchestration.spring.OrchestrationChatOptions; | ||
import java.util.List; | ||
import java.util.Objects; | ||
import javax.annotation.Nonnull; | ||
import lombok.extern.slf4j.Slf4j; | ||
import lombok.val; | ||
import org.springframework.ai.chat.client.ChatClient; | ||
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor; | ||
import org.springframework.ai.chat.memory.InMemoryChatMemory; | ||
import org.springframework.ai.chat.model.ChatModel; | ||
import org.springframework.ai.chat.model.ChatResponse; | ||
import org.springframework.ai.chat.prompt.Prompt; | ||
import org.springframework.ai.tool.ToolCallbacks; | ||
import org.springframework.stereotype.Service; | ||
|
||
/** Service class for the AgenticWorkflow service */ | ||
@Service | ||
@Slf4j | ||
public class SpringAiAgenticWorkflowService { | ||
private final ChatModel client = new OrchestrationChatModel(); | ||
private final OrchestrationModuleConfig config = | ||
new OrchestrationModuleConfig().withLlmConfig(GPT_4O_MINI); | ||
|
||
/** | ||
* Simple agentic workflow using chain-like structure. The agent is generating a travel itinerary | ||
* for a given city. | ||
* | ||
* @param userInput the user input including the target city | ||
* @return a short travel itinerary | ||
*/ | ||
@Nonnull | ||
public ChatResponse runAgent(@Nonnull final String userInput) { | ||
|
||
// Configure chat memory | ||
val memory = new InMemoryChatMemory(); | ||
val advisor = new MessageChatMemoryAdvisor(memory); | ||
val cl = ChatClient.builder(client).defaultAdvisors(advisor).build(); | ||
|
||
// Add (mocked) tools | ||
val options = new OrchestrationChatOptions(config); | ||
options.setToolCallbacks( | ||
List.of(ToolCallbacks.from(new WeatherMethod(), new RestaurantMethod()))); | ||
options.setInternalToolExecutionEnabled(true); | ||
|
||
// Prompts for the chain workflow | ||
final List<String> systemPrompts = | ||
List.of( | ||
"You are a traveling planning agent for a single day trip. Where appropriate, use the provided tools. First, start by suggesting some restaurants for the mentioned city.", | ||
"Now, check the whether for the city.", | ||
"Finally, combine the suggested itinerary from this conversation into a short, one-sentence plan for the day trip."); | ||
|
||
// Perform the chain workflow | ||
String responseText = userInput; | ||
ChatResponse response = null; | ||
|
||
for (final String systemPrompt : systemPrompts) { | ||
|
||
// Combine the pre-defined prompt with the previous answer to get the new input | ||
val input = String.format("{%s}\n {%s}", systemPrompt, responseText); | ||
val prompt = new Prompt(input, options); | ||
|
||
// Make a call to the LLM with the new input | ||
response = | ||
Objects.requireNonNull(cl.prompt(prompt).call().chatResponse(), "Chat response is null."); | ||
responseText = response.getResult().getOutput().getText(); | ||
} | ||
|
||
return response; | ||
} | ||
} |
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
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.
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.
(Preference)
Looks like here we are mixing system prompt with user prompt, which should not be encouraged. I am assuming this is a simplification for the sake of demonstration. But, I would prefer if we distinguish the usage of user and system message correctly.
That said, SpringAi docs also seems to simply concatenate the messages, which is sus to me. Let me know if I missed something.