Skip to content

application.yaml

yaml
server:
  port: 18080

spring:
  application:
    name: spring-ai-alibaba-helloworld

  ai:
    dashscope:
      api-key: ${AI_DASHSCOPE_API_KEY}

apikey填写到系统的环境变量中

key: AI_DASHSCOPE_API_KEY

value: sk-xxxx

pom.xml

xml
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xmlns="http://maven.apache.org/POM/4.0.0"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>com.alibaba.cloud.ai</groupId>
		<artifactId>spring-ai-alibaba-examples</artifactId>
		<version>${revision}</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<artifactId>spring-ai-alibaba-helloworld</artifactId>
	<version>${revision}</version>

	<description>Spring AI Alibaba Helloworld Example</description>
	<name>Spring AI Alibaba Helloworld Examples</name>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>com.alibaba.cloud.ai</groupId>
			<artifactId>spring-ai-alibaba-starter</artifactId>
			<version>${spring-ai-alibaba.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<version>${spring-boot.version}</version>
				<executions>
					<execution>
						<goals>
							<goal>repackage</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-deploy-plugin</artifactId>
				<version>${maven-deploy-plugin.version}</version>
			</plugin>
		</plugins>
	</build>

</project>

HelloworldController

初始化客户端

java
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import jakarta.servlet.http.HttpServletResponse;
import reactor.core.publisher.Flux;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@RestController
@RequestMapping("/helloworld")
public class HelloworldController {

	private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手,请根据用户提问回答!";

	private final ChatClient dashScopeChatClient;

	// 也可以使用如下的方式注入 ChatClient
	 public HelloworldController(ChatClient.Builder chatClientBuilder) {
	  	this.dashScopeChatClient = chatClientBuilder
				.defaultSystem(DEFAULT_PROMPT)
				 // 实现 Chat Memory 的 Advisor
				 // 在使用 Chat Memory 时,需要指定对话 ID,以便 Spring AI 处理上下文。
				 .defaultAdvisors(
						 new MessageChatMemoryAdvisor(new InMemoryChatMemory())
				 )
				 // 实现 Logger 的 Advisor
				 .defaultAdvisors(
						 new SimpleLoggerAdvisor()
				 )
				 // 设置 ChatClient 中 ChatModel 的 Options 参数
				 .defaultOptions(
						 DashScopeChatOptions.builder()
								 .withTopP(0.7)
								 .build()
				 )
				 .build();
	 }
}

1、简单调用

java
@GetMapping("/simple/chat")
	public String simpleChat(@RequestParam(value = "query", defaultValue = "你好,很高兴认识你,能简单介绍一下自己吗?")String query) {

		return dashScopeChatClient.prompt(query).call().content();
	}

测试脚本

python
import streamlit as st
import requests

def get_request(url,):
    response = requests.request("GET", url)
    return response.text


if st.button("请求"):
    st.write(get_request("http://localhost:18080/helloworld/simple/chat"))

提示词

shell
你是一个博学的智能聊天助手,请根据用户提问回答!

调用结果

你好!很高兴认识你。我是通义千问,阿里巴巴集团旗下的超大规模语言模型。我能够回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。我的设计目标是成为一个全方位的智能助手,帮助用户解决各种问题,提供有用的信息和有趣的互动体验。如果你有任何问题或需要帮助,随时告诉我哦!

2、流式调用

java
@GetMapping("/stream/chat")
public Flux<String> streamChat(@RequestParam(value = "query", defaultValue = "你好,很高兴认识你,能简单介绍一下自己吗?")String query, HttpServletResponse response) {

    response.setCharacterEncoding("UTF-8");
    return dashScopeChatClient.prompt(query).stream().content();
}

测试链接

shell
http://localhost:18080/helloworld/stream/chat

3、使用自定义的 Advisor 实现功能增强

java
@GetMapping("/advisor/chat/{id}")
public Flux<String> advisorChat(
        HttpServletResponse response,
        @PathVariable String id,
        @RequestParam String query) {

    response.setCharacterEncoding("UTF-8");

    return this.dashScopeChatClient.prompt(query)
            .advisors(
                    a -> a
                            .param(CHAT_MEMORY_CONVERSATION_ID_KEY, id)
                            .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100)
            ).stream().content();
}

测试链接

shell
http://127.0.0.1:18080/helloworld/advisor/chat/123?query=你好,我叫敏哥,之后的会话中都带上我的名字

输出结果为

你好,敏哥!很高兴认识你,之后的会话中我都会带上你的名字,有什么需要帮忙或者想聊的话题吗?敏哥。 😊

shell
http://127.0.0.1:18080/helloworld/advisor/chat/123?query=我叫什么名字?

输出结果为

敏哥,你叫敏哥呀!如果有其他问题或者需要帮忙的地方,随时告诉我哦! 😊