Spring Boot项目中使用OpenAI-Java
Posted JoseKe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot项目中使用OpenAI-Java相关的知识,希望对你有一定的参考价值。
目录
前言
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
准备工作
1、初始化一个springboot项目
参考地址:https://joseke.blog.csdn.net/article/details/127196743
2、访问OPENAI官网获取API密钥
地址:https://platform.openai.com/account/api-keys
3、通过OPENA开源的JAVA SDK (OpenAI-Java)访问 API
地址:GitHub - TheoKanning/openai-java: OpenAI GPT-3 Api Client in Java
集成达芬奇模型
1、编写SpringBoot项目中的pom文件
<dependency>
<groupId>com.theokanning.openai-gpt3-java</groupId>
<artifactId>client</artifactId>
<version>0.9.0</version>
</dependency>
2、初始化OpenAiService类
import com.theokanning.openai.OpenAiService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.Duration;
/**
* openai 配置类
*/
@Configuration
public class OpenAiConfiguration
@Value("$open.ai.key")
private String openAiKey;
@Value("$open.ai.request.timeout")
private long timeout;
@Bean
public OpenAiService openAiService()
return new OpenAiService(openAiKey, Duration.ofSeconds(timeout));
3、配置密钥、超时时间和使用的模型
#application.properties
server.port=8081
#密钥
open.ai.key=xxxxxxxx
#超时时间
open.ai.request.timeout=100000
#达芬奇模型
open.ai.model=text-davinci-003
3、编写访问业务类
import com.google.common.collect.Maps;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.Map;
@Slf4j
@Service
public class OpenAiChatBiz
@Value("$open.ai.model")
private String openAiModel;
@Autowired
private OpenAiService openAiService;
/**
* 聊天
* @param prompt
* @return
*/
public String chat(String prompt)
CompletionRequest completionRequest = CompletionRequest.builder()
.prompt(prompt)
.model(openAiModel)
.echo(true)
.temperature(0.7)
.topP(1d)
.frequencyPenalty(0d)
.presencePenalty(0d)
.maxTokens(1000)
.build();
CompletionResult completionResult = openAiService.createCompletion(completionRequest);
String text = completionResult.getChoices().get(0).getText();
return text;
4、编写访问接口
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OpenAiChatApi
@Autowired
private OpenAiChatBiz openAiChatBiz;
@RequestMapping(path = "/chat/question",method = RequestMethod.GET)
public String openAiChat(@RequestParam("question")String question)
if(StringUtils.isBlank(question))
return "Please Input";
return openAiChatBiz.chat(question);
效果展示
使用google的API Tester插件进行测试
在多模块 Spring Boot 项目中使用属性
【中文标题】在多模块 Spring Boot 项目中使用属性【英文标题】:using properties in a multi module Spring Boot project 【发布时间】:2019-02-18 00:23:31 【问题描述】:我正在开发一个多模块 Spring Boot 项目,但遇到了有关保存在 application.properties 文件中的属性的问题。从头开始:
目前我有两个模块:数据和网络。项目结构如下:
parent project
|_ data
|_ web
模块在父 pom 文件中正确命名
<modules>
<module>data</module>
<module>web</module>
</modules>
数据模块负责连接数据库并定义数据访问的存储库。它的 application.properties 文件中有一些属性,其中包含与数据库的连接详细信息
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.username=XXXXXXXX
spring.datasource.password=XXXXXXXXX
在 web 模块中,我想从数据库中读取数据并将其放入 jsp。于是我在web-module的pom中添加了一个依赖到data-module:
<dependency>
<groupId>de.my.fancy.groupId</groupId>
<artifactId>data</artifactId>
<version>$project.version</version>
</dependency>
启动网络模块时出现此错误:
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
我想我可能不得不从数据模块中注入我的配置类,所以我改变了 web 模块的起始类,如下所示:
@SpringBootApplication(exclude= SecurityAutoConfiguration.class, scanBasePackageClasses= JPAConfig.class)
public class WebApplication
@Autowired
JPAConfig config;
public static void main(String[] args)
SpringApplication.run(WebApplication.class, args);
修改后出现如下错误:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-09-13 11:25:21.517 ERROR 8120 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webApplication': Unsatisfied dependency expressed through field 'config'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'JPAConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.datasource.driver-class-name' in value "$spring.datasource.driver-class-name"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:587) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1350) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:580) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at de.fraport.bvd.mobisl.web.WebApplication.main(WebApplication.java:17) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'JPAConfig': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.datasource.driver-class-name' in value "$spring.datasource.driver-class-name"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:379) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1350) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:580) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 19 common frames omitted
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.datasource.driver-class-name' in value "$spring.datasource.driver-class-name"
at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:172) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:124) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:237) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:211) ~[spring-core-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:175) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:839) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1086) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
... 30 common frames omitted
所以似乎我无法从数据模块中的 application.properties 获取属性,以在 web 模块中的注入配置对象中使用。我可以在这里做些什么来让 web 模块中使用的属性?
【问题讨论】:
***.com/a/43222303/9705485 或 ***.com/a/44722003/9705485 可能会有所帮助。也许您可以使用 data.properties 和 PropertySource 您可以在 web 项目(用于最终 jar 的那个)上再次列出属性,或者这可以帮助您解决此问题:***.com/a/35285874/3154883 好吧,太好了!感谢你们俩。听起来不错,我会试一试 【参考方案1】:问题可能在于 application.properties 来自 Web 项目而不是数据。你不能继承这些并且 application.properties 文件没有被聚合,它只是来自链中的最后一个项目。您可以尝试将数据项目中的属性文件重命名为例如data.properties 并确保它已加载 @PropertySource(value = "data.properties"
【讨论】:
以上是关于Spring Boot项目中使用OpenAI-Java的主要内容,如果未能解决你的问题,请参考以下文章
spring-boot学习一:使用Spring Initializr快速创建Spring boot项目
不能在spring boot,gradle项目中使用@Entity注解
如何从 Spring Boot 项目创建 jar,这个 jar 我们想在另一个 Spring Boot 应用程序中使用?