|
12 | 12 | */ |
13 | 13 | package ch.xxx.aidoclibchat.usecase.service; |
14 | 14 |
|
15 | | -import java.util.List; |
16 | | -import java.util.Map; |
17 | | -import java.util.concurrent.atomic.AtomicReference; |
18 | | - |
19 | 15 | import org.slf4j.Logger; |
20 | 16 | import org.slf4j.LoggerFactory; |
21 | 17 | import org.springframework.ai.chat.client.ChatClient; |
22 | 18 | import org.springframework.ai.chat.client.ChatClient.Builder; |
23 | 19 | import org.springframework.beans.factory.annotation.Value; |
24 | | -import org.springframework.boot.context.properties.bind.ConstructorBinding; |
25 | 20 | import org.springframework.stereotype.Service; |
26 | 21 |
|
27 | | -import com.fasterxml.jackson.annotation.JsonProperty; |
28 | | -import com.fasterxml.jackson.core.JsonProcessingException; |
29 | | -import com.fasterxml.jackson.databind.ObjectMapper; |
30 | | - |
31 | | -import ch.xxx.aidoclibchat.domain.client.OpenLibraryClient; |
32 | | -import ch.xxx.aidoclibchat.domain.client.OpenLibraryClient.FunctionTool.Type; |
33 | | -import ch.xxx.aidoclibchat.domain.client.OpenLibraryClient.Response; |
34 | | - |
35 | 22 | @Service |
36 | 23 | public class FunctionService { |
37 | 24 | private static final Logger LOGGER = LoggerFactory.getLogger(FunctionService.class); |
38 | | - private final ObjectMapper objectMapper; |
39 | 25 | private final ChatClient chatClient; |
40 | | - private final OpenLibraryClient openLibraryClient; |
41 | | - private final List<String> nullCodes = List.of("none", "string"); |
42 | 26 | private final String promptStr = """ |
43 | | - You have access to the following tools: |
44 | | - %s |
45 | | -
|
46 | | - You must follow these instructions: |
47 | | - Always select one or more of the above tools based on the user query |
48 | | - If a tool is found, you must respond in the JSON format matching the following schema: |
49 | | - {"tools": [{ |
50 | | - "tool": "<name of the selected tool>", |
51 | | - "tool_input": "<parameters for the selected tool, matching the tool's JSON schema>" |
52 | | - }]} |
53 | | - Make sure to include all tool parameters in the JSON at tool_input. |
54 | | - If there is no tool that match the user request, you will respond with empty json. |
55 | | - Do not add any additional Notes or Explanations. Respond only with the JSON. |
| 27 | + Make sure to have all the parameters when calling a function. |
| 28 | + If a parameter is missing ask the user for the parameter. |
56 | 29 |
|
57 | 30 | User Query: |
58 | 31 | %s |
59 | 32 | """; |
60 | 33 |
|
61 | | - private record Tool(@JsonProperty("tool") String tool, @JsonProperty("tool_input") Map<String, Object> toolInput) { |
62 | | - @ConstructorBinding |
63 | | - public Tool(String tool, String jsonSchema) { |
64 | | - this(tool, OpenLibraryClient.parseJson(jsonSchema)); |
65 | | - } |
66 | | - } |
67 | | - |
68 | | - private record Tools(@JsonProperty("tools") List<Tool> tools) { |
69 | | - } |
70 | | - |
71 | 34 | @Value("${spring.profiles.active:}") |
72 | 35 | private String activeProfile; |
73 | 36 |
|
74 | | - public FunctionService(ObjectMapper objectMapper, Builder builder, OpenLibraryClient openLibraryClient) { |
75 | | - this.objectMapper = objectMapper; |
| 37 | + public FunctionService(Builder builder) { |
76 | 38 | this.chatClient = builder.build(); |
77 | | - this.openLibraryClient = openLibraryClient; |
78 | 39 | } |
79 | 40 |
|
80 | | - public Response functionCall(String question, Long resultsAmount) { |
| 41 | + public String functionCall(String question, Long resultsAmount) { |
81 | 42 | if (!this.activeProfile.contains("ollama")) { |
82 | | - return new Response(0L, 0L, false, List.of()); |
83 | | - } |
84 | | - var description = "Search for books by author, title or subject."; |
85 | | - var name = "booksearch"; |
86 | | - var aiFunction = new OpenLibraryClient.FunctionTool(Type.FUNCTION, new OpenLibraryClient.FunctionTool.Function( |
87 | | - description, name, Map.of("author", "string", "title", "string", "subject", "string"))); |
88 | | - String jsonStr = ""; |
89 | | - try { |
90 | | - jsonStr = this.objectMapper.writeValueAsString(aiFunction); |
91 | | - } catch (JsonProcessingException e) { |
92 | | - LOGGER.error("Json Mapping failed.", e); |
93 | | - } |
94 | | - var query = String.format(this.promptStr, jsonStr, question); |
95 | | - int aiCallCounter = 0; |
96 | | - var responseRef = new AtomicReference<Response>(new Response(0L, 0L, false, List.of())); |
97 | | - List<Tool> myToolsList = List.of(); |
98 | | - while (aiCallCounter < 3 && myToolsList.isEmpty()) { |
99 | | - aiCallCounter += 1; |
100 | | - var response = this.chatClient.prompt().user(u -> u.text(query)).call().chatResponse().getResult().getOutput().getContent(); |
101 | | - try { |
102 | | - response = response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1); |
103 | | - final var atomicResponse = new AtomicReference<String>(response); |
104 | | - this.nullCodes.forEach(myCode -> { |
105 | | - var myResponse = atomicResponse.get(); |
106 | | - atomicResponse.set(myResponse.replaceAll(myCode, "")); |
107 | | - }); |
108 | | - var myTools = this.objectMapper.readValue(atomicResponse.get(), Tools.class); |
109 | | - // LOGGER.info(myTools.toString()); |
110 | | - myToolsList = myTools.tools().stream() |
111 | | - .filter(myTool1 -> myTool1.toolInput().values().stream() |
112 | | - .filter(myValue -> (myValue instanceof String) && !((String) myValue).isBlank()) |
113 | | - .findFirst().isPresent()) |
114 | | - .toList(); |
115 | | - if (myToolsList.isEmpty()) { |
116 | | - throw new RuntimeException("No parameters found."); |
117 | | - } |
118 | | - } catch (Exception e) { |
119 | | - LOGGER.error("Chatresult Json Mapping failed.", e); |
120 | | - LOGGER.error("ChatResponse: {}", response); |
121 | | - } |
| 43 | + return ""; |
122 | 44 | } |
123 | 45 |
|
124 | | - myToolsList.forEach(myTool -> { |
125 | | - var myRequest = new OpenLibraryClient.Request((String) myTool.toolInput().get("author"), |
126 | | - (String) myTool.toolInput().get("title"), (String) myTool.toolInput().get("subject")); |
127 | | - var myResponse = this.openLibraryClient.apply(myRequest); |
128 | | - // LOGGER.info(myResponse.toString()); |
129 | | - responseRef.set(myResponse); |
130 | | - }); |
131 | | - return responseRef.get(); |
| 46 | + var result = this.chatClient.prompt().user(this.promptStr + question).functions("openLibraryClient").call().content(); |
| 47 | + return result; |
132 | 48 | } |
| 49 | + |
133 | 50 | } |
0 commit comments