-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathopenai-service.ts
More file actions
93 lines (87 loc) · 3.31 KB
/
openai-service.ts
File metadata and controls
93 lines (87 loc) · 3.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { Notice } from "obsidian";
import OpenAI from "openai";
import { AtomizerSettings } from "./settings";
import { getFormattedDateTime } from "./utils";
/**
* Service for interacting with the OpenAI API
*/
export class OpenAIService {
constructor(
private apiKey: string,
private model: string,
private settings: AtomizerSettings,
) {}
/**
* Generate atomic notes from content using OpenAI
* @param content The content to process
* @param timestamp ISO timestamp
* @param sourceFilePath Path to the source file
*/
async generateAtomicNotes(
content: string,
timestamp: string,
sourceFilePath: string,
): Promise<string> {
// Inform user about network request
new Notice("Sending request to OpenAI...", 3000);
const openai = new OpenAI({
apiKey: this.apiKey,
dangerouslyAllowBrowser: true,
});
try {
const completion = await openai.chat.completions.create({
model: this.model,
messages: [
{
role: "system",
content: this.getSystemPrompt(sourceFilePath),
},
{
role: "user",
content: content,
},
],
temperature: 0.7,
max_tokens: 4000,
});
return completion.choices[0]?.message?.content ?? "";
} catch (error: any) {
// Handle specific OpenAI API errors
if (error?.status === 401) {
throw new Error("Invalid OpenAI API key. Please check your settings.");
} else if (error?.status === 429) {
throw new Error("OpenAI API rate limit exceeded. Please try again later.");
} else if (error?.status === 404) {
throw new Error(`Model '${this.model}' not found. Please check your model selection.`);
} else if (error?.status === 400) {
throw new Error("Invalid request to OpenAI. The content may be too long or contain invalid characters.");
} else if (error?.code === "ENOTFOUND" || error?.code === "ECONNREFUSED") {
throw new Error("Network error. Please check your internet connection.");
} else if (error?.message) {
throw new Error(`OpenAI API error: ${error.message}`);
} else {
throw new Error("Failed to generate atomic notes. Please try again.");
}
}
}
/**
* Generate the system prompt for OpenAI
* @param sourceFilePath Path to the source file for back-linking
*/
private getSystemPrompt(sourceFilePath: string): string {
return `You are an expert at creating atomic notes from a single, larger note.
Take the content from a larger note and break it down into separate compact yet detailed atomic notes. Each note MUST be separated by placing '<<<>>>' on its own line between notes. Do not include an index or main note. Follow these rules:
1. Each note should contain exactly one clear idea. This can contain multiple lines.
2. Each note must have a YAML frontmatter section at the top with:
---
date: "${getFormattedDateTime()}"
tags: ${this.settings.enableAtomizedTag ? "atomized" : ""}${this.settings.customTags ? (this.settings.enableAtomizedTag ? ", " : "") + this.settings.customTags : ""}
source: "[[${sourceFilePath}]]"
---
3. You MUST separate each note by placing '<<<>>>' on its own line between notes
4. After the frontmatter, each note must start with a level 1 heading (# Title)
5. The content should be self-contained and independently understandable
6. Use proper Markdown formatting
7. Do not include the separator at the start or end of the response`;
}
}