solanapolis 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/README.md +518 -0
  2. package/bin/solanapolis.js +197 -0
  3. package/convex/_generated/api.d.ts +175 -0
  4. package/convex/_generated/api.js +23 -0
  5. package/convex/_generated/dataModel.d.ts +60 -0
  6. package/convex/_generated/server.d.ts +143 -0
  7. package/convex/_generated/server.js +93 -0
  8. package/convex/agent/conversation.ts +352 -0
  9. package/convex/agent/embeddingsCache.ts +110 -0
  10. package/convex/agent/memory.ts +450 -0
  11. package/convex/agent/schema.ts +53 -0
  12. package/convex/aiChat.ts +54 -0
  13. package/convex/aiTown/agent.ts +382 -0
  14. package/convex/aiTown/agentDescription.ts +27 -0
  15. package/convex/aiTown/agentInputs.ts +155 -0
  16. package/convex/aiTown/agentOperations.ts +178 -0
  17. package/convex/aiTown/conversation.ts +395 -0
  18. package/convex/aiTown/conversationMembership.ts +38 -0
  19. package/convex/aiTown/game.ts +371 -0
  20. package/convex/aiTown/ids.ts +32 -0
  21. package/convex/aiTown/inputHandler.ts +9 -0
  22. package/convex/aiTown/inputs.ts +25 -0
  23. package/convex/aiTown/insertInput.ts +20 -0
  24. package/convex/aiTown/location.ts +32 -0
  25. package/convex/aiTown/main.ts +154 -0
  26. package/convex/aiTown/movement.ts +189 -0
  27. package/convex/aiTown/player.ts +310 -0
  28. package/convex/aiTown/playerDescription.ts +35 -0
  29. package/convex/aiTown/schema.ts +79 -0
  30. package/convex/aiTown/world.ts +65 -0
  31. package/convex/aiTown/worldMap.ts +74 -0
  32. package/convex/chat.ts +79 -0
  33. package/convex/constants.ts +78 -0
  34. package/convex/convex.config.ts +6 -0
  35. package/convex/crons.ts +89 -0
  36. package/convex/engine/abstractGame.ts +199 -0
  37. package/convex/engine/historicalObject.ts +355 -0
  38. package/convex/engine/schema.ts +56 -0
  39. package/convex/http.ts +36 -0
  40. package/convex/init.ts +110 -0
  41. package/convex/messages.ts +53 -0
  42. package/convex/npcCarAgents.ts +415 -0
  43. package/convex/schema.ts +61 -0
  44. package/convex/streaming.ts +23 -0
  45. package/convex/testing.ts +202 -0
  46. package/convex/tsconfig.json +18 -0
  47. package/convex/util/FastIntegerCompression.ts +221 -0
  48. package/convex/util/assertNever.ts +4 -0
  49. package/convex/util/asyncMap.ts +20 -0
  50. package/convex/util/compression.ts +71 -0
  51. package/convex/util/geometry.ts +132 -0
  52. package/convex/util/isSimpleObject.ts +11 -0
  53. package/convex/util/llm.ts +724 -0
  54. package/convex/util/minheap.ts +38 -0
  55. package/convex/util/object.ts +22 -0
  56. package/convex/util/sleep.ts +3 -0
  57. package/convex/util/types.ts +33 -0
  58. package/convex/util/xxhash.ts +228 -0
  59. package/convex/world.ts +257 -0
  60. package/data/animations/campfire.json +45 -0
  61. package/data/animations/gentlesparkle.json +37 -0
  62. package/data/animations/gentlesplash.json +61 -0
  63. package/data/animations/gentlewaterfall.json +61 -0
  64. package/data/animations/windmill.json +78 -0
  65. package/data/characters.ts +121 -0
  66. package/data/convertMap.js +74 -0
  67. package/data/gentle.js +330 -0
  68. package/data/spritesheets/f1.ts +75 -0
  69. package/data/spritesheets/f2.ts +75 -0
  70. package/data/spritesheets/f3.ts +75 -0
  71. package/data/spritesheets/f4.ts +75 -0
  72. package/data/spritesheets/f5.ts +75 -0
  73. package/data/spritesheets/f6.ts +75 -0
  74. package/data/spritesheets/f7.ts +75 -0
  75. package/data/spritesheets/f8.ts +75 -0
  76. package/data/spritesheets/p1.ts +59 -0
  77. package/data/spritesheets/p2.ts +59 -0
  78. package/data/spritesheets/p3.ts +59 -0
  79. package/data/spritesheets/player.ts +59 -0
  80. package/data/spritesheets/types.ts +26 -0
  81. package/eslint.config.mjs +37 -0
  82. package/next.config.ts +7 -0
  83. package/package.json +85 -0
  84. package/postcss.config.mjs +7 -0
  85. package/public/file.svg +1 -0
  86. package/public/globe.svg +1 -0
  87. package/public/helius-icon.svg +84 -0
  88. package/public/helius-logo.svg +85 -0
  89. package/public/next.svg +1 -0
  90. package/public/plane.glb +0 -0
  91. package/public/vercel.svg +1 -0
  92. package/public/window.svg +1 -0
  93. package/scripts/clear-city.ts +74 -0
  94. package/scripts/seed-wallets.ts +185 -0
  95. package/scripts/setup-webhook.ts +73 -0
  96. package/src/app/api/auth/callback/route.ts +6 -0
  97. package/src/app/api/auth/link-wallet/route.ts +6 -0
  98. package/src/app/api/auth/phantom/route.ts +6 -0
  99. package/src/app/api/broadcast-position/route.ts +59 -0
  100. package/src/app/api/leaderboard/route.ts +85 -0
  101. package/src/app/api/network-stats/route.ts +86 -0
  102. package/src/app/api/parcel-reward/route.ts +181 -0
  103. package/src/app/api/queue-status/route.ts +30 -0
  104. package/src/app/api/snapshots/route.ts +37 -0
  105. package/src/app/api/transactions/enhanced/route.ts +57 -0
  106. package/src/app/api/treasury/route.ts +83 -0
  107. package/src/app/api/wallet/[address]/balances/route.ts +124 -0
  108. package/src/app/api/wallet/[address]/identity/route.ts +32 -0
  109. package/src/app/api/wallet/[address]/route.ts +216 -0
  110. package/src/app/api/wallet/[address]/traded-tokens/route.ts +41 -0
  111. package/src/app/api/wallets/route.ts +68 -0
  112. package/src/app/api/webhooks/helius/route.ts +76 -0
  113. package/src/app/auth/callback/page.tsx +29 -0
  114. package/src/app/favicon.ico +0 -0
  115. package/src/app/globals.css +39 -0
  116. package/src/app/layout.tsx +43 -0
  117. package/src/app/page.tsx +16 -0
  118. package/src/components/AITownNPCs.tsx +206 -0
  119. package/src/components/ActivityFeed.tsx +189 -0
  120. package/src/components/AuthPanel.tsx +163 -0
  121. package/src/components/BeachScene.tsx +280 -0
  122. package/src/components/Building.tsx +138 -0
  123. package/src/components/CesiumFlight.tsx +1768 -0
  124. package/src/components/CesiumGlobe.tsx +616 -0
  125. package/src/components/CitizenCard.tsx +442 -0
  126. package/src/components/CitizenCardModal.tsx +153 -0
  127. package/src/components/CityGrid.tsx +313 -0
  128. package/src/components/CityLandmarks.tsx +427 -0
  129. package/src/components/CityScene.tsx +1289 -0
  130. package/src/components/CitySlotsBadge.tsx +68 -0
  131. package/src/components/CockpitHUD.tsx +460 -0
  132. package/src/components/ConvexWrapper.tsx +19 -0
  133. package/src/components/DubaiDistrict.tsx +630 -0
  134. package/src/components/FlightMiniMap.tsx +133 -0
  135. package/src/components/GameChat.tsx +383 -0
  136. package/src/components/GameHUD.tsx +393 -0
  137. package/src/components/Ground.tsx +14 -0
  138. package/src/components/HowItWorksModal.tsx +251 -0
  139. package/src/components/IngestionBanner.tsx +123 -0
  140. package/src/components/InstancedBuildings.tsx +316 -0
  141. package/src/components/InstancedCars.tsx +504 -0
  142. package/src/components/InstancedCityPlanes.tsx +259 -0
  143. package/src/components/InstancedHouses.tsx +246 -0
  144. package/src/components/InstancedLampPosts.tsx +201 -0
  145. package/src/components/InstancedResidentCars.tsx +357 -0
  146. package/src/components/InstancedRoadDashes.tsx +42 -0
  147. package/src/components/InstancedSkyscrapers.tsx +434 -0
  148. package/src/components/InstancedTrees.tsx +67 -0
  149. package/src/components/LeaderboardPanel.tsx +136 -0
  150. package/src/components/MultiplayerPlanes.tsx +128 -0
  151. package/src/components/NetworkStats.tsx +83 -0
  152. package/src/components/NewBuildingSpotlight.tsx +93 -0
  153. package/src/components/ParcelChallengeBanner.tsx +242 -0
  154. package/src/components/ParcelReward.tsx +191 -0
  155. package/src/components/Park.tsx +42 -0
  156. package/src/components/PhantomWrapper.tsx +22 -0
  157. package/src/components/PixelStreamViewer.tsx +335 -0
  158. package/src/components/PlaneMode.tsx +190 -0
  159. package/src/components/PlayerCar.tsx +211 -0
  160. package/src/components/PlayerPlane.tsx +255 -0
  161. package/src/components/ProjectileRenderer.tsx +249 -0
  162. package/src/components/QueueStatusBanner.tsx +86 -0
  163. package/src/components/RealPlayerTags.tsx +82 -0
  164. package/src/components/SceneLighting.tsx +382 -0
  165. package/src/components/SelectionBeam.tsx +59 -0
  166. package/src/components/SwapPanel.tsx +104 -0
  167. package/src/components/SwapParticles.tsx +237 -0
  168. package/src/components/TreasureGate.tsx +505 -0
  169. package/src/components/WalletPanel.tsx +421 -0
  170. package/src/components/WalletSearch.tsx +244 -0
  171. package/src/components/WelcomeOverlay.tsx +135 -0
  172. package/src/components/WindowTooltip.tsx +498 -0
  173. package/src/context/AuthContext.tsx +230 -0
  174. package/src/lib/bot-detection.ts +125 -0
  175. package/src/lib/building-math.ts +136 -0
  176. package/src/lib/building-shader.ts +253 -0
  177. package/src/lib/car-paths.ts +244 -0
  178. package/src/lib/car-system.ts +182 -0
  179. package/src/lib/city-constants.ts +29 -0
  180. package/src/lib/city-slots.ts +35 -0
  181. package/src/lib/city-zoning.ts +64 -0
  182. package/src/lib/collision-map.ts +147 -0
  183. package/src/lib/day-night.ts +252 -0
  184. package/src/lib/export-card.ts +28 -0
  185. package/src/lib/helius-webhook.ts +90 -0
  186. package/src/lib/helius.ts +74 -0
  187. package/src/lib/house-shader.ts +119 -0
  188. package/src/lib/mock-data.ts +56 -0
  189. package/src/lib/multiplayer-manager.ts +329 -0
  190. package/src/lib/plane-physics.ts +66 -0
  191. package/src/lib/player-car.ts +147 -0
  192. package/src/lib/player-plane.ts +200 -0
  193. package/src/lib/projectile-system.ts +272 -0
  194. package/src/lib/skyscraper-types.ts +52 -0
  195. package/src/lib/sound-engine.ts +464 -0
  196. package/src/lib/supabase-admin.ts +9 -0
  197. package/src/lib/supabase.ts +8 -0
  198. package/src/lib/swap-events.ts +70 -0
  199. package/src/middleware.ts +37 -0
  200. package/src/types/phantom.d.ts +16 -0
  201. package/src/types/wallet.ts +20 -0
  202. package/tsconfig.json +34 -0
