Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(prompt): rework input completion prompt to v1.2 — predict intent, incl. long-range (#15961)

Arvin Xu3d0ee23c2dfd
diff --git a/packages/eval-rubric/src/matchers/__tests__/llmRubric.test.ts b/packages/eval-rubric/src/matchers/__tests__/llmRubric.test.ts
index e3c228d1b0b..4e17f827528 100644
--- a/packages/eval-rubric/src/matchers/__tests__/llmRubric.test.ts
+++ b/packages/eval-rubric/src/matchers/__tests__/llmRubric.test.ts
@@ -32,12 +32,12 @@ describe('matchLLMRubric', () => {
it('should pass when LLM returns high score', async () => {
mockGenerateObject.mockResolvedValue({ reason: 'Output is correct', score: 0.9 });
- const result = await matchLLMRubric(
- 'Paris',
- 'Paris',
- rubric({ criteria: 'Is the answer correct?' }),
+ const result = await matchLLMRubric({
+ actual: 'Paris',
context,
- );
+ expected: 'Paris',
+ rubric: rubric({ criteria: 'Is the answer correct?' }),
+ });
expect(result.passed).toBe(true);
expect(result.score).toBe(0.9);
@@ -47,12 +47,12 @@ describe('matchLLMRubric', () => {
it('should fail when LLM returns low score', async () => {
mockGenerateObject.mockResolvedValue({ reason: 'Output is wrong', score: 0.2 });
- const result = await matchLLMRubric(
- 'London',
- 'Paris',
- rubric({ criteria: 'Is the answer correct?' }),
+ const result = await matchLLMRubric({
+ actual: 'London',
context,
- );
+ expected: 'Paris',
+ rubric: rubric({ criteria: 'Is the answer correct?' }),
+ });
expect(result.passed).toBe(false);
expect(result.score).toBe(0.2);
@@ -62,12 +62,11 @@ describe('matchLLMRubric', () => {
it('should respect custom threshold from rubric', async () => {
mockGenerateObject.mockResolvedValue({ reason: 'Partially correct', score: 0.5 });
- const result = await matchLLMRubric(
- 'answer',
- undefined,
- rubric({ criteria: 'Check correctness' }, { threshold: 0.4 }),
+ const result = await matchLLMRubric({
+ actual: 'answer',
context,
- );
+ rubric: rubric({ criteria: 'Check correctness' }, { threshold: 0.4 }),
+ });
expect(result.passed).toBe(true);
expect(result.score).toBe(0.5);
@@ -76,13 +75,17 @@ describe('matchLLMRubric', () => {
it('should clamp score to [0, 1]', async () => {
mockGenerateObject.mockResolvedValue({ reason: 'overflow', score: 1.5 });
- const result = await matchLLMRubric('x', undefined, rubric({ criteria: 'test' }), context);
+ const result = await matchLLMRubric({
+ actual: 'x',
+ context,
+ rubric: rubric({ criteria: 'test' }),
+ });
expect(result.score).toBe(1);
});
it('should return score 0 when generateObject is not available', async () => {
- const result = await matchLLMRubric('x', undefined, rubric({ criteria: 'test' }));
+ const result = await matchLLMRubric({ actual: 'x', rubric: rubric({ criteria: 'test' }) });
expect(result.passed).toBe(false);
expect(result.score).toBe(0);
@@ -92,26 +95,92 @@ describe('matchLLMRubric', () => {
it('should handle LLM call failure gracefully', async () => {
mockGenerateObject.mockRejectedValue(new Error('API timeout'));
- const result = await matchLLMRubric('x', undefined, rubric({ criteria: 'test' }), context);
+ const result = await matchLLMRubric({
+ actual: 'x',
+ context,
+ rubric: rubric({ criteria: 'test' }),
+ });
expect(result.passed).toBe(false);
expect(result.score).toBe(0);
expect(result.reason).toBe('LLM judge failed: API timeout');
});
+ it('should treat a valid score of 0 as a real score (not "no score")', async () => {
+ mockGenerateObject.mockResolvedValue({ reason: 'Completely fails', score: 0 });
+
+ const result = await matchLLMRubric({
+ actual: 'garbage',
+ context,
+ rubric: rubric({ criteria: 'test' }),
+ });
+
+ expect(result.score).toBe(0);
+ expect(result.passed).toBe(false);
+ expect(result.reason).toBe('Completely fails');
+ expect(mockGenerateObject).toHaveBeenCalledTimes(1);
+ });
+
+ it('should retry when the judge returns no score, then succeed', async () => {
+ mockGenerateObject
+ .mockResolvedValueOnce({ reason: 'malformed' } as any)
+ .mockResolvedValueOnce({ reason: 'recovered', score: 0.8 });
+
+ const result = await matchLLMRubric({
+ actual: 'x',
+ context,
+ rubric: rubric({ criteria: 'test' }),
+ });
+
+ expect(result.passed).toBe(true);
+ expect(result.score).toBe(0.8);
+ expect(result.reason).toBe('recovered');
+ expect(mockGenerateObject).toHaveBeenCalledTimes(2);
+ });
+
+ it('should retry on a thrown error, then succeed', async () => {
+ mockGenerateObject
+ .mockRejectedValueOnce(new Error('rate limited'))
+ .mockResolvedValueOnce({ reason: 'ok', score: 1 });
+
+ const result = await matchLLMRubric({
+ actual: 'x',
+ context,
+ rubric: rubric({ criteria: 'test' }),
+ });
+
+ expect(result.passed).toBe(true);
+ expect(result.score).toBe(1);
+ expect(mockGenerateObject).toHaveBeenCalledTimes(2);
+ });
+
+ it('should give up after judgeMaxAttempts and report the last failure', async () => {
+ mockGenerateObject.mockResolvedValue({ reason: 'still malformed' } as any);
+
+ const result = await matchLLMRubric({
+ actual: 'x',
+ context: { ...context, judgeMaxAttempts: 2 },
+ rubric: rubric({ criteria: 'test' }),
+ });
+
+ expect(result.passed).toBe(false);
+ expect(result.score).toBe(0);
+ expect(result.reason).toBe('LLM judge did not return a score');
+ expect(mockGenerateObject).toHaveBeenCalledTimes(2);
+ });
+
it('should use rubric config model/provider over context judgeModel', async () => {
mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
- await matchLLMRubric(
- 'x',
- undefined,
- rubric({
+ await matchLLMRubric({
+ actual: 'x',
+ context,
+ rubric: rubric({
criteria: 'test',
model: 'claude-sonnet-4-20250514',
provider: 'anthropic',
}),
- context,
- );
+ });
expect(mockGenerateObject).toHaveBeenCalledWith(
expect.objectContaining({
@@ -124,14 +193,16 @@ describe('matchLLMRubric', () => {
it('should fallback to context.judgeModel when rubric config has no model', async () => {
mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
- await matchLLMRubric('x', undefined, rubric({ criteria: 'test' }), context);
+ await matchLLMRubric({ actual: 'x', context, rubric: rubric({ criteria: 'test' }) });
expect(mockGenerateObject).toHaveBeenCalledWith(expect.objectContaining({ model: 'gpt-4o' }));
});
it('should return score 0 when no judge model configured', async () => {
- const result = await matchLLMRubric('x', undefined, rubric({ criteria: 'test' }), {
- generateObject: mockGenerateObject,
+ const result = await matchLLMRubric({
+ actual: 'x',
+ context: { generateObject: mockGenerateObject },
+ rubric: rubric({ criteria: 'test' }),
});
expect(result.passed).toBe(false);
@@ -140,10 +211,41 @@ describe('matchLLMRubric', () => {
expect(mockGenerateObject).not.toHaveBeenCalled();
});
+ it('should include input in user prompt when provided', async () => {
+ mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
+
+ await matchLLMRubric({
+ actual: 'to Vercel',
+ context,
+ input: 'How do I deploy?',
+ rubric: rubric({ criteria: 'Is this a good continuation?' }),
+ });
+
+ const payload = mockGenerateObject.mock.calls[0][0];
+ const userMsg = payload.messages.find((m) => m.role === 'user')!;
+ expect(userMsg.content).toContain('[Input]');
+ expect(userMsg.content).toContain('How do I deploy?');
+ });
+
+ it('should omit input section when not provided', async () => {
+ mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
+
+ await matchLLMRubric({ actual: 'x', context, rubric: rubric({ criteria: 'test' }) });
+
+ const payload = mockGenerateObject.mock.calls[0][0];
+ const userMsg = payload.messages.find((m) => m.role === 'user')!;
+ expect(userMsg.content).not.toContain('[Input]');
+ });
+
it('should include expected in user prompt when provided', async () => {
mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
- await matchLLMRubric('Paris', 'Paris', rubric({ criteria: 'Check answer' }), context);
+ await matchLLMRubric({
+ actual: 'Paris',
+ context,
+ expected: 'Paris',
+ rubric: rubric({ criteria: 'Check answer' }),
+ });
const payload = mockGenerateObject.mock.calls[0][0];
const userMsg = payload.messages.find((m) => m.role === 'user')!;
@@ -154,12 +256,11 @@ describe('matchLLMRubric', () => {
it('should omit expected section when not provided', async () => {
mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
- await matchLLMRubric(
- 'some output',
- undefined,
- rubric({ criteria: 'Is this helpful?' }),
+ await matchLLMRubric({
+ actual: 'some output',
context,
- );
+ rubric: rubric({ criteria: 'Is this helpful?' }),
+ });
const payload = mockGenerateObject.mock.calls[0][0];
const userMsg = payload.messages.find((m) => m.role === 'user')!;
@@ -172,12 +273,11 @@ describe('matchLLMRubric', () => {
mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
const customSystemRole = 'You are a code review expert. Score code quality from 0 to 1.';
- await matchLLMRubric(
- 'function add(a, b) { return a + b; }',
- undefined,
- rubric({ criteria: 'Is the code clean?', systemRole: customSystemRole }),
+ await matchLLMRubric({
+ actual: 'function add(a, b) { return a + b; }',
context,
- );
+ rubric: rubric({ criteria: 'Is the code clean?', systemRole: customSystemRole }),
+ });
const payload = mockGenerateObject.mock.calls[0][0];
const systemMsg = payload.messages.find((m) => m.role === 'system')!;
@@ -187,7 +287,7 @@ describe('matchLLMRubric', () => {
it('should use default systemRole when not configured', async () => {
mockGenerateObject.mockResolvedValue({ reason: 'ok', score: 1 });
- await matchLLMRubric('x', undefined, rubric({ criteria: 'test' }), context);
+ await matchLLMRubric({ actual: 'x', context, rubric: rubric({ criteria: 'test' }) });
const payload = mockGenerateObject.mock.calls[0][0];
const systemMsg = payload.messages.find((m) => m.role === 'system')!;
diff --git a/packages/eval-rubric/src/matchers/index.ts b/packages/eval-rubric/src/matchers/index.ts
index aa17a339c9f..96a9688beaa 100644
--- a/packages/eval-rubric/src/matchers/index.ts
+++ b/packages/eval-rubric/src/matchers/index.ts
@@ -69,7 +69,7 @@ export const match = async (
}
case 'llm-rubric': {
- return matchLLMRubric(actual, expected, rubric, context);
+ return matchLLMRubric({ actual, context, expected, input, rubric });
}
case 'json-schema': {
diff --git a/packages/eval-rubric/src/matchers/llmRubric.ts b/packages/eval-rubric/src/matchers/llmRubric.ts
index 48758ed4e77..498d461de5d 100644
--- a/packages/eval-rubric/src/matchers/llmRubric.ts
+++ b/packages/eval-rubric/src/matchers/llmRubric.ts
@@ -27,20 +27,37 @@ function buildJudgeUserPrompt(
criteria: string,
actual: string,
expected: string | undefined,
+ input: string | undefined,
): string {
- const parts = [`[Criteria]\n${criteria}`, `[Output]\n${actual}`];
+ const parts = [`[Criteria]\n${criteria}`];
+ // Surface the task input (e.g. the prompt/draft/context the output responds
+ // to) so the judge can score the output against what it was supposed to do,
+ // not just against the criteria text in isolation.
+ if (input) {
+ parts.push(`[Input]\n${input}`);
+ }
+ parts.push(`[Output]\n${actual}`);
if (expected) {
parts.push(`[Expected]\n${expected}`);
}
return parts.join('\n\n');
}
-export const matchLLMRubric = async (
- actual: string,
- expected: string | undefined,
- rubric: EvalBenchmarkRubric,
- context?: MatchContext,
-): Promise<MatchResult> => {
+export interface MatchLLMRubricParams {
+ actual: string;
+ context?: MatchContext;
+ expected?: string;
+ input?: string;
+ rubric: EvalBenchmarkRubric;
+}
+
+export const matchLLMRubric = async ({
+ actual,
+ context,
+ expected,
+ input,
+ rubric,
+}: MatchLLMRubricParams): Promise<MatchResult> => {
if (!context?.generateObject) {
return { passed: false, reason: 'LLM judge not available', score: 0 };
}
@@ -53,34 +70,46 @@ export const matchLLMRubric = async (
return { passed: false, reason: 'No judge model configured', score: 0 };
}
- try {
- const result = await context.generateObject({
- messages: [
- { content: cfg.systemRole || DEFAULT_SYSTEM_ROLE, role: 'system' },
- { content: buildJudgeUserPrompt(criteria, actual, expected), role: 'user' },
- ],
- model,
- provider: cfg.provider,
- schema: JUDGE_SCORE_SCHEMA,
- });
+ const messages = [
+ { content: cfg.systemRole || DEFAULT_SYSTEM_ROLE, role: 'system' as const },
+ { content: buildJudgeUserPrompt(criteria, actual, expected, input), role: 'user' as const },
+ ];
+ const threshold = rubric.threshold ?? 0.6;
+ const maxAttempts = Math.max(1, context.judgeMaxAttempts ?? 3);
- if (!result?.score) {
- return { passed: false, reason: 'LLM judge did not return a score', score: 0 };
- }
+ // Retry transient judge flakes — a thrown error or a malformed response with no
+ // usable score. The judge occasionally returns no parseable score under load;
+ // a single bad sample shouldn't auto-fail an otherwise-good output.
+ let lastResult: MatchResult = {
+ passed: false,
+ reason: 'LLM judge did not return a score',
+ score: 0,
+ };
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ try {
+ const result = await context.generateObject({
+ messages,
+ model,
+ provider: cfg.provider,
+ schema: JUDGE_SCORE_SCHEMA,
+ });
- const score = Math.max(0, Math.min(1, result.score));
- const threshold = rubric.threshold ?? 0.6;
+ // Note: a valid score can be 0 (output fully fails the criteria), so check
+ // the type rather than truthiness — `!result.score` would drop real zeros.
+ if (typeof result?.score === 'number' && Number.isFinite(result.score)) {
+ const score = Math.max(0, Math.min(1, result.score));
+ return { passed: score >= threshold, reason: result.reason, score };
+ }
- return {
- passed: score >= threshold,
- reason: result.reason,
- score,
- };
- } catch (error) {
- return {
- passed: false,
- reason: `LLM judge failed: ${error instanceof Error ? error.message : String(error)}`,
- score: 0,
- };
+ lastResult = { passed: false, reason: 'LLM judge did not return a score', score: 0 };
+ } catch (error) {
+ lastResult = {
+ passed: false,
+ reason: `LLM judge failed: ${error instanceof Error ? error.message : String(error)}`,
+ score: 0,
+ };
+ }
}
+
+ return lastResult;
};
diff --git a/packages/eval-rubric/src/matchers/types.ts b/packages/eval-rubric/src/matchers/types.ts
index 37926fc7575..9567087ea7d 100644
--- a/packages/eval-rubric/src/matchers/types.ts
+++ b/packages/eval-rubric/src/matchers/types.ts
@@ -7,6 +7,8 @@ export interface GenerateObjectPayload {
export interface MatchContext {
generateObject?: (payload: GenerateObjectPayload) => Promise<{ reason: string; score: number }>;
+ /** Max attempts for the LLM judge before giving up (transient flakes / missing score). Default 3. */
+ judgeMaxAttempts?: number;
judgeModel?: string;
}
diff --git a/packages/prompts/src/chains/inputCompletion.test.ts b/packages/prompts/src/chains/inputCompletion.test.ts
index 882c311a824..ad676b831af 100644
--- a/packages/prompts/src/chains/inputCompletion.test.ts
+++ b/packages/prompts/src/chains/inputCompletion.test.ts
@@ -7,13 +7,22 @@ import {
} from './inputCompletion';
describe('chainInputCompletion', () => {
- it('returns a system + user message pair', () => {
+ it('returns a system + user message pair with the draft and cursor marker', () => {
const { messages } = chainInputCompletion('How can I ', '');
expect(messages).toHaveLength(2);
expect(messages[0].role).toBe('system');
expect(messages[1].role).toBe('user');
- expect(messages[1].content).toContain('Before cursor: "How can I "');
- expect(messages[1].content).toContain('After cursor: ""');
+
+ const draft = messages[1].content as string;
+ expect(draft).toContain('<draft>');
+ expect(draft).toContain('How can I ');
+ // beforeCursor is immediately followed by the cursor marker
+ expect(draft).toContain('How can I <|cursor|>');
+ });
+
+ it('places afterCursor text on the far side of the cursor marker', () => {
+ const { messages } = chainInputCompletion('fix the ', ' bug');
+ expect(messages[1].content as string).toContain('fix the <|cursor|> bug');
});
it('attaches a minimal `{ completion: string }` schema for generateObject', () => {
@@ -25,24 +34,54 @@ describe('chainInputCompletion', () => {
expect(schema.schema.properties.completion.type).toBe('string');
});
- it('adds a separate user message for conversation context when provided', () => {
+ it('folds conversation context into the single user message as a labelled block', () => {
const { messages } = chainInputCompletion('write ', '', [
{ content: 'previous response', role: 'assistant' },
{ content: 'previous question', role: 'user' },
]);
- expect(messages).toHaveLength(3);
+ // Context is NOT replayed as real role turns — still just system + user.
+ expect(messages).toHaveLength(2);
expect(messages[0].role).toBe('system');
expect(messages[1].role).toBe('user');
- expect(messages[2].role).toBe('user');
- const contextMsg = messages[1].content as string;
- expect(contextMsg).toContain('Current conversation context');
- expect(contextMsg).toContain('assistant: previous response');
- expect(contextMsg).toContain('user: previous question');
- expect(contextMsg).not.toContain('Before cursor');
+ const content = messages[1].content as string;
+ expect(content).toContain('<conversation>');
+ expect(content).toContain('Assistant: previous response');
+ expect(content).toContain('User: previous question');
+ // The draft still appears, after the context block.
+ expect(content.indexOf('<conversation>')).toBeLessThan(content.indexOf('<draft>'));
+ expect(content).toContain('write <|cursor|>');
+ });
+
+ it('omits the conversation block when there is no context', () => {
+ const { messages } = chainInputCompletion('hi', '');
+ expect(messages[1].content as string).not.toContain('<conversation>');
+ });
+
+ it('keeps only the most recent turns and drops non user/assistant + empty messages', () => {
+ const many = Array.from({ length: 12 }, (_, i) => ({
+ content: `msg ${i}`,
+ role: (i % 2 === 0 ? 'user' : 'assistant') as 'assistant' | 'user',
+ }));
+ const { messages } = chainInputCompletion('next ', '', [
+ { content: 'system noise', role: 'system' },
+ { content: ' ', role: 'user' },
+ ...many,
+ ]);
+ const content = messages[1].content as string;
+ // Last 8 of the 12 valid turns survive; the earliest do not.
+ expect(content).toContain('msg 11');
+ expect(content).toContain('msg 4');
+ expect(content).not.toContain('msg 3');
+ expect(content).not.toContain('system noise');
+ });
- const cursorMsg = messages[2].content as string;
- expect(cursorMsg).toContain('Before cursor: "write "');
+ it('clips an over-long message so it cannot crowd out the draft', () => {
+ const huge = 'x'.repeat(5000);
+ const { messages } = chainInputCompletion('go ', '', [{ content: huge, role: 'user' }]);
+ const content = messages[1].content as string;
+ expect(content).toContain('…');
+ expect(content).not.toContain('x'.repeat(1100));
});
it('keeps the system prompt stable regardless of conversation context', () => {
diff --git a/packages/prompts/src/chains/inputCompletion.ts b/packages/prompts/src/chains/inputCompletion.ts
index a809c3d81f3..b92909deb4d 100644
--- a/packages/prompts/src/chains/inputCompletion.ts
+++ b/packages/prompts/src/chains/inputCompletion.ts
@@ -6,7 +6,7 @@ import type { OpenAIChatMessage } from '@lobechat/types';
* groups runs by prompt iteration. The 6-char prompt hash on the row catches
* forgotten bumps.
*/
-export const INPUT_COMPLETION_PROMPT_VERSION = 'v1.1';
+export const INPUT_COMPLETION_PROMPT_VERSION = 'v1.2';
/**
* Symbolic schema name — also recorded on the tracing row's `schemaName`
@@ -40,7 +40,8 @@ const INPUT_COMPLETION_SCHEMA: InputCompletionSchema = {
additionalProperties: false,
properties: {
completion: {
- description: 'The missing text to insert at the cursor. Empty string for no suggestion.',
+ description:
+ "The continuation of the user's draft, inserted verbatim at the cursor and written in the user's own voice. Keep it short — usually just finish the current word, phrase, or sentence; only extend to the next sentence when the conversation makes it unmistakable. NEVER role-flip: when the draft tells or asks the assistant to do something, do not continue as the assistant accepting the task — no \"I'll…\", \"let me…\", or any first-person narration of carrying out the request (in whatever language the user is writing). Return an empty string when the only natural continuation would be the assistant's voice or would require fabricating specifics the user hasn't signalled.",
type: 'string',
},
},
@@ -50,58 +51,93 @@ const INPUT_COMPLETION_SCHEMA: InputCompletionSchema = {
strict: true,
};
-const SYSTEM_PROMPT = `You are an autocomplete engine for a chat input box. The user is composing a message to send to an AI assistant. Predict and complete what the USER is typing. Return only the missing text to insert at the cursor in the JSON object's \`completion\` field.
-
-CRITICAL RULES:
-- You are completing the USER's message, NOT the AI assistant's response
-- The completed text should read as something a human would type to ask, request, or tell an AI
-- NEVER generate text that sounds like an AI assistant responding (e.g., "help you", "assist you", "I can help")
-- Keep it short and natural, under 15 words
-- Match the user's language
-- If no completion would be useful, return an empty string
-
-GOOD examples (user perspective):
-"How can I " → "optimize my React component's performance?"
-"Hi" → ", I need help with a TypeScript issue"
-"Can you " → "explain how useEffect cleanup works?"
-"帮我" → "写一个数据库查询的优化方案"
-"Let me " → "describe the bug I'm seeing"
-"我想" → "了解一下如何部署到 Kubernetes"
-
-BAD examples (assistant perspective — NEVER do this):
-"How can I " → "help you today?" ← WRONG: this is what an AI assistant says
-"Hi" → ", how can I help you?" ← WRONG: assistant greeting
-"Let me " → "explain that for you" ← WRONG: assistant offering to explain`;
+const SYSTEM_PROMPT = `You are an inline autocomplete engine for a chat input box. The user is drafting a message to an AI assistant, and you continue that draft from the cursor. Predict what THIS user is about to type next and return it in the JSON object's \`completion\` field; the text is inserted verbatim at the cursor.
+
+Your job is to save the user keystrokes by predicting their intent — the way inline code completion finishes a line you were already writing. Read the conversation so far, infer where the user is heading, and continue their draft naturally.
+
+HOW MUCH TO WRITE
+- Keep it SHORT — this is the default. Finish the current word, phrase, or sentence the user is already writing, then stop. Aim for the length the user would actually have typed: a tight completion they accept in one keystroke, not a thorough one. Most completions are a few words to one clause.
+- Only continue past the current sentence when the conversation makes the very next sentence unmistakable AND stopping would leave the thought visibly unfinished. Extending is the exception, not the default.
+- Never write more than the user would plausibly type next: no second clause, no added qualifier, no extra example, no spelled-out reasoning, no paragraph. Stop as soon as you would be guessing at specifics you don't know, and never author the user's whole message from a blank start. When unsure how far to go, stop earlier — a short useful completion beats a long speculative one.
+
+STAY IN THE USER'S VOICE (the one hard rule)
+- You are always FINISHING the user's message, in the user's own voice and language. You are never the assistant; you never answer, agree with, or acknowledge the user.
+- It is always the USER speaking. Even when the conversation gives you enough to answer or to decide, do NOT — drawing the conclusion, resolving the question, or telling the assistant what to do is the assistant's job, not the user's. You only continue what the user is themselves asking, requesting, or stating. This matters most under heavy context, where it is tempting to write the answer instead of the user's next words.
+- Asking the assistant a question or making a request IS the user's voice — continue it (e.g. a draft that presents something usually continues into "…can you review this…" / "…help me check…"). Do not mistake the user turning to ask for help as the assistant's turn.
+- WATCH THE FIRST PERSON. Both the user and the assistant say "I", so the word alone won't tell you who is talking — the ROLE does. The user's "I" states what the user wants, thinks, or is asking for; the assistant's "I" narrates carrying out the user's request. When the draft tells or asks the assistant to act ("then change it?", "can you verify with the cli first?", "add X for me"), a continuation like "I'll fix it / let me confirm / I can run that" is the ASSISTANT accepting the task — that is the role-flip, not the user. Do NOT write it. Return an empty string, or continue only with MORE of the user's own instruction or question ("…and send me the logs", "…then run the tests").
+- A draft that is already a complete directive or question to the assistant ("then change it?", "continue?", "are you done yet?") usually has nothing left for the user to add — prefer an empty string over inventing the assistant's reply.
+- If the most natural continuation would be the assistant speaking (answering the question, offering help, issuing the decision, or narrating "I'll do…"), then there is nothing left for the user to type — return an empty string.
+
+RETURN AN EMPTY STRING WHEN
+- The only natural continuation is the assistant's voice (see above).
+- Continuing would require inventing a specific value the user hasn't signalled — a particular file path, name, number, or decision. Stop before the unknown specifics rather than fabricating them.
+- The conversation gives no real signal and you would only be padding with filler.
+
+Match the user's language, tone, and register. Output only the text to insert — no quotes, labels, or the cursor marker.
+
+EXAMPLES (→ is the completion; it picks up exactly at the cursor. Shown in English, but always match the user's language.)
+- Finish the sentence — draft "How do I cut the cold-start time" → " of my serverless function?"
+- Continue the user's stated plan — draft "Let's go with option 2, and " → "add a migration that backfills the new column for existing rows"
+- Long-range, conversation supports it — after the assistant proposed a fix, draft "Looks good. " → "Apply it, then run the test suite and show me what still fails."
+- Don't fabricate unknown specifics — draft "Deploy it to " → "" (the target environment is a value only the user knows)
+- Don't slip into the assistant's voice — draft "Sure, I can " → "" (this reads as the assistant talking, not the user)
+- Directive to the assistant, already complete — draft "Then just change it?" → "" ("I'll fix it" would be the assistant accepting the task, not the user)
+- Request to the assistant — draft "Can you verify it with the cli first" → " and send me the result" (more of the user's instruction), NOT "I can run that" (that role-flips into the assistant)
+- Don't answer your own question — draft "Are you done? why haven't the tests started?" → "" ("I'll check the env first" would be the assistant explaining itself, not the user)`;
export interface InputCompletionChainResult {
messages: OpenAIChatMessage[];
schema: InputCompletionSchema;
}
+/** Marks the caret position inside the <draft> block. Distinctive enough that it
+ * won't collide with anything a user types; the prompt tells the model to drop it. */
+const CURSOR_MARKER = '<|cursor|>';
+
+/** Keep only the most recent turns — the tail is what the user is actually
+ * replying to, and a long history both inflates latency/cost and drowns the draft. */
+const MAX_CONTEXT_MESSAGES = 8;
+/** Cap each turn so one long message can't crowd out the rest (and the draft). */
+const MAX_MESSAGE_CHARS = 1000;
+
+const clip = (text: string): string =>
+ text.length > MAX_MESSAGE_CHARS ? text.slice(0, MAX_MESSAGE_CHARS) + '…' : text;
+
+/**
+ * Render conversation history as a flat, speaker-labelled reference block — NOT
+ * as real `assistant`/`user` role turns. Replaying prior turns in their native
+ * roles invites the model to "continue the conversation" as the assistant, which
+ * is exactly the role-flip failure we're guarding against. A labelled block keeps
+ * the model's only generation target the draft at the end.
+ */
+const renderContext = (context: OpenAIChatMessage[]): string => {
+ const lines = context
+ .filter((m) => m.role === 'user' || m.role === 'assistant')
+ .filter((m) => typeof m.content === 'string' && m.content.trim())
+ .slice(-MAX_CONTEXT_MESSAGES)
+ .map((m) => `${m.role === 'assistant' ? 'Assistant' : 'User'}: ${clip(m.content as string)}`);
+ return lines.join('\n');
+};
+
export const chainInputCompletion = (
beforeCursor: string,
afterCursor: string,
context?: OpenAIChatMessage[],
): InputCompletionChainResult => {
- // Context is dynamic per conversation — keep it OUT of the system message so
- // the system prompt (and thus the tracing `promptHash`) stays stable across
- // invocations. Otherwise every keystroke in a longer conversation produces a
- // distinct hash, defeating the per-prompt grouping.
- const contextMessage: OpenAIChatMessage | null = context?.length
- ? {
- content: `Current conversation context:\n${context.map((m) => `${m.role}: ${m.content}`).join('\n')}`,
- role: 'user',
- }
- : null;
+ // Everything dynamic lives in the user message; the system prompt stays
+ // constant so the tracing `promptHash` keeps grouping runs by prompt version
+ // instead of fragmenting per keystroke.
+ const draftBlock = `The user is typing a new message to the assistant. Continue their draft from the ${CURSOR_MARKER} marker, in the user's own voice:\n<draft>\n${beforeCursor}${CURSOR_MARKER}${afterCursor}\n</draft>`;
+
+ const rendered = context?.length ? renderContext(context) : '';
+ const userContent = rendered
+ ? `<conversation>\n${rendered}\n</conversation>\n\n${draftBlock}`
+ : draftBlock;
return {
messages: [
{ content: SYSTEM_PROMPT, role: 'system' },
- ...(contextMessage ? [contextMessage] : []),
- {
- content: `Before cursor: "${beforeCursor}"\nAfter cursor: "${afterCursor}"`,
- role: 'user',
- },
+ { content: userContent, role: 'user' },
],
schema: INPUT_COMPLETION_SCHEMA,
};