Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test: tests for chat-gpt.ts #47

Merged
merged 11 commits into from
Feb 27, 2024
4 changes: 4 additions & 0 deletions jest-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
process.env['AZURE_OPENAI_ENDPOINT'] = 'test_endpoint';
process.env['AZURE_OPENAI_KEY'] = 'test_api_key';
process.env['CLIENT_EMAIL'] = '[email protected]';
process.env['GOOGLE_PRIVATE_KEY'] = 'test_private_key';
5 changes: 3 additions & 2 deletions jest.config.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"preset": "ts-jest"
}
"preset": "ts-jest",
"setupFiles": ["<rootDir>/jest-setup.ts"]
}
88 changes: 88 additions & 0 deletions src/libs/chat-gpt.test.ts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it'd be worth adding logic into the function itself that will check for empty comments array and return early if they're missing

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@namanaman Do you think it would be better to put this behavior directly into the summary handler (rather than in getSummary) so that getSummary is only being called when there are any relevant comments? Something like the below:

...
const summary: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async (
  event
) => {
  const { pageURL } = event.body;
  const dataReach = pageURL.includes('uistatus')
    ? INPUT_SIZE_FREQUENT
    : INPUT_SIZE_SPARSE;

  try {
    const client = await getAuthClient();
    const data = await getLastNComments(client, dataReach);

    const filteredData = data.filter((v) =>
      v[SHEETS_COLUMN_MAP[Feedback.PageURL]].includes(pageURL)
    );

///////// Something like this /////////
    if (filteredData.length === 0) {
      return formatJSONResponse({
        message: 'No comments found for the specified URL',
        dataSize: 0
      });
    }

    const cleanedComments = filteredData.map((v) =>
      v[SHEETS_COLUMN_MAP[Feedback.Comment]].trim()
    );
    const dataSummary = await getSummary(cleanedComments, pageURL);
...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, I think this behavior could belong in both places, so I will put this in the getSummary for now, and when I work on the summary handler file, I can think about adding it in as well.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call! Yea I think it makes sense in both places as well. I could see us using the ChatGPT function separately from the summary handler in our next work, so having a stopgap there is nice too

Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { getSummary } from './chat-gpt';
import { OpenAIClient } from '@azure/openai';

const MOCK_CHAT_COMPLETIONS = jest.fn().mockImplementation(() => ({
choices: [{ message: { content: 'mocked response' } }]
}));

jest.mock('@azure/openai', () => {
const originalModule = jest.requireActual('@azure/openai');
return {
...originalModule,
OpenAIClient: jest.fn().mockImplementation(() => ({
getChatCompletions: MOCK_CHAT_COMPLETIONS
}))
};
});

describe('getSummary', () => {
const comments = ['Test Comment 1', 'Test Comment 2'];
const userContent = `---\nTest Comment 1\nTest Comment 2---`;

afterEach(() => {
jest.clearAllMocks();
});

it('should use the expected arguments and return a string response', async () => {
const pageURL = 'https://uistatus.dol.state.nj.us/';
const programName = 'Unemployment Insurance benefits';
const systemContent = `You are an assistant designed to find the most common themes in a large dataset of free text. Users will send a list of comments written by residents of New Jersey about their experience applying for ${programName}, where each line represents one comment. You will find the 10 most common themes in the data, and for each theme, you will include a theme title, theme description, and 3 real comments (actually in the dataset, not generated) that fit the given theme. Your output will be in the following structured valid JSON format: {"themes":[{"title":"title 1","description":"description 1","actualComments":["real comment 1","real comment 2","real comment 3"]},{"title":"title 2","description":"description 2","actualComments":["real comment 1","real comment 2","real comment 3"]}, ...]}. Make sure that the 3 comments are in the user-provided list of comments, not generated. Make sure the output is in valid JSON format, and do not add trailing commas.`;
const deployment_id = 'gpt-35-turbo-16k';
const prompt = [
{ role: 'system', content: systemContent },
{ role: 'user', content: userContent }
];
const result = await getSummary(comments, pageURL);
expect(MOCK_CHAT_COMPLETIONS).toHaveBeenCalledTimes(1);
const mockChatCompletionsArgs = MOCK_CHAT_COMPLETIONS.mock.calls[0];
expect(Array.isArray(mockChatCompletionsArgs)).toBe(true);
expect(mockChatCompletionsArgs[0]).toBe(deployment_id);
expect(mockChatCompletionsArgs[1][0]).toMatchObject(prompt[0]);
expect(mockChatCompletionsArgs[1][1]).toMatchObject(prompt[1]);
expect(result).toBe('mocked response');
});

it('should return "{}" and not call OpenAIClient when there are no comments', async () => {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test to check empty comment array behavior

const comments = [];
const pageURL = 'https://uistatus.dol.state.nj.us/';
const result = await getSummary(comments, pageURL);
expect(OpenAIClient).toHaveBeenCalledTimes(0);
expect(result).toBe('{}');
});

describe('getSummary with different URLs', () => {
const cases = [
['Unemployment Insurance benefits', 'https://uistatus.dol.state.nj.us/'],
[
'Temporary Disability Insurance and Family Leave Insurance benefits',
'https://www.nj.gov/labor/myleavebenefits/'
],
['', 'https://www.example.com']
];

it.each(cases)(
'should utilize a prompt referencing "%s" benefits when page URL is %s',
async (programName, pageURL) => {
const systemContent = `You are an assistant designed to find the most common themes in a large dataset of free text. Users will send a list of comments written by residents of New Jersey about their experience applying for ${programName}, where each line represents one comment. You will find the 10 most common themes in the data, and for each theme, you will include a theme title, theme description, and 3 real comments (actually in the dataset, not generated) that fit the given theme. Your output will be in the following structured valid JSON format: {"themes":[{"title":"title 1","description":"description 1","actualComments":["real comment 1","real comment 2","real comment 3"]},{"title":"title 2","description":"description 2","actualComments":["real comment 1","real comment 2","real comment 3"]}, ...]}. Make sure that the 3 comments are in the user-provided list of comments, not generated. Make sure the output is in valid JSON format, and do not add trailing commas.`;
jasnoo marked this conversation as resolved.
Show resolved Hide resolved
await getSummary(comments, pageURL);
expect(MOCK_CHAT_COMPLETIONS.mock.calls[0][1][0].content).toEqual(
systemContent
);
}
);
});

it('should throw an error on failure', async () => {
const testErrorMessage = 'Test Error';
(OpenAIClient as jest.Mock).mockImplementation(() => ({
getChatCompletions: jest
.fn()
.mockRejectedValue(new Error(testErrorMessage))
}));
const expectedErrorMessage = `Azure OpenAI getChatCompletions failed with error: ${testErrorMessage}`;
const pageURL = 'https://www.nj.gov/labor/myleavebenefits/';
await expect(getSummary(comments, pageURL)).rejects.toThrow(
expectedErrorMessage
);
});
});
3 changes: 3 additions & 0 deletions src/libs/chat-gpt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ const PARAMETERS = {
const DEPLOYMENT_ID = 'gpt-35-turbo-16k';

export async function getSummary(comments: string[], pageURL: string) {
if (comments.length === 0) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated to handle empty array comment here

return '{}';
}
const client = new OpenAIClient(ENDPOINT, new AzureKeyCredential(API_KEY), {
apiVersion: API_VERSION
});
Expand Down