大家好 這里是蘇澤 后端是工作 ai是興趣?
對于ai的產生我的立場是擁抱ai的? 是希望拿他作為提升能力的工具? 那么這一篇帶大家來學習如何使用ai打造一個專屬的業務大模型?
需求 就是說假設現在有一個 商城系統 里面有查詢訂單的api和獲取商品購買方式的api? ?用戶只需要輸入 “幫我看看我前幾天買過最便宜的衣服”? 經過語言處理 ai就能夠調用 查詢訂單的api并在里面自動的添加查詢條件以及 排序條件??這是我們的目標? 本文就是來講解實現這樣的目標
Spring AI介紹
Spring AI 是 AI 工程師的一個應用框架,它提供了一個友好的 API 和開發 AI 應用的抽象,旨在簡化 AI 應用的開發工序。
提供對常見模型的接入能力,目前已經上架 https://start.spring.io/,提供大家測試訪問。(請注意雖然已經上架 start.spring.io,但目前還是在 Spring 私服,未發布至 Maven 中央倉庫)
基本知識講解:
函數調用
函數調用(Function Calling)是OpenAI
在2023年6月13日對外發布的新能力。根據OpenAI官方博客描述,函數調用能力可以讓大模型輸出一個請求調用函數的消息,其中包含所需調用的函數信息、以及調用函數時所攜帶的參數信息。這是一種將大模型
(LLM)能力與外部工具/API
連接起來的新方式。
比如用戶輸入:
What’s the weather like in Tokyo?
使用function calling,可實現函數執行get_current_weather(location: string)
,從而獲取函數輸出,即得到對應地理位置的天氣情況。這其中,location
這個參數及其取值是借助大模型能力從用戶輸入中抽取出來的,同時,大模型判斷得到調用的函數為get_current_weather
。
開發人員可以使用大模型的function calling能力實現:
- 在進行自然語言交流時,通過調用外部工具回答問題(類似于ChatGPT插件);
- 將自然語言轉換為調用API調用,或數據庫查詢語句;
- 從文本中抽取結構化數據
- 其它
實現步驟
1. 添加依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-openai-spring-boot-starter</artifactId></dependency><!-- 配置 Spring 倉庫 --><repositories><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></repository></repositories>
2. 配置 OpenAI 相關參數
spring:
??ai:
????openai:
??????base-url:?#?支持?openai-sb、openai-hk?等中轉站點,如用官方則不填
??????api-key:?sk-xxxx
?
3.創建一個Spring Controller處理HTTP請求。
在Spring項目中創建一個Controller類,用于處理提取要素的HTTP請求和生成調用的API和變量集合。
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;
import java.util.Map;@RestController
public class ElementExtractionController {@Autowiredprivate ElementExtractionService elementExtractionService;@PostMapping("/extract-elements")public ResponseEntity<Map<String, Object>> extractElements(@RequestBody String userInput) {Map<String, Object> result = elementExtractionService.extractElements(userInput);return ResponseEntity.ok(result);}
}
3.創建一個ElementExtractionService服務類來提取要素
創建一個服務類,用于封裝提取要素的邏輯。在這個服務類中,可以使用自然語言處理技術來分析用戶輸入并提取需求和變量。可以使用現有的開源NLP庫或API,如NLTK、SpaCy、Stanford CoreNLP、Google Cloud Natural Language API等
這里使用NLTK庫來進行文本分析和實體識別,以提取用戶輸入中的需求和變量:
import org.springframework.stereotype.Service;
import edu.stanford.nlp.simple.Document;
import edu.stanford.nlp.simple.Sentence;import java.util.HashMap;
import java.util.List;
import java.util.Map;@Service
public class ElementExtractionService {public Map<String, Object> extractElements(String userInput) {// 使用NLTK庫進行文本分析和實體識別Document doc = new Document(userInput);List<Sentence> sentences = doc.sentences();// 提取需求String requirement = extractRequirement(sentences);// 提取變量Map<String, String> variables = extractVariables(sentences);// 構建結果Map<String, Object> result = new HashMap<>();result.put("api", requirement);result.put("variables", variables);return result;}private String extractRequirement(List<Sentence> sentences) {// 在這里根據實際需求,從句子中提取需求// 可以使用關鍵詞提取、模式匹配等方法// 這里示例直接返回第一句話作為需求if (!sentences.isEmpty()) {return sentences.get(0).text();}return "";}private Map<String, String> extractVariables(List<Sentence> sentences) {// 在這里根據實際需求,從句子中提取變量// 可以使用實體識別、關鍵詞提取等方法// 這里示例直接從第一句話中提取名詞作為變量Map<String, String> variables = new HashMap<>();if (!sentences.isEmpty()) {Sentence sentence = sentences.get(0);for (String word : sentence.words()) {if (isNoun(word)) {variables.put(word, "true");}}}return variables;}private boolean isNoun(String word) {// 在這里根據實際需求,判斷一個詞是否為名詞// 可以使用詞性標注、詞典匹配等方法// 這里示例簡單判斷是否以大寫字母開頭,作為名詞的判斷條件return Character.isUpperCase(word.charAt(0));}
}
那么下一步 :
4.封裝一個API來操作open ai的Assistants API
創建一個Spring Service來操作OpenAI Assistants API。
創建一個服務類,用于封裝操作OpenAI Assistants API的邏輯。
import com.google.gson.Gson;
import okhttp3.*;import org.springframework.stereotype.Service;import java.io.IOException;@Service
public class OpenAIAssistantsService {public String callOpenAIAssistantsAPI(String prompt) {OkHttpClient client = new OkHttpClient();MediaType mediaType = MediaType.parse("application/json");JsonObject requestBody = new JsonObject();requestBody.addProperty("prompt", prompt);requestBody.addProperty("max_tokens", 32);requestBody.addProperty("stop", null);RequestBody body = RequestBody.create(mediaType, requestBody.toString());Request request = new Request.Builder().url(OPENAI_API_URL).post(body).addHeader("Authorization", "Bearer " + OPENAI_API_KEY).build();try {Response response = client.newCall(request).execute();if (response.isSuccessful()) {String responseBody = response.body().string();JsonObject jsonObject = new Gson().fromJson(responseBody, JsonObject.class);return jsonObject.getAsJsonObject("choices").get(0).getAsJsonObject().get("text").getAsString();} else {System.out.println("OpenAI Assistants API調用失敗: " + response.code() + " - " + response.message());}} catch (IOException e) {System.out.println("OpenAI Assistants API調用異常: " + e.getMessage());}return null;}
}
創建一個自定義函數簽名。
創建一個函數,它將調用其他項目中的API,并返回結果。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class CustomFunctionService {@Autowiredprivate OtherAPIService otherAPIService;public String customFunction(String apiId, String inputParameters) {// 根據API的ID篩選需要調用的APIString apiEndpoint = getApiEndpoint(apiId);// 調用其他項目中的API,并進行處理String result = otherAPIService.callOtherAPI(apiEndpoint, inputParameters);// 對結果進行處理,并返回return "處理后的結果:" + result;}private String getApiEndpoint(String apiId) {//這里還會有很多具體業務的api就不一一列舉了// 根據API的ID獲取相應的API的URL或其他信息// 這里可以根據實際情況進行實現if (apiId.equals("api1")) {return "https://api.example.com/api1";} else if (apiId.equals("api2")) {return "https://api.example.com/api2";} else {throw new IllegalArgumentException("無效的API ID: " + apiId);}}
}
創建一個Spring Controller來調用自定義函數。
創建一個Controller類,它將調用自定義函數,并返回結果。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;
import java.util.Map;@RestController
public class CustomFunctionController {@Autowiredprivate CustomFunctionService customFunctionService;@PostMapping("/call-custom-function")public ResponseEntity<String> callCustomFunction(@RequestBody String userInput) {String result = customFunctionService.customFunction(userInput);return ResponseEntity.ok(result);}
}
在上面提取要素的服務(ElementExtractionService)的基礎上,我們可以再封裝一個Assistants服務,它將接受用戶的請求并調用提取要素的服務。然后,Assistants服務將提取的要素和變量(uid)作為輸入傳遞給封裝了OpenAI的服務(OpenAIAssistantsService),并根據要素選擇適當的API進行調用,并返回對應的結果。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.Map;@Service
public class AssistantsService {@Autowiredprivate ElementExtractionService elementExtractionService;@Autowiredprivate OpenAIAssistantsService openAIAssistantsService;public String processUserRequest(String userInput) {// 提取要素Map<String, Object> elements = elementExtractionService.extractElements(userInput);// 獲取要素和變量String requirement = (String) elements.get("api");Map<String, String> variables = (Map<String, String>) elements.get("variables");String uid = (String) elements.get("uid");// 調用OpenAI Assistants服務String result = openAIAssistantsService.callOpenAIAssistantsAPI(requirement, variables, uid);return result;}
}
AssistantsService類接受用戶的請求,并調用ElementExtractionService來提取要素。然后,它獲取要素、變量和uid,并將它們作為參數傳遞給OpenAIAssistantsService的callOpenAIAssistantsAPI方法。該方法根據要素選擇適當的API進行調用,并返回結果。
具體的業務實現“提取要素”的邏輯部分
請注意,為了實現這個過程,還需要修改ElementExtractionService中提取要素的邏輯,以確保這個服務能符合具體業務的邏輯? 例如我提到的 “幫我看看我買過最便宜的衣服”
import org.springframework.stereotype.Service;
import edu.stanford.nlp.simple.Document;
import edu.stanford.nlp.simple.Sentence;import java.util.HashMap;
import java.util.List;
import java.util.Map;@Service
public class ElementExtractionService {public Map<String, Object> extractElements(String userInput) {// 使用NLTK庫進行文本分析和實體識別Document doc = new Document(userInput);List<Sentence> sentences = doc.sentences();// 提取需求String requirement = extractRequirement(sentences);// 提取變量Map<String, String> variables = extractVariables(sentences);// 構建結果Map<String, Object> result = new HashMap<>();result.put("api", requirement);result.put("variables", variables);return result;}private String extractRequirement(List<Sentence> sentences) {// 在這里根據實際需求,從句子中提取需求// 可以使用關鍵詞提取、模式匹配等方法// 這里示例直接返回第一句話作為需求if (!sentences.isEmpty()) {return sentences.get(0).text();}return "";}private Map<String, String> extractVariables(List<Sentence> sentences) {// 在這里根據實際需求,從句子中提取變量// 可以使用實體識別、關鍵詞提取等方法// 這里示例從第一句話中提取名詞作為變量,并根據特定模式進行匹配Map<String, String> variables = new HashMap<>();if (!sentences.isEmpty()) {Sentence sentence = sentences.get(0);List<String> words = sentence.words();for (int i = 0; i < words.size() - 1; i++) {String currentWord = words.get(i);String nextWord = words.get(i + 1);if (isNoun(currentWord) && nextWord.equals("的")) {variables.put(currentWord, "true");}}}return variables;}private boolean isNoun(String word) {// 在這里根據實際需求,判斷一個詞是否為名詞// 可以使用詞性標注、詞典匹配等方法// 這里示例簡單判斷是否以大寫字母開頭,作為名詞的判斷條件return Character.isUpperCase(word.charAt(0));}
}
我將extractVariables方法進行了修改。現在它從第一句話中提取名詞作為變量,并且根據特定模式進行匹配。特定模式是判斷當前詞是否為名詞,以及下一個詞是否為"的"。如果匹配成功,則將當前詞作為變量存儲。
這樣我們就基本實現了一開始的那個目標:
假設現在有一個 商城系統 里面有查詢訂單的api和獲取商品購買方式的api? ?用戶只需要輸入 “幫我看看我前幾天買過最便宜的衣服”? 經過語言處理 ai就能夠調用 查詢訂單的api并在里面自動的添加查詢條件以及 排序條件??這是我們的目標? 本文就是來講解實現這樣的目標
更長遠的目標:
希望能夠開發出一款中間件(作為一個服務被注冊到項目當中)?能夠作為open ai 和具體項目的橋梁? 即在開發配置當中我輸入我的已有項目的服務的簽名?? 那這個助手能夠根據用戶的自然語言輸入 自動的去調用執行 項目中已有的各種服務 來做各種各樣的復雜的數據庫查詢 等操作
本文所受啟發 參考文獻:
- Function calling and other API updates:?https://openai.com/blog/function-calling-and-other-api-updates
- OpenAI assistants in LangChain:?https://python.langchain.com/docs/modules/agents/agent_types/openai_assistants
- Multi-Input Tools in LangChain:?https://python.langchain.com/docs/modules/agents/tools/multi_input_tool
- examples/Assistants_API_overview_python.ipynb:?https://github.com/openai/opena...
- The Spring Boot Actuator is the one dependency you should include in every project (danvega.dev)
- Assistants API won't allow external web request - API - OpenAI Developer Forum
?
本文只是簡單提供一個可行的思路做參考 真正做出可拓展性的ai開發插件道路還很長 先在這立個小flag吧? 希望今年能夠完成這個小目標? 如果有一起開發這個項目的伙伴可以跟我來討論哦
?