Skip to content

Commit

Permalink
Fix the issue #124 (#290)
Browse files Browse the repository at this point in the history
  • Loading branch information
junyanxu authored Nov 5, 2024
1 parent 927f6f0 commit 6ec2c27
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
11 changes: 11 additions & 0 deletions src/methods/chat-session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import * as chaiAsPromised from "chai-as-promised";
import * as generateContentMethods from "./generate-content";
import { GenerateContentStreamResult } from "../../types";
import { ChatSession } from "./chat-session";
import { getMockResponse } from "../../test-utils/mock-response";
import * as request from "../requests/request";

use(sinonChai);
use(chaiAsPromised);
Expand All @@ -45,6 +47,15 @@ describe("ChatSession", () => {
);
});
});
describe("sendMessageRecitationErrorNotAddingResponseToHistory()", () => {
it("generateContent errors should be catchable", async () => {
const mockResponse = getMockResponse("unary-failure-citations.json");
stub(request, "makeModelRequest").resolves(mockResponse as Response);
const chatSession = new ChatSession("MY_API_KEY", "a-model");
await chatSession.sendMessage("hello");
expect((await chatSession.getHistory()).length).equals(0);
});
});
describe("sendMessageStream()", () => {
it("generateContentStream errors should be catchable", async () => {
const clock = useFakeTimers();
Expand Down
9 changes: 7 additions & 2 deletions src/methods/chat-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,8 @@ export class ChatSession {
.then((result) => {
if (
result.response.candidates &&
result.response.candidates.length > 0
result.response.candidates.length > 0 &&
result.response.candidates[0]?.content !== undefined
) {
this._history.push(newContent);
const responseContent: Content = {
Expand Down Expand Up @@ -179,7 +180,11 @@ export class ChatSession {
})
.then((streamResult) => streamResult.response)
.then((response) => {
if (response.candidates && response.candidates.length > 0) {
if (
response.candidates &&
response.candidates.length > 0 &&
response.candidates[0]?.content !== undefined
) {
this._history.push(newContent);
const responseContent = { ...response.candidates[0].content };
// Response seems to come back without a role set.
Expand Down
13 changes: 13 additions & 0 deletions test-utils/mock-responses/unary-failure-citations.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"candidates": [
{
"finishReason": "RECITATION",
"index": 0
}
],
"usageMetadata": {
"promptTokenCount": 18,
"totalTokenCount": 18
},
"modelVersion": "gemini-1.5-flash-001"
}

0 comments on commit 6ec2c27

Please sign in to comment.