Skip to content

Commit e9712f9

Browse files
committed
Use a ChatModel for completion
1 parent 44b28f5 commit e9712f9

File tree

1 file changed

+37
-22
lines changed

1 file changed

+37
-22
lines changed

src/llm-models/openai-completer.ts

+37-22
Original file line numberDiff line numberDiff line change
@@ -2,51 +2,66 @@ import {
22
CompletionHandler,
33
IInlineCompletionContext
44
} from '@jupyterlab/completer';
5-
import { BaseLLM } from '@langchain/core/language_models/llms';
6-
import { OpenAI } from '@langchain/openai';
5+
import { BaseChatModel } from '@langchain/core/language_models/chat_models';
6+
import { AIMessage, SystemMessage } from '@langchain/core/messages';
7+
import { ChatOpenAI } from '@langchain/openai';
78

89
import { BaseCompleter, IBaseCompleter } from './base-completer';
10+
import { COMPLETION_SYSTEM_PROMPT } from '../provider';
911

1012
export class OpenAICompleter implements IBaseCompleter {
1113
constructor(options: BaseCompleter.IOptions) {
12-
this._gptProvider = new OpenAI({ ...options.settings });
14+
this._gptProvider = new ChatOpenAI({ ...options.settings });
1315
}
1416

15-
get provider(): BaseLLM {
17+
get provider(): BaseChatModel {
1618
return this._gptProvider;
1719
}
1820

21+
/**
22+
* Getter and setter for the initial prompt.
23+
*/
24+
get prompt(): string {
25+
return this._prompt;
26+
}
27+
set prompt(value: string) {
28+
this._prompt = value;
29+
}
30+
1931
async fetch(
2032
request: CompletionHandler.IRequest,
2133
context: IInlineCompletionContext
2234
) {
2335
const { text, offset: cursorOffset } = request;
2436
const prompt = text.slice(0, cursorOffset);
25-
const suffix = text.slice(cursorOffset);
26-
27-
const data = {
28-
prompt,
29-
suffix,
30-
model: this._gptProvider.model,
31-
// temperature: 0,
32-
// top_p: 1,
33-
// max_tokens: 1024,
34-
// min_tokens: 0,
35-
// random_seed: 1337,
36-
stop: []
37-
};
37+
38+
const messages = [new SystemMessage(this._prompt), new AIMessage(prompt)];
3839

3940
try {
40-
const response = await this._gptProvider.completionWithRetry(data, {});
41-
const items = response.choices.map((choice: any) => {
42-
return { insertText: choice.message.content as string };
43-
});
41+
const response = await this._gptProvider.invoke(messages);
42+
const items = [];
43+
if (typeof response.content === 'string') {
44+
items.push({
45+
insertText: response.content
46+
});
47+
} else {
48+
response.content.forEach(content => {
49+
if (content.type !== 'text') {
50+
return;
51+
}
52+
items.push({
53+
insertText: content.text,
54+
filterText: prompt.substring(prompt.length)
55+
});
56+
});
57+
}
4458
return items;
4559
} catch (error) {
4660
console.error('Error fetching completions', error);
4761
return { items: [] };
4862
}
4963
}
5064

51-
private _gptProvider: OpenAI;
65+
private _gptProvider: ChatOpenAI;
66+
private _prompt: string = COMPLETION_SYSTEM_PROMPT;
5267
}

0 commit comments

Comments
 (0)