Skip to content

Commit

Permalink
Fixes context middleware to append to user message only. (#591)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbleigh authored Jul 11, 2024
1 parent 7722b5b commit fd9873f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
2 changes: 1 addition & 1 deletion js/ai/src/model/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ export function augmentWithContext(
return (req, next) => {
// if there is no context in the request, no-op
if (!req.context?.length) return next(req);
const userMessage = req.messages.at(-1);
const userMessage = lastUserMessage(req.messages);
// if there are no messages, no-op
if (!userMessage) return next(req);
// if there is already a context part, no-op
Expand Down
22 changes: 20 additions & 2 deletions js/ai/tests/model/middleware_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,16 @@ import assert from 'node:assert';
import { beforeEach, describe, it } from 'node:test';
import { DocumentData } from '../../src/document.js';
import {
defineModel,
GenerateRequest,
GenerateResponseData,
MessageData,
Part,
defineModel,
} from '../../src/model.js';
import {
augmentWithContext,
AugmentWithContextOptions,
CONTEXT_PREFACE,
augmentWithContext,
simulateSystemPrompt,
validateSupport,
} from '../../src/model/middleware.js';
Expand Down Expand Up @@ -414,6 +414,24 @@ describe('augmentWithContext', () => {
});
});

it('should append to the last user message', async () => {
const messages: MessageData[] = [
{ role: 'user', content: [{ text: 'first part' }] },
{
role: 'tool',
content: [{ toolResponse: { name: 'testTool', output: { abc: 123 } } }],
},
];
const result = await testRequest(messages, [
{ content: [{ text: 'i am context' }] },
{ content: [{ text: 'i am more context' }] },
]);
assert.deepEqual(result[0].content.at(-1), {
text: `${CONTEXT_PREFACE}- [0]: i am context\n- [1]: i am more context\n\n`,
metadata: { purpose: 'context' },
});
});

it('should use a custom preface', async () => {
const messages: MessageData[] = [
{ role: 'user', content: [{ text: 'first part' }] },
Expand Down

0 comments on commit fd9873f

Please sign in to comment.