Spring AI 使用教程

avatar
作者
筋斗云
阅读量:1
  1. 创建项目



    勾选Spring Web以及OpenAI

  2. 获取openai-api-key

    访问网址:https://api.xty.app/register?aff=JljC
    注册账号--->添加令牌



    创建成功后可以复制请求的api-key
  3. 配置参数
    spring.application.name=spring-ai-demo  #代理地址 spring.ai.openai.base-url=https://api.xty.app #自己的app-key spring.ai.openai.api-key=sk-NjTrM6e2LlQwAEa52C626754 #AI 模型 spring.ai.openai.chat.options.model=gpt-3.5-turbo
    <dependencies> 		<dependency> 			<groupId>org.springframework.boot</groupId> 			<artifactId>spring-boot-starter-web</artifactId> 		</dependency> 		<dependency> 			<groupId>org.projectlombok</groupId> 			<artifactId>lombok</artifactId> 			<version>1.18.32</version> 		</dependency> 		<dependency> 			<groupId>org.springframework.ai</groupId> 			<artifactId>spring-ai-openai-spring-boot-starter</artifactId> 		</dependency>  		<dependency> 			<groupId>org.springframework.boot</groupId> 			<artifactId>spring-boot-starter-test</artifactId> 			<scope>test</scope> 		</dependency> </dependencies>
  4. 测试接口
    import lombok.extern.slf4j.Slf4j; import org.springframework.ai.chat.ChatResponse; import org.springframework.ai.chat.messages.UserMessage; import org.springframework.ai.chat.prompt.Prompt; import org.springframework.ai.openai.OpenAiChatClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux;  import java.util.HashMap; import java.util.Map;  @Slf4j @RestController public class ZxxOpenAiController {      private final OpenAiChatClient chatClient;      @Autowired     public ZxxOpenAiController(OpenAiChatClient chatClient) {         this.chatClient = chatClient;     }      @GetMapping("/ai/call")     public Map<String, String> call(String message) {         log.info("start method 【call】 param: message=【{}】", message);         String msg = chatClient.call(message);         Map<String, String> result = new HashMap<>();         result.put("msg", msg);         return result;     }  } 

  5. 总结

    Spring AI是一个人工智能工程的应用框架,它结合了Spring生态系统的设计原则和模块化的概念。该框架旨在为Java开发者提供一种更简洁的方式与人工智能进行交互,并降低接入大型语言模型(LLM)的学习成本。

    Spring AI提供了丰富的自然语言处理(NLP)工具,开发人员可以利用这些工具来处理文本数据、执行情感分析、实现语音识别等功能,为开发语言处理应用提供了强大的支持。同时,它还使得机器学习模型的集成变得更加简单,开发人员可以轻松地将训练好的模型嵌入到Spring应用程序中,并利用这些模型进行预测、分类、聚类等任务。此外,Spring AI还提供了图像处理和计算机视觉功能,支持图像识别、目标检测、图像分割等任务。

    Spring AI的核心特性包括跨AI提供商的API支持,提供了一套可移植的API,支持与多个AI服务提供商的聊天、文本到图像和嵌入模型进行交互。它还支持同步和流式API选项,为开发者提供了灵活的交互方式。此外,Spring AI允许开发者通过配置参数访问特定模型的功能,提供了更细致的控制。

    目前,Spring AI已经集成了多个AI服务提供商的API,如OpenAI、Azure OpenAI、Hugging Face和Ollama等。这意味着开发者可以方便地接入这些服务,实现各种人工智能功能。

    综上所述,Spring AI是一个功能强大、易于使用的人工智能应用框架,为Java开发者提供了与人工智能交互的便捷方式,并简化了AI应用的开发过程。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!