为了更好地理解Spring AI是如何实现的,建议更好地理解AI概念。
什么是Spring AI项目
Spring AI项目的创建是为了加快开发可以使用人工智能资源且不太复杂的应用程序。
该项目的灵感来自LangChain和LlamaIndex,两者都是用Python开发的,但生成式AI应用的浪潮不仅仅来自Python开发人员。
Spring AI提供了抽象,因此即使在 AI 发生变化的情况下,也只会进行最少的代码更改。
Ollama是什么?
Ollama是一个用于在本地运行大型语言模型 (LLM) (称为模型)的简化工具。使用Ollama可以运行开源模型,例如:
除其他外。您可以在此处查看型号列表。对于我们的示例,我们将使用Llama2模型。
什么是Llama2?
Llama2是Meta的开源模型。该模型可以出于个人、研究或商业目的免费分发。
对于我们的示例,我们将创建一个 REST API 来使用Spring AI与Ollama进行交互。
让我们来看看代码吧!
首先,我们在start.spring.io创建一个新项目。
我们的示例所需的唯一依赖项是Spring Web。
由于 Spring AI 仍然是一个实验项目,它还没有正式出现在Spring Initializr中,因此您需要在pom.xml中配置 SNAPSHOTS 存储库:
<repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </repository> </repositories>
|
接下来,我们将添加 Spring AI 依赖项,该依赖项具有与 Ollama 集成的 API。为此,请添加到pom.xml:
<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-ollama-spring-boot-starter</artifactId> <version>0.8.0</version> </dependency>
|
由于我们将使用 Ollama,因此我们将在application.yml文件中定义它:
spring: ai: ollama: chat: options: model: llama2
|
为了与 Ollama 集成,我们将使用ChatClient类,称为call(Prompt prompt).让我们创建一个注入ChatClient的 bean并使用以下方法:
@Component public class ChatAiClient {
private final ChatClient chatClient;
public ChatAiClient(ChatClient chatClient) { this.chatClient = chatClient; }
public String chat(String question) { var aiResponse = this.chatClient.call(new Prompt(question)); var response = aiResponse.getResult().getOutput().getContent();
return response; } }
|
该方法chat将接收提示作为参数,传递给API并返回AI响应。
现在我们将创建controller并records通过 REST API 进行集成。首先让我们分别创建 orequest和 o response:
record QuestionRequest(String question) {}
record Response(String response) {}
接下来我们将创建controller通过路径响应的内容/ask:
@RestController public class AskQuestionController {
private final ChatAiClient chatClient;
public AskQuestionController(ChatAiClient chatClient) { this.chatClient = chatClient; }
@PostMapping("/ask") public Response ask(@RequestBody QuestionRequest questionRequest) { return new Response(chatClient.chat(questionRequest.question())); } }
|
应用程序初始化后,您可以运行curl:
curl --location 'http://localhost:8080/ask' \ --header 'Content-Type: application/json' \ --data '{ "question": "给我讲个笑话吗?" }'
|
测试时的响应如下:
{ "response": "为什么这本数学书很难过?因为它的问题太多了!" }
|
结论
对于Spring AI的Milestones版本,现在可以与市场上主要的人工智能集成,并将此功能添加到您的系统、产品或项目中。这个项目将会发生很大的变化,就像人工智能的发展一样。
如果您想查看完整的示例,只需访问示例github 。