@@ -0,0 +1,724 @@
1
+ // That's right! No imports and no dependencies 🤯
2
+
3
+ const OPENAI_EMBEDDING_DIMENSION = 1536;
4
+ const TOGETHER_EMBEDDING_DIMENSION = 768;
5
+ const OLLAMA_EMBEDDING_DIMENSION = 1024;
6
+
7
+ export const EMBEDDING_DIMENSION: number = OPENAI_EMBEDDING_DIMENSION;
8
+
9
+ export function detectMismatchedLLMProvider() {
10
+ switch (EMBEDDING_DIMENSION) {
11
+ case OPENAI_EMBEDDING_DIMENSION:
12
+ if (!process.env.OPENAI_API_KEY) {
13
+ throw new Error(
14
+ "Are you trying to use OpenAI? If so, run: npx convex env set OPENAI_API_KEY 'your-key'",
15
+ );
16
+ }
17
+ break;
18
+ case TOGETHER_EMBEDDING_DIMENSION:
19
+ if (!process.env.TOGETHER_API_KEY) {
20
+ throw new Error(
21
+ "Are you trying to use Together.ai? If so, run: npx convex env set TOGETHER_API_KEY 'your-key'",
22
+ );
23
+ }
24
+ break;
25
+ case OLLAMA_EMBEDDING_DIMENSION:
26
+ break;
27
+ default:
28
+ if (!process.env.LLM_API_URL) {
29
+ throw new Error(
30
+ "Are you trying to use a custom cloud-hosted LLM? If so, run: npx convex env set LLM_API_URL 'your-url'",
31
+ );
32
+ }
33
+ break;
34
+ }
35
+ }
36
+
37
+ export interface LLMConfig {
38
+ provider: 'openai' | 'together' | 'ollama' | 'custom';
39
+ url: string; // Should not have a trailing slash
40
+ chatModel: string;
41
+ embeddingModel: string;
42
+ stopWords: string[];
43
+ apiKey: string | undefined;
44
+ }
45
+
46
+ export function getLLMConfig(): LLMConfig {
47
+ // OpenRouter support
48
+ if (process.env.OPENROUTER_API_KEY) {
49
+ return {
50
+ provider: 'custom',
51
+ url: 'https://openrouter.ai/api',
52
+ chatModel: process.env.OPENROUTER_MODEL ?? 'minimax/minimax-m2-her',
53
+ embeddingModel: process.env.OPENAI_EMBEDDING_MODEL ?? 'text-embedding-ada-002',
54
+ stopWords: [],
55
+ apiKey: process.env.OPENROUTER_API_KEY,
56
+ };
57
+ }
58
+ let provider = process.env.LLM_PROVIDER;
59
+ if (provider ? provider === 'openai' : process.env.OPENAI_API_KEY) {
60
+ if (EMBEDDING_DIMENSION !== OPENAI_EMBEDDING_DIMENSION) {
61
+ throw new Error('EMBEDDING_DIMENSION must be 1536 for OpenAI');
62
+ }
63
+ return {
64
+ provider: 'openai',
65
+ url: 'https://api.openai.com',
66
+ chatModel: process.env.OPENAI_CHAT_MODEL ?? 'gpt-4o-mini',
67
+ embeddingModel: process.env.OPENAI_EMBEDDING_MODEL ?? 'text-embedding-ada-002',
68
+ stopWords: [],
69
+ apiKey: process.env.OPENAI_API_KEY,
70
+ };
71
+ }
72
+ if (process.env.TOGETHER_API_KEY) {
73
+ if (EMBEDDING_DIMENSION !== TOGETHER_EMBEDDING_DIMENSION) {
74
+ throw new Error('EMBEDDING_DIMENSION must be 768 for Together.ai');
75
+ }
76
+ return {
77
+ provider: 'together',
78
+ url: 'https://api.together.xyz',
79
+ chatModel: process.env.TOGETHER_CHAT_MODEL ?? 'meta-llama/Llama-3-8b-chat-hf',
80
+ embeddingModel:
81
+ process.env.TOGETHER_EMBEDDING_MODEL ?? 'togethercomputer/m2-bert-80M-8k-retrieval',
82
+ stopWords: ['<|eot_id|>'],
83
+ apiKey: process.env.TOGETHER_API_KEY,
84
+ };
85
+ }
86
+ if (process.env.LLM_API_URL) {
87
+ const apiKey = process.env.LLM_API_KEY;
88
+ const url = process.env.LLM_API_URL;
89
+ const chatModel = process.env.LLM_MODEL;
90
+ if (!chatModel) throw new Error('LLM_MODEL is required');
91
+ const embeddingModel = process.env.LLM_EMBEDDING_MODEL;
92
+ if (!embeddingModel) throw new Error('LLM_EMBEDDING_MODEL is required');
93
+ return {
94
+ provider: 'custom',
95
+ url,
96
+ chatModel,
97
+ embeddingModel,
98
+ stopWords: [],
99
+ apiKey,
100
+ };
101
+ }
102
+ // Assume Ollama
103
+ if (EMBEDDING_DIMENSION !== OLLAMA_EMBEDDING_DIMENSION) {
104
+ detectMismatchedLLMProvider();
105
+ throw new Error(
106
+ `Unknown EMBEDDING_DIMENSION ${EMBEDDING_DIMENSION} found` +
107
+ `. See convex/util/llm.ts for details.`,
108
+ );
109
+ }
110
+ // Alternative embedding model:
111
+ // embeddingModel: 'llama3'
112
+ // const OLLAMA_EMBEDDING_DIMENSION = 4096,
113
+ return {
114
+ provider: 'ollama',
115
+ url: process.env.OLLAMA_HOST ?? 'http://127.0.0.1:11434',
116
+ chatModel: process.env.OLLAMA_MODEL ?? 'llama3',
117
+ embeddingModel: process.env.OLLAMA_EMBEDDING_MODEL ?? 'mxbai-embed-large',
118
+ stopWords: ['<|eot_id|>'],
119
+ apiKey: undefined,
120
+ };
121
+ }
122
+
123
+ const AuthHeaders = (): Record<string, string> =>
124
+ getLLMConfig().apiKey
125
+ ? {
126
+ Authorization: 'Bearer ' + getLLMConfig().apiKey,
127
+ }
128
+ : {};
129
+
130
+ // Overload for non-streaming
131
+ export async function chatCompletion(
132
+ body: Omit<CreateChatCompletionRequest, 'model'> & {
133
+ model?: CreateChatCompletionRequest['model'];
134
+ } & {
135
+ stream?: false | null | undefined;
136
+ },
137
+ ): Promise<{ content: string; retries: number; ms: number }>;
138
+ // Overload for streaming
139
+ export async function chatCompletion(
140
+ body: Omit<CreateChatCompletionRequest, 'model'> & {
141
+ model?: CreateChatCompletionRequest['model'];
142
+ } & {
143
+ stream?: true;
144
+ },
145
+ ): Promise<{ content: ChatCompletionContent; retries: number; ms: number }>;
146
+ export async function chatCompletion(
147
+ body: Omit<CreateChatCompletionRequest, 'model'> & {
148
+ model?: CreateChatCompletionRequest['model'];
149
+ },
150
+ ) {
151
+ const config = getLLMConfig();
152
+ body.model = body.model ?? config.chatModel;
153
+ const stopWords = body.stop ? (typeof body.stop === 'string' ? [body.stop] : body.stop) : [];
154
+ if (config.stopWords) stopWords.push(...config.stopWords);
155
+ console.log(body);
156
+ const {
157
+ result: content,
158
+ retries,
159
+ ms,
160
+ } = await retryWithBackoff(async () => {
161
+ const result = await fetch(config.url + '/v1/chat/completions', {
162
+ method: 'POST',
163
+ headers: {
164
+ 'Content-Type': 'application/json',
165
+ ...AuthHeaders(),
166
+ },
167
+
168
+ body: JSON.stringify(body),
169
+ });
170
+ if (!result.ok) {
171
+ const error = await result.text();
172
+ console.error({ error });
173
+ if (result.status === 404 && config.provider === 'ollama') {
174
+ await tryPullOllama(body.model!, error);
175
+ }
176
+ throw {
177
+ retry: result.status === 429 || result.status >= 500,
178
+ error: new Error(`Chat completion failed with code ${result.status}: ${error}`),
179
+ };
180
+ }
181
+ if (body.stream) {
182
+ return new ChatCompletionContent(result.body!, stopWords);
183
+ } else {
184
+ const json = (await result.json()) as CreateChatCompletionResponse;
185
+ const content = json.choices[0].message?.content;
186
+ if (content === undefined) {
187
+ throw new Error('Unexpected result from OpenAI: ' + JSON.stringify(json));
188
+ }
189
+ console.log(content);
190
+ return content;
191
+ }
192
+ });
193
+
194
+ return {
195
+ content,
196
+ retries,
197
+ ms,
198
+ };
199
+ }
200
+
201
+ export async function tryPullOllama(model: string, error: string) {
202
+ if (error.includes('try pulling')) {
203
+ console.error('Embedding model not found, pulling from Ollama');
204
+ const pullResp = await fetch(getLLMConfig().url + '/api/pull', {
205
+ method: 'POST',
206
+ headers: {
207
+ 'Content-Type': 'application/json',
208
+ },
209
+ body: JSON.stringify({ name: model }),
210
+ });
211
+ console.log('Pull response', await pullResp.text());
212
+ throw { retry: true, error: `Dynamically pulled model. Original error: ${error}` };
213
+ }
214
+ }
215
+
216
+ export async function fetchEmbeddingBatch(texts: string[]) {
217
+ const config = getLLMConfig();
218
+ if (config.provider === 'ollama') {
219
+ return {
220
+ ollama: true as const,
221
+ embeddings: await Promise.all(
222
+ texts.map(async (t) => (await ollamaFetchEmbedding(t)).embedding),
223
+ ),
224
+ };
225
+ }
226
+ // For OpenRouter (custom provider), embeddings go through OpenAI directly
227
+ const embeddingUrl = config.provider === 'custom' && process.env.OPENAI_API_KEY
228
+ ? 'https://api.openai.com'
229
+ : config.url;
230
+ const embeddingAuth = config.provider === 'custom' && process.env.OPENAI_API_KEY
231
+ ? { Authorization: 'Bearer ' + process.env.OPENAI_API_KEY }
232
+ : AuthHeaders();
233
+ const {
234
+ result: json,
235
+ retries,
236
+ ms,
237
+ } = await retryWithBackoff(async () => {
238
+ const result = await fetch(embeddingUrl + '/v1/embeddings', {
239
+ method: 'POST',
240
+ headers: {
241
+ 'Content-Type': 'application/json',
242
+ ...embeddingAuth,
243
+ },
244
+
245
+ body: JSON.stringify({
246
+ model: config.embeddingModel,
247
+ input: texts.map((text) => text.replace(/\n/g, ' ')),
248
+ }),
249
+ });
250
+ if (!result.ok) {
251
+ throw {
252
+ retry: result.status === 429 || result.status >= 500,
253
+ error: new Error(`Embedding failed with code ${result.status}: ${await result.text()}`),
254
+ };
255
+ }
256
+ return (await result.json()) as CreateEmbeddingResponse;
257
+ });
258
+ if (json.data.length !== texts.length) {
259
+ console.error(json);
260
+ throw new Error('Unexpected number of embeddings');
261
+ }
262
+ const allembeddings = json.data;
263
+ allembeddings.sort((a, b) => a.index - b.index);
264
+ return {
265
+ ollama: false as const,
266
+ embeddings: allembeddings.map(({ embedding }) => embedding),
267
+ usage: json.usage?.total_tokens,
268
+ retries,
269
+ ms,
270
+ };
271
+ }
272
+
273
+ export async function fetchEmbedding(text: string) {
274
+ const { embeddings, ...stats } = await fetchEmbeddingBatch([text]);
275
+ return { embedding: embeddings[0], ...stats };
276
+ }
277
+
278
+ export async function fetchModeration(content: string) {
279
+ const { result: flagged } = await retryWithBackoff(async () => {
280
+ const result = await fetch(getLLMConfig().url + '/v1/moderations', {
281
+ method: 'POST',
282
+ headers: {
283
+ 'Content-Type': 'application/json',
284
+ ...AuthHeaders(),
285
+ },
286
+
287
+ body: JSON.stringify({
288
+ input: content,
289
+ }),
290
+ });
291
+ if (!result.ok) {
292
+ throw {
293
+ retry: result.status === 429 || result.status >= 500,
294
+ error: new Error(`Embedding failed with code ${result.status}: ${await result.text()}`),
295
+ };
296
+ }
297
+ return (await result.json()) as { results: { flagged: boolean }[] };
298
+ });
299
+ return flagged;
300
+ }
301
+
302
+ // Retry after this much time, based on the retry number.
303
+ const RETRY_BACKOFF = [1000, 10_000, 20_000]; // In ms
304
+ const RETRY_JITTER = 100; // In ms
305
+ type RetryError = { retry: boolean; error: any };
306
+
307
+ export async function retryWithBackoff<T>(
308
+ fn: () => Promise<T>,
309
+ ): Promise<{ retries: number; result: T; ms: number }> {
310
+ let i = 0;
311
+ for (; i <= RETRY_BACKOFF.length; i++) {
312
+ try {
313
+ const start = Date.now();
314
+ const result = await fn();
315
+ const ms = Date.now() - start;
316
+ return { result, retries: i, ms };
317
+ } catch (e) {
318
+ const retryError = e as RetryError;
319
+ if (i < RETRY_BACKOFF.length) {
320
+ if (retryError.retry) {
321
+ console.log(
322
+ `Attempt ${i + 1} failed, waiting ${RETRY_BACKOFF[i]}ms to retry...`,
323
+ Date.now(),
324
+ );
325
+ await new Promise((resolve) =>
326
+ setTimeout(resolve, RETRY_BACKOFF[i] + RETRY_JITTER * Math.random()),
327
+ );
328
+ continue;
329
+ }
330
+ }
331
+ if (retryError.error) throw retryError.error;
332
+ else throw e;
333
+ }
334
+ }
335
+ throw new Error('Unreachable');
336
+ }
337
+
338
+ // Lifted from openai's package
339
+ export interface LLMMessage {
340
+ /**
341
+ * The contents of the message. `content` is required for all messages, and may be
342
+ * null for assistant messages with function calls.
343
+ */
344
+ content: string | null;
345
+
346
+ /**
347
+ * The role of the messages author. One of `system`, `user`, `assistant`, or
348
+ * `function`.
349
+ */
350
+ role: 'system' | 'user' | 'assistant' | 'function';
351
+
352
+ /**
353
+ * The name of the author of this message. `name` is required if role is
354
+ * `function`, and it should be the name of the function whose response is in the
355
+ * `content`. May contain a-z, A-Z, 0-9, and underscores, with a maximum length of
356
+ * 64 characters.
357
+ */
358
+ name?: string;
359
+
360
+ /**
361
+ * The name and arguments of a function that should be called, as generated by the model.
362
+ */
363
+ function_call?: {
364
+ // The name of the function to call.
365
+ name: string;
366
+ /**
367
+ * The arguments to call the function with, as generated by the model in
368
+ * JSON format. Note that the model does not always generate valid JSON,
369
+ * and may hallucinate parameters not defined by your function schema.
370
+ * Validate the arguments in your code before calling your function.
371
+ */
372
+ arguments: string;
373
+ };
374
+ }
375
+
376
+ // Non-streaming chat completion response
377
+ interface CreateChatCompletionResponse {
378
+ id: string;
379
+ object: string;
380
+ created: number;
381
+ model: string;
382
+ choices: {
383
+ index?: number;
384
+ message?: {
385
+ role: 'system' | 'user' | 'assistant';
386
+ content: string;
387
+ };
388
+ finish_reason?: string;
389
+ }[];
390
+ usage?: {
391
+ completion_tokens: number;
392
+
393
+ prompt_tokens: number;
394
+
395
+ total_tokens: number;
396
+ };
397
+ }
398
+
399
+ interface CreateEmbeddingResponse {
400
+ data: {
401
+ index: number;
402
+ object: string;
403
+ embedding: number[];
404
+ }[];
405
+ model: string;
406
+ object: string;
407
+ usage: {
408
+ prompt_tokens: number;
409
+ total_tokens: number;
410
+ };
411
+ }
412
+
413
+ export interface CreateChatCompletionRequest {
414
+ /**
415
+ * ID of the model to use.
416
+ * @type {string}
417
+ * @memberof CreateChatCompletionRequest
418
+ */
419
+ model: string;
420
+ // | 'gpt-4'
421
+ // | 'gpt-4-0613'
422
+ // | 'gpt-4-32k'
423
+ // | 'gpt-4-32k-0613'
424
+ // | 'gpt-3.5-turbo'; // <- our default
425
+ /**
426
+ * The messages to generate chat completions for, in the chat format:
427
+ * https://platform.openai.com/docs/guides/chat/introduction
428
+ * @type {Array<ChatCompletionRequestMessage>}
429
+ * @memberof CreateChatCompletionRequest
430
+ */
431
+ messages: LLMMessage[];
432
+ /**
433
+ * What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or `top_p` but not both.
434
+ * @type {number}
435
+ * @memberof CreateChatCompletionRequest
436
+ */
437
+ temperature?: number | null;
438
+ /**
439
+ * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or `temperature` but not both.
440
+ * @type {number}
441
+ * @memberof CreateChatCompletionRequest
442
+ */
443
+ top_p?: number | null;
444
+ /**
445
+ * How many chat completion choices to generate for each input message.
446
+ * @type {number}
447
+ * @memberof CreateChatCompletionRequest
448
+ */
449
+ n?: number | null;
450
+ /**
451
+ * If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message.
452
+ * @type {boolean}
453
+ * @memberof CreateChatCompletionRequest
454
+ */
455
+ stream?: boolean | null;
456
+ /**
457
+ *
458
+ * @type {CreateChatCompletionRequestStop}
459
+ * @memberof CreateChatCompletionRequest
460
+ */
461
+ stop?: Array<string> | string;
462
+ /**
463
+ * The maximum number of tokens allowed for the generated answer. By default,
464
+ * the number of tokens the model can return will be (4096 - prompt tokens).
465
+ * @type {number}
466
+ * @memberof CreateChatCompletionRequest
467
+ */
468
+ max_tokens?: number;
469
+ /**
470
+ * Number between -2.0 and 2.0. Positive values penalize new tokens based on
471
+ * whether they appear in the text so far, increasing the model\'s likelihood
472
+ * to talk about new topics. See more information about frequency and
473
+ * presence penalties:
474
+ * https://platform.openai.com/docs/api-reference/parameter-details
475
+ * @type {number}
476
+ * @memberof CreateChatCompletionRequest
477
+ */
478
+ presence_penalty?: number | null;
479
+ /**
480
+ * Number between -2.0 and 2.0. Positive values penalize new tokens based on
481
+ * their existing frequency in the text so far, decreasing the model\'s
482
+ * likelihood to repeat the same line verbatim. See more information about
483
+ * presence penalties:
484
+ * https://platform.openai.com/docs/api-reference/parameter-details
485
+ * @type {number}
486
+ * @memberof CreateChatCompletionRequest
487
+ */
488
+ frequency_penalty?: number | null;
489
+ /**
490
+ * Modify the likelihood of specified tokens appearing in the completion.
491
+ * Accepts a json object that maps tokens (specified by their token ID in the
492
+ * tokenizer) to an associated bias value from -100 to 100. Mathematically,
493
+ * the bias is added to the logits generated by the model prior to sampling.
494
+ * The exact effect will vary per model, but values between -1 and 1 should
495
+ * decrease or increase likelihood of selection; values like -100 or 100
496
+ * should result in a ban or exclusive selection of the relevant token.
497
+ * @type {object}
498
+ * @memberof CreateChatCompletionRequest
499
+ */
500
+ logit_bias?: object | null;
501
+ /**
502
+ * A unique identifier representing your end-user, which can help OpenAI to
503
+ * monitor and detect abuse. Learn more:
504
+ * https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids
505
+ * @type {string}
506
+ * @memberof CreateChatCompletionRequest
507
+ */
508
+ user?: string;
509
+ tools?: {
510
+ // The type of the tool. Currently, only function is supported.
511
+ type: 'function';
512
+ function: {
513
+ /**
514
+ * The name of the function to be called. Must be a-z, A-Z, 0-9, or
515
+ * contain underscores and dashes, with a maximum length of 64.
516
+ */
517
+ name: string;
518
+ /**
519
+ * A description of what the function does, used by the model to choose
520
+ * when and how to call the function.
521
+ */
522
+ description?: string;
523
+ /**
524
+ * The parameters the functions accepts, described as a JSON Schema
525
+ * object. See the guide[1] for examples, and the JSON Schema reference[2]
526
+ * for documentation about the format.
527
+ * [1]: https://platform.openai.com/docs/guides/gpt/function-calling
528
+ * [2]: https://json-schema.org/understanding-json-schema/
529
+ * To describe a function that accepts no parameters, provide the value
530
+ * {"type": "object", "properties": {}}.
531
+ */
532
+ parameters: object;
533
+ };
534
+ }[];
535
+ /**
536
+ * Controls which (if any) function is called by the model. `none` means the
537
+ * model will not call a function and instead generates a message.
538
+ * `auto` means the model can pick between generating a message or calling a
539
+ * function. Specifying a particular function via
540
+ * {"type: "function", "function": {"name": "my_function"}} forces the model
541
+ * to call that function.
542
+ *
543
+ * `none` is the default when no functions are present.
544
+ * `auto` is the default if functions are present.
545
+ */
546
+ tool_choice?:
547
+ | 'none' // none means the model will not call a function and instead generates a message.
548
+ | 'auto' // auto means the model can pick between generating a message or calling a function.
549
+ // Specifies a tool the model should use. Use to force the model to call
550
+ // a specific function.
551
+ | {
552
+ // The type of the tool. Currently, only function is supported.
553
+ type: 'function';
554
+ function: { name: string };
555
+ };
556
+ // Replaced by "tools"
557
+ // functions?: {
558
+ // /**
559
+ // * The name of the function to be called. Must be a-z, A-Z, 0-9, or
560
+ // * contain underscores and dashes, with a maximum length of 64.
561
+ // */
562
+ // name: string;
563
+ // /**
564
+ // * A description of what the function does, used by the model to choose
565
+ // * when and how to call the function.
566
+ // */
567
+ // description?: string;
568
+ // /**
569
+ // * The parameters the functions accepts, described as a JSON Schema
570
+ // * object. See the guide[1] for examples, and the JSON Schema reference[2]
571
+ // * for documentation about the format.
572
+ // * [1]: https://platform.openai.com/docs/guides/gpt/function-calling
573
+ // * [2]: https://json-schema.org/understanding-json-schema/
574
+ // * To describe a function that accepts no parameters, provide the value
575
+ // * {"type": "object", "properties": {}}.
576
+ // */
577
+ // parameters: object;
578
+ // }[];
579
+ // /**
580
+ // * Controls how the model responds to function calls. "none" means the model
581
+ // * does not call a function, and responds to the end-user. "auto" means the
582
+ // * model can pick between an end-user or calling a function. Specifying a
583
+ // * particular function via {"name":\ "my_function"} forces the model to call
584
+ // * that function.
585
+ // * - "none" is the default when no functions are present.
586
+ // * - "auto" is the default if functions are present.
587
+ // */
588
+ // function_call?: 'none' | 'auto' | { name: string };
589
+ /**
590
+ * An object specifying the format that the model must output.
591
+ *
592
+ * Setting to { "type": "json_object" } enables JSON mode, which guarantees
593
+ * the message the model generates is valid JSON.
594
+ * *Important*: when using JSON mode, you must also instruct the model to
595
+ * produce JSON yourself via a system or user message. Without this, the model
596
+ * may generate an unending stream of whitespace until the generation reaches
597
+ * the token limit, resulting in a long-running and seemingly "stuck" request.
598
+ * Also note that the message content may be partially cut off if
599
+ * finish_reason="length", which indicates the generation exceeded max_tokens
600
+ * or the conversation exceeded the max context length.
601
+ */
602
+ response_format?: { type: 'text' | 'json_object' };
603
+ }
604
+
605
+ // Checks whether a suffix of s1 is a prefix of s2. For example,
606
+ // ('Hello', 'Kira:') -> false
607
+ // ('Hello Kira', 'Kira:') -> true
608
+ const suffixOverlapsPrefix = (s1: string, s2: string) => {
609
+ for (let i = 1; i <= Math.min(s1.length, s2.length); i++) {
610
+ const suffix = s1.substring(s1.length - i);
611
+ const prefix = s2.substring(0, i);
612
+ if (suffix === prefix) {
613
+ return true;
614
+ }
615
+ }
616
+ return false;
617
+ };
618
+
619
+ export class ChatCompletionContent {
620
+ private readonly body: ReadableStream<Uint8Array>;
621
+ private readonly stopWords: string[];
622
+
623
+ constructor(body: ReadableStream<Uint8Array>, stopWords: string[]) {
624
+ this.body = body;
625
+ this.stopWords = stopWords;
626
+ }
627
+
628
+ async *readInner() {
629
+ for await (const data of this.splitStream(this.body)) {
630
+ if (data.startsWith('data: ')) {
631
+ try {
632
+ const json = JSON.parse(data.substring('data: '.length)) as {
633
+ choices: { delta: { content?: string } }[];
634
+ };
635
+ if (json.choices[0].delta.content) {
636
+ yield json.choices[0].delta.content;
637
+ }
638
+ } catch (e) {
639
+ // e.g. the last chunk is [DONE] which is not valid JSON.
640
+ }
641
+ }
642
+ }
643
+ }
644
+
645
+ // stop words in OpenAI api don't always work.
646
+ // So we have to truncate on our side.
647
+ async *read() {
648
+ let lastFragment = '';
649
+ for await (const data of this.readInner()) {
650
+ lastFragment += data;
651
+ let hasOverlap = false;
652
+ for (const stopWord of this.stopWords) {
653
+ const idx = lastFragment.indexOf(stopWord);
654
+ if (idx >= 0) {
655
+ yield lastFragment.substring(0, idx);
656
+ return;
657
+ }
658
+ if (suffixOverlapsPrefix(lastFragment, stopWord)) {
659
+ hasOverlap = true;
660
+ }
661
+ }
662
+ if (hasOverlap) continue;
663
+ yield lastFragment;
664
+ lastFragment = '';
665
+ }
666
+ yield lastFragment;
667
+ }
668
+
669
+ async readAll() {
670
+ let allContent = '';
671
+ for await (const chunk of this.read()) {
672
+ allContent += chunk;
673
+ }
674
+ return allContent;
675
+ }
676
+
677
+ async *splitStream(stream: ReadableStream<Uint8Array>) {
678
+ const reader = stream.getReader();
679
+ let lastFragment = '';
680
+ try {
681
+ while (true) {
682
+ const { value, done } = await reader.read();
683
+ if (done) {
684
+ // Flush the last fragment now that we're done
685
+ if (lastFragment !== '') {
686
+ yield lastFragment;
687
+ }
688
+ break;
689
+ }
690
+ const data = new TextDecoder().decode(value);
691
+ lastFragment += data;
692
+ const parts = lastFragment.split('\n\n');
693
+ // Yield all except for the last part
694
+ for (let i = 0; i < parts.length - 1; i += 1) {
695
+ yield parts[i];
696
+ }
697
+ // Save the last part as the new last fragment
698
+ lastFragment = parts[parts.length - 1];
699
+ }
700
+ } finally {
701
+ reader.releaseLock();
702
+ }
703
+ }
704
+ }
705
+
706
+ export async function ollamaFetchEmbedding(text: string) {
707
+ const config = getLLMConfig();
708
+ const { result } = await retryWithBackoff(async () => {
709
+ const resp = await fetch(config.url + '/api/embeddings', {
710
+ method: 'POST',
711
+ headers: {
712
+ 'Content-Type': 'application/json',
713
+ },
714
+ body: JSON.stringify({ model: config.embeddingModel, prompt: text }),
715
+ });
716
+ if (resp.status === 404) {
717
+ const error = await resp.text();
718
+ await tryPullOllama(config.embeddingModel, error);
719
+ throw new Error(`Failed to fetch embeddings: ${resp.status}`);
720
+ }
721
+ return (await resp.json()).embedding as number[];
722
+ });
723
+ return { embedding: result };
724
+ }