1.介绍

chatgpt-spring-boot-starter是一个基于openai-api的启动器,与Springboot集成轻松调用ChatGPT。
它集成了官方api,而非其他开源项目劫取auth-session的做法,所以非常稳定。

项目github地址:chatgpt-spring-boot-starter
Demo github地址:demo-chatgpt-spring-boot-starter

Demo 在线体验(仅供学习使用):Demo ChatGPT

**画面是ChatGPT帮我写的html,非常简陋。如有大佬擅长前端,可提pull request帮忙优化,感谢。文件路径 src/main/resources/static/index.html

2.使用方法

1.添加maven依赖

1
2
3
4
5
<dependency>
<groupId>io.github.flashvayne</groupId>
<artifactId>chatgpt-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>

2.在application.yml配置chatgpt

1
2
3
4
5
6
7
chatgpt:
api-key: xxxxxxxxxxx #your api-key. It can be generated in the link https://beta.openai.com/docs/quickstart/adjust-your-settings
# some properties as below have default values. Of course, you can change them.
# max-tokens: 300 # The maximum number of tokens to generate in the completion.The token count of your prompt plus max_tokens cannot exceed the model's context length. Most models have a context length of 2048 tokens (except for the newest models, which support 4096).
# model: text-davinci-003 # GPT-3 models can understand and generate natural language. We offer four main models with different levels of power suitable for different tasks. Davinci is the most capable model, and Ada is the fastest.
# temperature: 0.0 # What sampling temperature to use. Higher values means the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer.We generally recommend altering this or top_p but not both.
# top-p: 1.0 # An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.We generally recommend altering this or temperature but not both.

3.在任何你想用的地方注入Bean ChatgptService,然后调用它的方法给ChatGPT发消息并获得回复

1
2
3
4
5
6
7
@Autowired
private ChatgptService chatgptService;

public void test(){
String responseMessage = chatgptService.sendMessage("how are you");
System.out.print(responseMessage); //I'm doing well, thank you. How about you?
}

ChatgptService的两个方法:

1
2
String sendMessage(String message); //方法直接返回chatgpt的消息。
ChatResponse sendChatRequest(ChatRequest request); //方法可自定义完整的请求参数和接收完整的api返回信息。

这个Bean是@ConditionalOnMissingBean(ChatgptService.class)条件注入的,如有需要可自定义ChatgptService,重写接口的相关方法覆盖掉默认的实现DefaultChatgptService。

3.其他

如果你对这个项目感兴趣欢迎你star/提交贡献。
如有任何问题,请联系我。
github: flashvayne
email: flashvayne@gmail.com