-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathllm.js
More file actions
470 lines (384 loc) · 12.5 KB
/
llm.js
File metadata and controls
470 lines (384 loc) · 12.5 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/**
* LLM Integration for xboost
* Multi-provider support via Vercel AI SDK
*
* Supported providers:
* - Anthropic (Claude)
* - OpenAI (GPT-4, GPT-3.5)
* - Google (Gemini)
* - OpenRouter (access to many models)
* - Ollama (local models)
* - LM Studio (local models)
*/
import { generateText } from 'ai';
import { createAnthropic } from '@ai-sdk/anthropic';
import { createOpenAI } from '@ai-sdk/openai';
import { createGoogleGenerativeAI } from '@ai-sdk/google';
// Provider configurations
const PROVIDERS = {
anthropic: {
name: 'Anthropic (Claude)',
envKey: ['ANTHROPIC_API_KEY', 'CLAUDE_API_KEY'],
defaultModel: 'claude-sonnet-4-20250514',
models: ['claude-sonnet-4-20250514', 'claude-3-5-sonnet-20241022', 'claude-3-haiku-20240307'],
},
openai: {
name: 'OpenAI',
envKey: ['OPENAI_API_KEY'],
defaultModel: 'gpt-4o',
models: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'gpt-3.5-turbo'],
},
google: {
name: 'Google (Gemini)',
envKey: ['GOOGLE_GENERATIVE_AI_API_KEY', 'GEMINI_API_KEY'],
defaultModel: 'gemini-2.0-flash',
models: ['gemini-2.0-flash', 'gemini-1.5-pro', 'gemini-1.5-flash'],
},
openrouter: {
name: 'OpenRouter',
envKey: ['OPENROUTER_API_KEY'],
defaultModel: 'anthropic/claude-3.5-sonnet',
models: ['anthropic/claude-3.5-sonnet', 'openai/gpt-4o', 'google/gemini-pro', 'meta-llama/llama-3.1-70b-instruct'],
},
ollama: {
name: 'Ollama (Local)',
envKey: [], // No API key needed
defaultModel: 'llama3.2',
models: ['llama3.2', 'mistral', 'codellama', 'phi3'],
baseURL: 'http://localhost:11434/v1',
},
lmstudio: {
name: 'LM Studio (Local)',
envKey: [], // No API key needed
defaultModel: 'local-model',
models: ['local-model'],
baseURL: 'http://localhost:1234/v1',
},
};
// Get configured provider and model
function getProviderConfig() {
// Check for explicit provider setting
const explicitProvider = process.env.XBOOST_PROVIDER?.toLowerCase();
const explicitModel = process.env.XBOOST_MODEL;
// If explicitly set, use that
if (explicitProvider && PROVIDERS[explicitProvider]) {
return {
provider: explicitProvider,
model: explicitModel || PROVIDERS[explicitProvider].defaultModel,
};
}
// Auto-detect based on available API keys
for (const [providerId, config] of Object.entries(PROVIDERS)) {
// Skip local providers in auto-detect (user should explicitly choose)
if (providerId === 'ollama' || providerId === 'lmstudio') continue;
for (const envKey of config.envKey) {
if (process.env[envKey]) {
return {
provider: providerId,
model: explicitModel || config.defaultModel,
apiKey: process.env[envKey],
};
}
}
}
return null;
}
// Create the appropriate provider instance
function createProvider(providerConfig) {
const { provider, model, apiKey } = providerConfig;
const config = PROVIDERS[provider];
switch (provider) {
case 'anthropic': {
const anthropic = createAnthropic({ apiKey });
return anthropic(model);
}
case 'openai': {
const openai = createOpenAI({ apiKey });
return openai(model);
}
case 'google': {
const google = createGoogleGenerativeAI({ apiKey });
return google(model);
}
case 'openrouter': {
const openrouter = createOpenAI({
apiKey,
baseURL: 'https://openrouter.ai/api/v1',
});
return openrouter(model);
}
case 'ollama': {
const ollama = createOpenAI({
apiKey: 'ollama', // Ollama doesn't need a real key
baseURL: process.env.OLLAMA_BASE_URL || config.baseURL,
});
return ollama(model);
}
case 'lmstudio': {
const lmstudio = createOpenAI({
apiKey: 'lmstudio', // LM Studio doesn't need a real key
baseURL: process.env.LMSTUDIO_BASE_URL || config.baseURL,
});
return lmstudio(model);
}
default:
throw new Error(`Unknown provider: ${provider}`);
}
}
// Build the system prompt with algorithm knowledge
export function buildSystemPrompt() {
return `You are an X/Twitter content optimization expert. Your job is to help create engaging posts that perform well with the X algorithm.
## X Algorithm Knowledge (from actual source code)
### Engagement Weights (what the algorithm optimizes for):
- Reply: 11x weight (MOST IMPORTANT - drive conversation!)
- Follow: 10x weight
- Repost/Quote/Share: 4x weight each
- Bookmark: 2x weight
- Like: 1x weight (baseline)
- Negative: Block (-50x), Mute (-30x), Report (-100x)
### Content Multipliers:
- Threads: 1.3x boost
- Quote tweets: 1.2x boost
- Original tweets: 1.0x
- Pure reposts: 0.5x (add commentary!)
### Media Boosts:
- Polls: 1.3x (drive engagement)
- Video: 1.2x
- Multiple images: 1.15x
- Single image: 1.1x
- External links: 0.95x (slight penalty - add value to compensate)
### Timing:
- Posts under 1 hour old: 1.5x recency boost
- Author diversity matters - don't flood
## Your Guidelines:
1. **Prioritize replies over likes** - Write posts that invite discussion, ask questions, share opinions people can respond to
2. **Use proven hooks**:
- "I spent X hours/days/years..."
- "Here's what nobody tells you about..."
- "The biggest mistake I see..."
- "Unpopular opinion:"
- "X things I learned from..."
3. **Optimal structure**:
- Strong hook in first line (this shows in timeline)
- ~100-280 characters for single posts
- Break into threads if >200 chars of value
- End with question or CTA when appropriate
4. **Avoid**:
- Spammy language (buy now, click here, follow back)
- Excessive emojis
- Pure self-promotion without value
- Engagement bait that feels manipulative
5. **Voice**: Keep the author's authentic voice. Optimize structure and hooks, don't make it sound generic.
When given content to optimize, provide multiple variations with different angles (hot take, question, thread, personal story).`;
}
// Call LLM with unified interface
export async function callLLM(prompt, options = {}) {
const providerConfig = getProviderConfig();
if (!providerConfig) {
return {
success: false,
error: `No AI provider configured. Set one of these environment variables:
Cloud Providers:
ANTHROPIC_API_KEY - Claude (recommended)
OPENAI_API_KEY - GPT-4
GOOGLE_GENERATIVE_AI_API_KEY - Gemini
OPENROUTER_API_KEY - OpenRouter (many models)
Local Models:
XBOOST_PROVIDER=ollama - Use Ollama
XBOOST_PROVIDER=lmstudio - Use LM Studio
Optional:
XBOOST_MODEL - Override default model`,
};
}
const { maxTokens = 1024, temperature = 0.7 } = options;
try {
const model = createProvider(providerConfig);
const { text } = await generateText({
model,
system: buildSystemPrompt(),
prompt,
maxTokens,
temperature,
});
return {
success: true,
text,
provider: providerConfig.provider,
model: providerConfig.model,
};
} catch (error) {
return {
success: false,
error: error.message,
provider: providerConfig.provider,
};
}
}
// Optimize a rough idea/text into engaging posts
export async function optimizeText(text, options = {}) {
const { context = '' } = options;
const prompt = `Optimize this content for X/Twitter engagement.
**Original content:**
${text}
${context ? `**Additional context:** ${context}` : ''}
**Task:** Create 3-4 variations optimized for the X algorithm:
1. **Hook version** - Lead with a compelling hook that stops the scroll
2. **Question version** - Frame it to invite replies (remember: replies = 11x weight!)
3. **Thread opener** - If there's enough substance, create a thread-worthy opener with 🧵
4. **Hot take version** - A slightly contrarian or bold angle
For each variation:
- Show the optimized post text (ready to copy-paste)
- Note the key optimization applied
- Keep the author's authentic voice
Format each as:
### [Type]
\`\`\`
[Post text here]
\`\`\`
*Optimization: [what you did]*`;
return callLLM(prompt);
}
// Generate posts from a URL/link
export async function optimizeFromUrl(url, urlContent, options = {}) {
const prompt = `Create engaging X/Twitter posts about this content.
**URL:** ${url}
**Content summary:**
${urlContent}
**Task:** Generate 4 different posts sharing this link, optimized for the X algorithm:
1. **Value-add post** - Share the key insight + your take (remember: external links get 0.95x, so add value!)
2. **Question post** - Frame it to drive discussion (replies = 11x!)
3. **Contrarian/hot take** - A bold perspective on this content
4. **Thread opener** - If there's enough substance for a thread with 🧵
For each:
- The post should work standalone (people should want to engage even before clicking)
- Include the URL naturally
- Add a hook that makes people stop scrolling
Format each as:
### [Type]
\`\`\`
[Post text here - include ${url} where appropriate]
\`\`\`
*Hook used: [the technique]*
*Expected engagement driver: [reply/share/click]*`;
return callLLM(prompt);
}
// Generate smart replies to a tweet
export async function generateReplies(tweetText, tweetAuthor, options = {}) {
const prompt = `Generate smart reply options for this tweet.
**Original tweet by @${tweetAuthor}:**
"${tweetText}"
**Task:** Create 4 reply options that could perform well:
1. **Add value** - Share additional insight or information
2. **Ask smart question** - Genuine curiosity that drives thread
3. **Share experience** - Relate with a personal angle
4. **Friendly challenge** - Respectful different perspective (controversial drives engagement, but stay constructive)
For each reply:
- Keep it concise (replies should be punchy)
- Make it genuine, not sycophantic
- Aim to start a conversation, not end it
Format:
### [Type]
\`\`\`
[Reply text]
\`\`\`
*Why this works: [brief explanation]*`;
return callLLM(prompt);
}
// Generate a full thread from content
export async function generateThread(topic, content, options = {}) {
const { maxTweets = 7 } = options;
const prompt = `Create an engaging Twitter/X thread about this topic.
**Topic:** ${topic}
**Source content/ideas:**
${content}
**Task:** Create a ${maxTweets}-tweet thread optimized for the X algorithm.
Thread structure:
1. **Tweet 1 (Hook)** - Must stop the scroll. Use a proven hook pattern. End with 🧵
2. **Tweets 2-${maxTweets - 1}** - Each tweet should:
- Deliver ONE clear point
- Be valuable standalone (people might see just one)
- Flow logically from previous
- Be under 280 characters
3. **Final tweet** - Call to action or question to drive replies
Remember:
- Threads get 1.3x algorithm boost
- Each tweet in thread should be self-contained value
- Questions throughout drive replies (11x weight!)
Format:
### Tweet 1/X (Hook)
\`\`\`
[text]
\`\`\`
### Tweet 2/X
\`\`\`
[text]
\`\`\`
[continue for all tweets]`;
return callLLM(prompt, { maxTokens: 2000 });
}
// Analyze and improve an existing post
export async function improvePost(originalPost, metrics = {}) {
const prompt = `Analyze and improve this X/Twitter post.
**Original post:**
"${originalPost}"
${Object.keys(metrics).length > 0 ? `**Current metrics:** ${JSON.stringify(metrics)}` : ''}
**Task:**
1. Analyze what's working and what's not (based on X algorithm knowledge)
2. Provide 2 improved versions
Analysis should cover:
- Hook strength (does first line stop scroll?)
- Reply potential (will people respond?)
- Length optimization
- Missing elements (question? CTA? hook?)
Format:
### Analysis
[Your analysis]
### Improved Version 1 (Minor tweaks)
\`\`\`
[Optimized post]
\`\`\`
*Changes: [what you changed and why]*
### Improved Version 2 (Reimagined)
\`\`\`
[More significantly reworked version]
\`\`\`
*Changes: [what you changed and why]*`;
return callLLM(prompt);
}
// Check if LLM is available
export async function checkLLMAvailable() {
return getProviderConfig() !== null;
}
// Get current provider info
export function getProviderInfo() {
const config = getProviderConfig();
if (!config) return null;
return {
provider: config.provider,
name: PROVIDERS[config.provider].name,
model: config.model,
};
}
// List available providers
export function listProviders() {
return Object.entries(PROVIDERS).map(([id, config]) => ({
id,
name: config.name,
models: config.models,
envKeys: config.envKey,
isLocal: id === 'ollama' || id === 'lmstudio',
}));
}
export default {
buildSystemPrompt,
callLLM,
optimizeText,
optimizeFromUrl,
generateReplies,
generateThread,
improvePost,
checkLLMAvailable,
getProviderInfo,
listProviders,
PROVIDERS,
};