-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ChatSession.java
177 lines (164 loc) · 6.34 KB
/
ChatSession.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.vertexai.generativeai;
import static com.google.cloud.vertexai.generativeai.ResponseHandler.aggregateStreamIntoResponse;
import static com.google.cloud.vertexai.generativeai.ResponseHandler.getContent;
import static com.google.cloud.vertexai.generativeai.ResponseHandler.getFinishReason;
import com.google.api.core.BetaApi;
import com.google.cloud.vertexai.api.Candidate.FinishReason;
import com.google.cloud.vertexai.api.Content;
import com.google.cloud.vertexai.api.GenerateContentResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** Represents a conversation between the user and the model */
public final class ChatSession {
private final GenerativeModel model;
private List<Content> history = new ArrayList<>();
private ResponseStream<GenerateContentResponse> currentResponseStream = null;
private GenerateContentResponse currentResponse = null;
@BetaApi
public ChatSession(GenerativeModel model) {
if (model == null) {
throw new IllegalArgumentException("model should not be null");
}
this.model = model;
}
/**
* Sends a message to the model and returns a stream of responses.
*
* @param text the message to be sent.
* @return an iterable in which each element is a GenerateContentResponse. Can be converted to
* stream by stream() method.
*/
@BetaApi
public ResponseStream<GenerateContentResponse> sendMessageStream(String text) throws IOException {
return sendMessageStream(ContentMaker.fromString(text));
}
/**
* Sends a message to the model and returns a stream of responses.
*
* @param content the content to be sent.
* @return an iterable in which each element is a GenerateContentResponse. Can be converted to
* stream by stream() method.
*/
@BetaApi
public ResponseStream<GenerateContentResponse> sendMessageStream(Content content)
throws IOException, IllegalArgumentException {
checkLastResponseAndEditHistory();
history.add(content);
ResponseStream<GenerateContentResponse> respStream = model.generateContentStream(history);
currentResponseStream = respStream;
currentResponse = null;
return respStream;
}
/**
* Sends a message to the model and returns a response.
*
* @param text the message to be sent.
* @return a response.
*/
@BetaApi
public GenerateContentResponse sendMessage(String text) throws IOException {
return sendMessage(ContentMaker.fromString(text));
}
/**
* Sends a message to the model and returns a response.
*
* @param content the content to be sent.
* @return a response.
*/
@BetaApi
public GenerateContentResponse sendMessage(Content content) throws IOException {
checkLastResponseAndEditHistory();
history.add(content);
GenerateContentResponse response = model.generateContent(history);
currentResponse = response;
currentResponseStream = null;
return response;
}
private void removeLastContent() {
int lastIndex = history.size() - 1;
history.remove(lastIndex);
}
/**
* Checks whether the last response is available and edit the history if necessary.
*
* @throws IllegalStateException if the response stream is not finished.
*/
private void checkLastResponseAndEditHistory() {
if (currentResponseStream == null && currentResponse == null) {
return;
} else if (currentResponseStream != null && !currentResponseStream.isConsumed()) {
throw new IllegalStateException("Response stream is not consumed");
} else if (currentResponseStream != null && currentResponseStream.isConsumed()) {
GenerateContentResponse response = aggregateStreamIntoResponse(currentResponseStream);
FinishReason finishReason = getFinishReason(response);
if (finishReason != FinishReason.STOP && finishReason != FinishReason.MAX_TOKENS) {
// We also remove the request from the history.
removeLastContent();
currentResponseStream = null;
throw new IllegalStateException(
String.format(
"The last round of conversation will not be added to history because response"
+ " stream did not finish normally. Finish reason is %s.",
finishReason));
}
history.add(getContent(response));
} else if (currentResponseStream == null && currentResponse != null) {
FinishReason finishReason = getFinishReason(currentResponse);
if (finishReason != FinishReason.STOP && finishReason != FinishReason.MAX_TOKENS) {
// We also remove the request from the history.
removeLastContent();
currentResponse = null;
throw new IllegalStateException(
String.format(
"The last round of conversation will not be added to history because response did"
+ " not finish normally. Finish reason is %s.",
finishReason));
}
history.add(getContent(currentResponse));
currentResponse = null;
}
}
/**
* Returns the history of the conversation.
*
* @return an unmodifiable history of the conversation.
*/
@BetaApi
public List<Content> getHistory() {
try {
checkLastResponseAndEditHistory();
} catch (IllegalStateException e) {
if (e.getMessage()
.contains("The last round of conversation will not be added to history because")) {
IllegalStateException modifiedExecption =
new IllegalStateException("Rerun getHistory() to get cleaned history.");
modifiedExecption.initCause(e);
throw modifiedExecption;
}
throw e;
}
return Collections.unmodifiableList(history);
}
/** Set the history to a list of Content */
@BetaApi
public void setHistory(List<Content> history) {
this.history = history;
}
}