Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/test/simulation/fixtures/multiFileEdit/issue-8131/extension.ts
13405 views
1
import * as vscode from 'vscode';
2
import OpenAI from 'openai';
3
import * as dotenv from 'dotenv';
4
import * as path from 'path';
5
6
const O1_PARTICIPANT_ID = 'vscode-samples.o1';
7
8
interface ICatChatResult extends vscode.ChatResult {
9
metadata: {
10
command: string;
11
}
12
}
13
14
const logger = vscode.env.createTelemetryLogger({
15
sendEventData(eventName, data) {
16
// Capture event telemetry
17
console.log(`Event: ${eventName}`);
18
console.log(`Data: ${JSON.stringify(data)}`);
19
},
20
sendErrorData(error, data) {
21
// Capture error telemetry
22
console.error(`Error: ${error}`);
23
console.error(`Data: ${JSON.stringify(data)}`);
24
}
25
});
26
27
// Initialize OpenAI client
28
29
30
export function activate(context: vscode.ExtensionContext) {
31
// Load .env file from the extension's root directory
32
dotenv.config();
33
34
let openai: OpenAI | undefined;
35
const handler: vscode.ChatRequestHandler = async (request: vscode.ChatRequest, context: vscode.ChatContext, stream: vscode.ChatResponseStream, token: vscode.CancellationToken): Promise<ICatChatResult> => {
36
if (!openai) {
37
let apiKey = process.env.OPENAI_API_KEY;
38
if (!apiKey) {
39
apiKey = await vscode.window.showInputBox({
40
prompt: 'Enter your OpenAI API Key',
41
ignoreFocusOut: true,
42
password: true
43
});
44
45
if (!apiKey) {
46
stream.markdown('API Key is required to proceed.');
47
throw new Error('API Key is required');
48
}
49
}
50
openai = new OpenAI({
51
apiKey
52
});
53
}
54
55
try {
56
const chatCompletion = await openai.chat.completions.create({
57
model: "o1-preview", // You can change this to the appropriate model
58
messages: [{ role: "user", content: request.prompt }],
59
stream: true,
60
});
61
62
for await (const chunk of chatCompletion) {
63
if (chunk.choices[0]?.delta?.content) {
64
stream.markdown(chunk.choices[0].delta.content);
65
}
66
}
67
} catch(err) {
68
handleError(logger, err, stream);
69
}
70
71
logger.logUsage('request', { kind: 'o1' });
72
return { metadata: { command: 'o1_chat' } };
73
};
74
75
const o1 = vscode.chat.createChatParticipant(O1_PARTICIPANT_ID, handler);
76
o1.iconPath = vscode.Uri.joinPath(context.extensionUri, 'openai-icon.png');
77
78
context.subscriptions.push(o1);
79
}
80
81
function handleError(logger: vscode.TelemetryLogger, err: any, stream: vscode.ChatResponseStream): void {
82
logger.logError(err);
83
84
if (err instanceof Error) {
85
console.error(err.message);
86
stream.markdown(`An error occurred: ${err.message}`);
87
} else {
88
console.error('An unknown error occurred');
89
stream.markdown('An unknown error occurred');
90
}
91
}
92
93
export function deactivate() { }
94
95