-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnlang.js
More file actions
110 lines (94 loc) · 2.85 KB
/
Copy pathnlang.js
File metadata and controls
110 lines (94 loc) · 2.85 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import { readdir, readFile, writeFile } from "fs/promises";
import { join } from "path";
import { config } from "dotenv";
// Load .env file when running locally
config();
const { OPENAI_API_KEY, LLM_MODEL, LLM_BASEPATH } = process.env;
function getSecretForHostname(hostname) {
// Convert hostname to env var format: github.com -> GITHUB_SECRET
const envKey =
hostname
.split(".")
.slice(0, -1) // Remove TLD
.join("_")
.toUpperCase()
.replace(/-/g, "_") + "_SECRET";
return process.env[envKey];
}
async function fetchUrl(url) {
const { hostname } = new URL(url);
const secret = getSecretForHostname(hostname);
const headers = {};
if (secret) {
headers["Authorization"] = `Bearer ${secret}`;
}
const response = await fetch(url, { headers });
if (!response.ok) {
throw new Error(`Failed to fetch ${url}: ${response.status}`);
}
return response.text();
}
async function replaceUrlsWithContent(content) {
// Match URLs (http/https)
const urlRegex = /https?:\/\/[^\s<>"{}|\\^`\[\]]+/g;
const urls = [...new Set(content.match(urlRegex) || [])];
for (const url of urls) {
try {
const fetched = await fetchUrl(url);
content = content.replaceAll(url, fetched);
} catch (err) {
console.error(`Warning: Could not fetch ${url}: ${err.message}`);
}
}
return content;
}
async function findMdMdFiles(dir = ".") {
const files = [];
const entries = await readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const path = join(dir, entry.name);
if (entry.isDirectory() && !entry.name.startsWith(".")) {
files.push(...(await findMdMdFiles(path)));
} else if (entry.name.endsWith(".md.md")) {
files.push(path);
}
}
return files;
}
async function chat(prompt) {
const response = await fetch(`${LLM_BASEPATH}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: LLM_MODEL,
messages: [{ role: "user", content: prompt }],
}),
});
if (!response.ok) {
throw new Error(
`LLM API error: ${response.status} ${await response.text()}`,
);
}
const data = await response.json();
return data.choices[0].message.content;
}
async function main() {
const files = await findMdMdFiles();
console.log(`Found ${files.length} .md.md files`);
for (const file of files) {
console.log(`Processing: ${file}`);
const content = await readFile(file, "utf-8");
const processedContent = await replaceUrlsWithContent(content);
const result = await chat(processedContent);
const outputPath = file.replace(/\.md\.md$/, ".md");
await writeFile(outputPath, result);
console.log(`Written: ${outputPath}`);
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});