雖然 AI 很神奇,不過它不是萬能的,遇到以下幾種問題 AI 就沒轍
第一點我們後續會有專門章節來說明,其他幾點則可靠 Function Call 來擴充 AI 的能力
簡單的說 Function Calling 就像是 AI 的外掛,除了能透過 Function 取得即時資料外,一些複雜的運算或是需要分析的部分,也可以透過 Function 來呼叫外部函式取得結果,下圖就是 Function Calling 的運作流程
每個流程動作如下
return chatModel.call(
new Prompt(
prompt,
OpenAiChatOptions.builder()
.withFunction("CurrectDateTime")
.build())
).getResult().getOutput().getContent();
@Bean
public FunctionCallback currectDateTime() {
return FunctionCallbackWrapper.builder(new CurrectDateTimeFunction())
.withName("CurrectDateTime")
.withDescription("Get the Date Time")
.withResponseConverter((response) -> response.currDateTime().toString())
.build();
}
public Response apply(Request request) {
return new Response(new Date());
}
1-3 項主要是由我們來撰寫,4﹑5 則是 Spring AI 幫我們處理了,還記得 Day5 提到的 FunctionMessage 嗎?這就是 Function Calling 所回傳的解答
接下來就教大家從外部函式的撰寫到提示詞如何調用一步一步帶著大家做
java.util.function
public class CurrectDateTimeFunction implements Function<CurrectDateTimeFunction.Request, CurrectDateTimeFunction.Response>{
@Override
public Response apply(Request request) { //這個函式就是 Function 被呼叫後執行的內容
return new Response(new Date());
}
public record Request(String State){ //其實可以不用請求參數,不過 Function 最少一定要有一個參數
}
public record Response(Date currDateTime) { //回傳的型態
}
}
FunctionCallbackWrapper
將外掛程式包進 Builder 內,這裡須給予幾個設定
@Configuration
public class AiConfig {
@Bean
public FunctionCallback currectDateTime() {
return FunctionCallbackWrapper.builder(new CurrectDateTimeFunction())
.withName("CurrectDateTime") //Function Name
.withDescription("Get the Date Time") //Description
.withResponseConverter((response) -> response.currDateTime().toString())
//回傳結果要如何轉換,一個參數通常都直接使用 .toString()
.build();
}
}
@GetMapping("/func")
public String func(String prompt) {
return chatModel.call(
new Prompt(prompt,
OpenAiChatOptions.builder()
.withFunction("CurrectDateTime")
.build())
).getResult().getOutput().getContent();
}
今天學到的內容:
今天的觀念比較複雜,調用函式寫法也比較抽象,明天會在講更複雜的寫法
今日的程式碼: https://github.com/kevintsai1202/SpringBoot-AI-Day11.git
凱文大叔使用 Java 開發程式超過 20 年,對於 Java 生態非常熟悉,曾使用反射機制開發 ETL 框架,對 Spring 背後的原理非常清楚,目前以 Spring Boot 作為後端開發框架,前端使用 React 搭配 Ant Design
下班之餘在 Amazing Talker 擔任程式語言講師,並獲得學員的一致好評
最近剛成立一個粉絲專頁-凱文大叔教你寫程式 歡迎大家多追蹤,我會不定期分享實用的知識以及程式開發技巧
想討論 Spring 的 Java 開發人員可以加入 FB 討論區 Spring Boot Developer Taiwan
我是凱文大叔,歡迎一起加入學習程式的行列