Class ChatSession (1.0.0)

The ChatSession class is used to make multiturn send message requests. You can instantiate this class by using the startChat method in the GenerativeModel class. The sendMessage method makes an async call to get the response of a chat message at at once. The sendMessageStream method makes an async call to stream the response of a chat message as it's being generated.

Package

@google-cloud/vertexai

Constructors

(constructor)(request, requestOptions)

constructor(request: StartChatSessionRequest, requestOptions?: RequestOptions);

Constructs a new instance of the ChatSession class

Parameters
Name Description
request StartChatSessionRequest

StartChatSessionRequest

requestOptions RequestOptions

Properties

requestOptions

protected readonly requestOptions?: RequestOptions;

Methods

getHistory()

getHistory(): Promise<Content[]>;
Returns
Type Description
Promise<Content[]>

sendMessage(request)

sendMessage(request: string | Array<string | Part>): Promise<GenerateContentResult>;

Makes an async call to send chat message.

The response is returned in GenerateContentResult.response.

Parameter
Name Description
request string | Array<string | Part>

send message request.

Returns
Type Description
Promise<GenerateContentResult>

Promise of GenerateContentResult.

Example

const chat = generativeModel.startChat();
const result1 = await chat.sendMessage("How can I learn more about Node.js?");
console.log('Response: ', JSON.stringify(result1.response));

const result2 = await chat.sendMessage("What about python?");
console.log('Response: ', JSON.stringify(result2.response));

sendMessageStream(request)

sendMessageStream(request: string | Array<string | Part>): Promise<StreamGenerateContentResult>;

Makes an async call to stream send message.

The response is streamed chunk by chunk in StreamGenerateContentResult.stream. The aggregated response is avaliable in StreamGenerateContentResult.response after all chunks are returned.

Parameter
Name Description
request string | Array<string | Part>

send message request.

Returns
Type Description
Promise<StreamGenerateContentResult>

Promise of StreamGenerateContentResult.

Example

const chat = generativeModel.startChat();
const chatInput = "How can I learn more about Node.js?";
const result = await chat.sendMessageStream(chatInput);
for await (const item of result.stream) {
  console.log(item.candidates[0].content.parts[0].text);
}
const response = await result.response;
console.log('aggregated response: ', JSON.stringify(result.response));