这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions spring-ai-modules/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
</parent>

<modules>
<module>spring-ai-chat-stream</module>
<module>spring-ai-introduction</module>
<module>spring-ai-mcp</module>
<module>spring-ai-text-to-sql</module>
Expand Down
99 changes: 99 additions & 0 deletions spring-ai-modules/spring-ai-chat-stream/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-ai-chat-stream</artifactId>
<version>0.0.1</version>
<name>spring-ai-chat-stream</name>

<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-ai-modules</artifactId>
<version>0.0.1</version>
<relativePath>../pom.xml</relativePath>
</parent>

<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<properties>
<java.version>21</java.version>
<spring-ai.version>1.0.1</spring-ai.version>
<spring-boot.version>3.5.5</spring-boot.version>
</properties>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<release>${java.version}</release>
</configuration>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.baeldung.springai.streaming;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.baeldung.springai.streaming;

import javax.validation.Valid;

import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@Validated
public class ChatController {

private final ChatService chatService;

public ChatController(ChatService chatService) {
this.chatService = chatService;
}

@PostMapping(value = "/chat")
public Mono<String> chat(@RequestBody @Valid ChatRequest request) {
return chatService.chatAsWord(request.getPrompt())
.collectList()
.map(list -> String.join("", list));
}

@PostMapping(value = "/chat-word", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> chatAsWord(@RequestBody @Valid ChatRequest request) {
return chatService.chatAsWord(request.getPrompt());
}

@PostMapping(value = "/chat-chunk", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> chatAsChunk(@RequestBody @Valid ChatRequest request) {
return chatService.chatAsChunk(request.getPrompt());
}

@PostMapping(value = "/chat-json", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> chatAsJson(@RequestBody @Valid ChatRequest request) {
return chatService.chatAsJson(request.getPrompt());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.baeldung.springai.streaming;

import javax.validation.constraints.NotNull;

public class ChatRequest {

@NotNull
private String prompt;

public String getPrompt() {
return prompt;
}

public void setPrompt(String prompt) {
this.prompt = prompt;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
package com.baeldung.springai.streaming;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.stereotype.Component;

import reactor.core.publisher.Flux;

@Component
public class ChatService {

private final ChatClient chatClient;

public ChatService(ChatModel chatModel) {
this.chatClient = ChatClient.builder(chatModel)
.build();
}

public Flux<String> chat(String prompt) {
return chatClient.prompt()
.user(userMessage -> userMessage.text(prompt))
.stream()
.content();
}

public Flux<String> chatAsWord(String prompt) {
return chatClient.prompt()
.user(userMessage -> userMessage.text(prompt))
.stream()
.content();
}

public Flux<String> chatAsChunk(String prompt) {
return chatClient.prompt()
.user(userMessage -> userMessage.text(prompt))
.stream()
.content()
.transform(flux -> toChunk(flux, 100));
}

public Flux<String> chatAsJson(String prompt) {
return chatClient.prompt()
.system(systemMessage -> systemMessage.text(
"""
Respond in NDJSON format.
Each JSON object should contains around 100 characters.
Sample json object format: {"part":0,"text":"Once in a small town..."}
"""))
.user(userMessage -> userMessage.text(prompt))
.stream()
.content()
.transform(this::toJsonChunk);
}

private Flux<String> toChunk(Flux<String> tokenFlux, int chunkSize) {
return Flux.create(sink -> {
StringBuilder buffer = new StringBuilder();
tokenFlux.subscribe(
token -> {
buffer.append(token);
if (buffer.length() >= chunkSize) {
sink.next(buffer.toString());
buffer.setLength(0);
}
},
sink::error,
() -> {
if (buffer.length() > 0) {
sink.next(buffer.toString());
}
sink.complete();
}
);
});
}

private Flux<String> toJsonChunk(Flux<String> tokenFlux) {
return Flux.create(sink -> {
StringBuilder buffer = new StringBuilder();
tokenFlux.subscribe(
token -> {
buffer.append(token);
int idx;
if ((idx = buffer.indexOf("\n")) >= 0) {
String line = buffer.substring(0, idx);
sink.next(line);
buffer.delete(0, idx + 1);
}
},
sink::error,
() -> {
if (buffer.length() > 0) {
sink.next(buffer.toString());
}
sink.complete();
}
);
});
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
spring:
ai:
openai:
api-key: "<YOUR-API-KEY>"
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{yyyy-MM-dd HH:mm:ss}] [%p] [%c{1}] - %m%n</pattern>
</encoder>
</appender>

<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>

<logger name="org.springframework" level="INFO" additivity="false">
<appender-ref ref="CONSOLE" />
</logger>
</configuration>