genaicode 0.0.37 → 0.2.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 (312) hide show
  1. package/README.md +3 -1
  2. package/bin/genaicode-dev.js +11 -0
  3. package/bin/genaicode.cjs +15 -1
  4. package/dist/ai-service/ai-studio.d.ts +6 -0
  5. package/dist/ai-service/ai-studio.js +135 -0
  6. package/dist/ai-service/ai-studio.js.map +1 -0
  7. package/dist/ai-service/anthropic.d.ts +6 -0
  8. package/dist/ai-service/anthropic.js +135 -0
  9. package/dist/ai-service/anthropic.js.map +1 -0
  10. package/dist/ai-service/chat-gpt.d.ts +5 -0
  11. package/dist/ai-service/chat-gpt.js +132 -0
  12. package/dist/ai-service/chat-gpt.js.map +1 -0
  13. package/dist/ai-service/common.d.ts +58 -0
  14. package/dist/ai-service/common.js +38 -0
  15. package/dist/ai-service/common.js.map +1 -0
  16. package/dist/ai-service/common.test.d.ts +1 -0
  17. package/dist/ai-service/common.test.js +85 -0
  18. package/dist/ai-service/common.test.js.map +1 -0
  19. package/dist/ai-service/dall-e.d.ts +14 -0
  20. package/dist/ai-service/dall-e.js +48 -0
  21. package/dist/ai-service/dall-e.js.map +1 -0
  22. package/dist/ai-service/vertex-ai-claude.d.ts +5 -0
  23. package/dist/ai-service/vertex-ai-claude.js +94 -0
  24. package/dist/ai-service/vertex-ai-claude.js.map +1 -0
  25. package/dist/ai-service/vertex-ai-imagen.d.ts +14 -0
  26. package/dist/ai-service/vertex-ai-imagen.js +77 -0
  27. package/dist/ai-service/vertex-ai-imagen.js.map +1 -0
  28. package/dist/ai-service/vertex-ai.d.ts +7 -0
  29. package/dist/ai-service/vertex-ai.js +142 -0
  30. package/dist/ai-service/vertex-ai.js.map +1 -0
  31. package/dist/cli/cli-options.d.ts +10 -0
  32. package/dist/cli/cli-options.js +124 -0
  33. package/dist/cli/cli-options.js.map +1 -0
  34. package/dist/cli/cli-options.test.d.ts +1 -0
  35. package/dist/cli/cli-options.test.js +34 -0
  36. package/dist/cli/cli-options.test.js.map +1 -0
  37. package/dist/cli/cli-params.d.ts +30 -0
  38. package/dist/cli/cli-params.js +109 -0
  39. package/dist/cli/cli-params.js.map +1 -0
  40. package/dist/cli/cli-params.test.d.ts +1 -0
  41. package/dist/cli/cli-params.test.js +38 -0
  42. package/dist/cli/cli-params.test.js.map +1 -0
  43. package/dist/cli/service-autodetect.d.ts +2 -0
  44. package/dist/cli/service-autodetect.js +17 -0
  45. package/dist/cli/service-autodetect.js.map +1 -0
  46. package/dist/cli/service-autodetect.test.d.ts +1 -0
  47. package/dist/cli/service-autodetect.test.js +38 -0
  48. package/dist/cli/service-autodetect.test.js.map +1 -0
  49. package/dist/cli/validate-cli-params.d.ts +18 -0
  50. package/dist/cli/validate-cli-params.js +129 -0
  51. package/dist/cli/validate-cli-params.js.map +1 -0
  52. package/dist/cli/validate-cli-params.test.d.ts +1 -0
  53. package/dist/cli/validate-cli-params.test.js +106 -0
  54. package/dist/cli/validate-cli-params.test.js.map +1 -0
  55. package/dist/files/file-utils.d.ts +2 -0
  56. package/dist/files/file-utils.js +7 -0
  57. package/dist/files/file-utils.js.map +1 -0
  58. package/dist/files/file-utils.test.d.ts +1 -0
  59. package/dist/files/file-utils.test.js +18 -0
  60. package/dist/files/file-utils.test.js.map +1 -0
  61. package/dist/files/find-files.d.ts +8 -0
  62. package/dist/files/find-files.js +76 -0
  63. package/dist/files/find-files.js.map +1 -0
  64. package/dist/files/read-files.d.ts +18 -0
  65. package/dist/files/read-files.js +66 -0
  66. package/dist/files/read-files.js.map +1 -0
  67. package/dist/files/read-files.test.d.ts +1 -0
  68. package/dist/files/read-files.test.js +88 -0
  69. package/dist/files/read-files.test.js.map +1 -0
  70. package/dist/files/temp-buffer.d.ts +2 -0
  71. package/dist/files/temp-buffer.js +12 -0
  72. package/dist/files/temp-buffer.js.map +1 -0
  73. package/dist/files/update-files.d.ts +6 -0
  74. package/dist/files/update-files.js +197 -0
  75. package/dist/files/update-files.js.map +1 -0
  76. package/dist/images/ensure-alpha.d.ts +1 -0
  77. package/dist/images/ensure-alpha.js +5 -0
  78. package/dist/images/ensure-alpha.js.map +1 -0
  79. package/dist/images/imgly-remove-background.d.ts +2 -0
  80. package/dist/images/imgly-remove-background.js +21 -0
  81. package/dist/images/imgly-remove-background.js.map +1 -0
  82. package/dist/images/resize-image.d.ts +19 -0
  83. package/dist/images/resize-image.js +22 -0
  84. package/dist/images/resize-image.js.map +1 -0
  85. package/dist/images/split-image.d.ts +18 -0
  86. package/dist/images/split-image.js +25 -0
  87. package/dist/images/split-image.js.map +1 -0
  88. package/dist/main/codegen-interactive-utils.d.ts +8 -0
  89. package/dist/main/codegen-interactive-utils.js +148 -0
  90. package/dist/main/codegen-interactive-utils.js.map +1 -0
  91. package/dist/main/codegen-interactive.d.ts +2 -0
  92. package/dist/main/codegen-interactive.js +68 -0
  93. package/dist/main/codegen-interactive.js.map +1 -0
  94. package/dist/main/codegen-types.d.ts +28 -0
  95. package/dist/main/codegen-types.js +2 -0
  96. package/dist/main/codegen-types.js.map +1 -0
  97. package/dist/main/codegen.d.ts +4 -0
  98. package/dist/main/codegen.js +164 -0
  99. package/dist/main/codegen.js.map +1 -0
  100. package/dist/main/codegen.test.d.ts +2 -0
  101. package/dist/main/codegen.test.js +273 -0
  102. package/dist/main/codegen.test.js.map +1 -0
  103. package/dist/main/config-lib.d.ts +16 -0
  104. package/dist/main/config-lib.js +28 -0
  105. package/dist/main/config-lib.js.map +1 -0
  106. package/dist/main/config-lib.test.d.ts +1 -0
  107. package/dist/main/config-lib.test.js +64 -0
  108. package/dist/main/config-lib.test.js.map +1 -0
  109. package/dist/main/config.d.ts +6 -0
  110. package/{src → dist}/main/config.js +28 -22
  111. package/dist/main/config.js.map +1 -0
  112. package/dist/main/interactive/codegen-interactive.d.ts +2 -0
  113. package/dist/main/interactive/codegen-interactive.js +55 -0
  114. package/dist/main/interactive/codegen-interactive.js.map +1 -0
  115. package/dist/main/interactive/codegen-interactive.test.d.ts +4 -0
  116. package/dist/main/interactive/codegen-interactive.test.js +77 -0
  117. package/dist/main/interactive/codegen-interactive.test.js.map +1 -0
  118. package/dist/main/interactive/codegen-worker.d.ts +3 -0
  119. package/dist/main/interactive/codegen-worker.js +47 -0
  120. package/dist/main/interactive/codegen-worker.js.map +1 -0
  121. package/dist/main/interactive/common.d.ts +5 -0
  122. package/dist/main/interactive/common.js +51 -0
  123. package/dist/main/interactive/common.js.map +1 -0
  124. package/dist/main/interactive/configure.d.ts +2 -0
  125. package/dist/main/interactive/configure.js +99 -0
  126. package/dist/main/interactive/configure.js.map +1 -0
  127. package/dist/main/interactive/error-handling.d.ts +4 -0
  128. package/dist/main/interactive/error-handling.js +49 -0
  129. package/dist/main/interactive/error-handling.js.map +1 -0
  130. package/dist/main/interactive/help.d.ts +1 -0
  131. package/dist/main/interactive/help.js +22 -0
  132. package/dist/main/interactive/help.js.map +1 -0
  133. package/dist/main/interactive/process-comments.d.ts +2 -0
  134. package/dist/main/interactive/process-comments.js +39 -0
  135. package/dist/main/interactive/process-comments.js.map +1 -0
  136. package/dist/main/interactive/select-ai-service.d.ts +2 -0
  137. package/dist/main/interactive/select-ai-service.js +27 -0
  138. package/dist/main/interactive/select-ai-service.js.map +1 -0
  139. package/dist/main/interactive/task-file.d.ts +2 -0
  140. package/dist/main/interactive/task-file.js +28 -0
  141. package/dist/main/interactive/task-file.js.map +1 -0
  142. package/dist/main/interactive/text-prompt.d.ts +2 -0
  143. package/dist/main/interactive/text-prompt.js +18 -0
  144. package/dist/main/interactive/text-prompt.js.map +1 -0
  145. package/dist/main/interactive/user-interrupt.d.ts +1 -0
  146. package/dist/main/interactive/user-interrupt.js +36 -0
  147. package/dist/main/interactive/user-interrupt.js.map +1 -0
  148. package/dist/main/interactive/worker-script.d.ts +1 -0
  149. package/dist/main/interactive/worker-script.js +24 -0
  150. package/dist/main/interactive/worker-script.js.map +1 -0
  151. package/dist/main/interactive/worker.d.ts +2 -0
  152. package/dist/main/interactive/worker.js +55 -0
  153. package/dist/main/interactive/worker.js.map +1 -0
  154. package/dist/prompt/function-calling-validate.d.ts +3 -0
  155. package/dist/prompt/function-calling-validate.js +33 -0
  156. package/dist/prompt/function-calling-validate.js.map +1 -0
  157. package/dist/prompt/function-calling.d.ts +5 -0
  158. package/{src → dist}/prompt/function-calling.js +25 -24
  159. package/dist/prompt/function-calling.js.map +1 -0
  160. package/dist/prompt/function-defs/ask-question.d.ts +65 -0
  161. package/dist/prompt/function-defs/ask-question.js +67 -0
  162. package/dist/prompt/function-defs/ask-question.js.map +1 -0
  163. package/dist/prompt/function-defs/codegen-summary.d.ts +63 -0
  164. package/dist/prompt/function-defs/codegen-summary.js +80 -0
  165. package/dist/prompt/function-defs/codegen-summary.js.map +1 -0
  166. package/dist/prompt/function-defs/create-directory.d.ts +21 -0
  167. package/dist/prompt/function-defs/create-directory.js +22 -0
  168. package/dist/prompt/function-defs/create-directory.js.map +1 -0
  169. package/dist/prompt/function-defs/create-file.d.ts +25 -0
  170. package/dist/prompt/function-defs/create-file.js +26 -0
  171. package/dist/prompt/function-defs/create-file.js.map +1 -0
  172. package/dist/prompt/function-defs/delete-file.d.ts +21 -0
  173. package/dist/prompt/function-defs/delete-file.js +22 -0
  174. package/dist/prompt/function-defs/delete-file.js.map +1 -0
  175. package/dist/prompt/function-defs/download-file.d.ts +25 -0
  176. package/dist/prompt/function-defs/download-file.js +26 -0
  177. package/dist/prompt/function-defs/download-file.js.map +1 -0
  178. package/dist/prompt/function-defs/explanation.d.ts +17 -0
  179. package/dist/prompt/function-defs/explanation.js +18 -0
  180. package/dist/prompt/function-defs/explanation.js.map +1 -0
  181. package/dist/prompt/function-defs/generate-image.d.ts +41 -0
  182. package/dist/prompt/function-defs/generate-image.js +42 -0
  183. package/dist/prompt/function-defs/generate-image.js.map +1 -0
  184. package/dist/prompt/function-defs/get-image-assets.d.ts +20 -0
  185. package/dist/prompt/function-defs/get-image-assets.js +21 -0
  186. package/dist/prompt/function-defs/get-image-assets.js.map +1 -0
  187. package/dist/prompt/function-defs/get-source-code.d.ts +20 -0
  188. package/dist/prompt/function-defs/get-source-code.js +21 -0
  189. package/dist/prompt/function-defs/get-source-code.js.map +1 -0
  190. package/dist/prompt/function-defs/imgly-remove-background.d.ts +25 -0
  191. package/dist/prompt/function-defs/imgly-remove-background.js +26 -0
  192. package/dist/prompt/function-defs/imgly-remove-background.js.map +1 -0
  193. package/dist/prompt/function-defs/move-file.d.ts +25 -0
  194. package/dist/prompt/function-defs/move-file.js +26 -0
  195. package/dist/prompt/function-defs/move-file.js.map +1 -0
  196. package/dist/prompt/function-defs/patch-file.d.ts +25 -0
  197. package/dist/prompt/function-defs/patch-file.js +39 -0
  198. package/dist/prompt/function-defs/patch-file.js.map +1 -0
  199. package/dist/prompt/function-defs/resize-image.d.ts +36 -0
  200. package/dist/prompt/function-defs/resize-image.js +37 -0
  201. package/dist/prompt/function-defs/resize-image.js.map +1 -0
  202. package/dist/prompt/function-defs/split-image.d.ts +57 -0
  203. package/dist/prompt/function-defs/split-image.js +46 -0
  204. package/dist/prompt/function-defs/split-image.js.map +1 -0
  205. package/dist/prompt/function-defs/update-file.d.ts +25 -0
  206. package/dist/prompt/function-defs/update-file.js +26 -0
  207. package/dist/prompt/function-defs/update-file.js.map +1 -0
  208. package/dist/prompt/limits.d.ts +3 -0
  209. package/dist/prompt/limits.js +19 -0
  210. package/dist/prompt/limits.js.map +1 -0
  211. package/dist/prompt/limits.test.d.ts +1 -0
  212. package/dist/prompt/limits.test.js +35 -0
  213. package/dist/prompt/limits.test.js.map +1 -0
  214. package/dist/prompt/prompt-codegen.d.ts +9 -0
  215. package/dist/prompt/prompt-codegen.js +90 -0
  216. package/dist/prompt/prompt-codegen.js.map +1 -0
  217. package/dist/prompt/prompt-codegen.test.d.ts +1 -0
  218. package/dist/prompt/prompt-codegen.test.js +98 -0
  219. package/dist/prompt/prompt-codegen.test.js.map +1 -0
  220. package/dist/prompt/prompt-consts.d.ts +1 -0
  221. package/{src → dist}/prompt/prompt-consts.js +1 -0
  222. package/dist/prompt/prompt-consts.js.map +1 -0
  223. package/dist/prompt/prompt-service-ask-question.test.d.ts +3 -0
  224. package/dist/prompt/prompt-service-ask-question.test.js +142 -0
  225. package/dist/prompt/prompt-service-ask-question.test.js.map +1 -0
  226. package/dist/prompt/prompt-service.d.ts +28 -0
  227. package/dist/prompt/prompt-service.js +163 -0
  228. package/dist/prompt/prompt-service.js.map +1 -0
  229. package/dist/prompt/prompt-service.test.d.ts +1 -0
  230. package/dist/prompt/prompt-service.test.js +531 -0
  231. package/dist/prompt/prompt-service.test.js.map +1 -0
  232. package/dist/prompt/steps/step-ask-question.d.ts +6 -0
  233. package/dist/prompt/steps/step-ask-question.js +82 -0
  234. package/dist/prompt/steps/step-ask-question.js.map +1 -0
  235. package/dist/prompt/steps/step-generate-image.d.ts +2 -0
  236. package/dist/prompt/steps/step-generate-image.js +29 -0
  237. package/dist/prompt/steps/step-generate-image.js.map +1 -0
  238. package/dist/prompt/steps/step-validate-recover.d.ts +13 -0
  239. package/dist/prompt/steps/step-validate-recover.js +51 -0
  240. package/dist/prompt/steps/step-validate-recover.js.map +1 -0
  241. package/dist/prompt/steps/step-verify-patch.d.ts +7 -0
  242. package/dist/prompt/steps/step-verify-patch.js +41 -0
  243. package/dist/prompt/steps/step-verify-patch.js.map +1 -0
  244. package/dist/prompt/steps/steps-types.d.ts +4 -0
  245. package/dist/prompt/steps/steps-types.js +6 -0
  246. package/dist/prompt/steps/steps-types.js.map +1 -0
  247. package/dist/prompt/systemprompt.d.ts +3 -0
  248. package/dist/prompt/systemprompt.js +47 -0
  249. package/dist/prompt/systemprompt.js.map +1 -0
  250. package/dist/prompt/systemprompt.test.d.ts +3 -0
  251. package/dist/prompt/systemprompt.test.js +46 -0
  252. package/dist/prompt/systemprompt.test.js.map +1 -0
  253. package/package.json +15 -5
  254. package/bin/genaicode.js +0 -5
  255. package/bin/vertex-monkey-patch.cjs +0 -33
  256. package/src/ai-service/anthropic.js +0 -126
  257. package/src/ai-service/chat-gpt.js +0 -126
  258. package/src/ai-service/common.js +0 -49
  259. package/src/ai-service/common.test.js +0 -107
  260. package/src/ai-service/dall-e.js +0 -50
  261. package/src/ai-service/vertex-ai-claude.js +0 -99
  262. package/src/ai-service/vertex-ai-imagen.js +0 -78
  263. package/src/ai-service/vertex-ai.js +0 -156
  264. package/src/cli/cli-options.js +0 -132
  265. package/src/cli/cli-options.test.js +0 -50
  266. package/src/cli/cli-params.js +0 -114
  267. package/src/cli/cli-params.test.js +0 -43
  268. package/src/cli/service-autodetect.js +0 -11
  269. package/src/cli/service-autodetect.test.js +0 -43
  270. package/src/cli/validate-cli-params.js +0 -137
  271. package/src/cli/validate-cli-params.test.js +0 -134
  272. package/src/files/file-utils.js +0 -7
  273. package/src/files/file-utils.test.js +0 -21
  274. package/src/files/find-files.js +0 -86
  275. package/src/files/read-files.js +0 -65
  276. package/src/files/read-files.test.js +0 -103
  277. package/src/files/temp-buffer.js +0 -13
  278. package/src/files/update-files.js +0 -205
  279. package/src/images/ensure-alpha.js +0 -5
  280. package/src/images/imgly-remove-background.js +0 -23
  281. package/src/images/resize-image.js +0 -23
  282. package/src/images/split-image.js +0 -26
  283. package/src/main/codegen.js +0 -120
  284. package/src/main/codegen.test.js +0 -335
  285. package/src/main/config-lib.js +0 -33
  286. package/src/main/config-lib.test.js +0 -80
  287. package/src/prompt/function-calling-validate.js +0 -25
  288. package/src/prompt/function-defs/ask-question.js +0 -33
  289. package/src/prompt/function-defs/codegen-summary.js +0 -87
  290. package/src/prompt/function-defs/create-directory.js +0 -21
  291. package/src/prompt/function-defs/create-file.js +0 -26
  292. package/src/prompt/function-defs/delete-file.js +0 -21
  293. package/src/prompt/function-defs/download-file.js +0 -25
  294. package/src/prompt/function-defs/explanation.js +0 -17
  295. package/src/prompt/function-defs/generate-image.js +0 -51
  296. package/src/prompt/function-defs/get-image-assets.js +0 -21
  297. package/src/prompt/function-defs/get-source-code.js +0 -21
  298. package/src/prompt/function-defs/imgly-remove-background.js +0 -25
  299. package/src/prompt/function-defs/move-file.js +0 -25
  300. package/src/prompt/function-defs/patch-file.js +0 -39
  301. package/src/prompt/function-defs/resize-image.js +0 -36
  302. package/src/prompt/function-defs/split-image.js +0 -45
  303. package/src/prompt/function-defs/update-file.js +0 -26
  304. package/src/prompt/limits.js +0 -23
  305. package/src/prompt/limits.test.js +0 -40
  306. package/src/prompt/prompt-codegen.js +0 -106
  307. package/src/prompt/prompt-codegen.test.js +0 -116
  308. package/src/prompt/prompt-service-ask-question.test.js +0 -163
  309. package/src/prompt/prompt-service.js +0 -335
  310. package/src/prompt/prompt-service.test.js +0 -602
  311. package/src/prompt/systemprompt.js +0 -39
  312. package/src/prompt/systemprompt.test.js +0 -64
package/README.md CHANGED
@@ -58,6 +58,7 @@ npx genaicode --dry-run --explicit-prompt="Analyze my project sourcecode and wri
58
58
 
59
59
  GenAIcode supports various command-line options to customize its behavior:
60
60
 
61
+ - `--interactive`: Run the tool in interactive mode
61
62
  - `--dry-run`: Runs the tool without making any changes to the files.
62
63
  - `--consider-all-files`: Considers all files for code generation, even if they don't contain `@CODEGEN` comments.
63
64
  - `--allow-file-create`: Allows the tool to create new files.
@@ -66,6 +67,7 @@ GenAIcode supports various command-line options to customize its behavior:
66
67
  - `--allow-file-move`: Allows the tool to move files within the project structure.
67
68
  - `--vertex-ai`: Uses Vertex AI with Google's Gemini Pro model for code generation.
68
69
  - `--vertex-ai-claude`: Uses Claude via Vertex AI for code generation.
70
+ - `--ai-studio`: Uses Google AI Studio for code generation, an alternative to Vertex AI with potentially different capabilities or limitations.
69
71
  - `--explicit-prompt=<prompt>`: Provides an explicit prompt for code generation.
70
72
  - `--task-file=<file>`: Specifies a file with a task description for code generation.
71
73
  - `--dependency-tree`: Limits the scope of code generation to files marked with `@CODEGEN` and their dependencies.
@@ -80,7 +82,7 @@ GenAIcode supports various command-line options to customize its behavior:
80
82
  - `--cheap`: Uses a cheaper, faster model for code generation, which may provide lower quality results but is more cost-effective for simpler tasks.
81
83
  - `--content-mask=<path>`: Applies a content mask to limit the initial source code files included in the request. The value should be a prefix of the path relative to rootDir.
82
84
  - `--ignore-pattern="glob/regex"`: Specify a pattern of files to ignore during the initial source code fetching. This saves initial token usage.
83
- - `--ask-question`: Allows the AI assistant to ask questions for clarification during the code generation process.
85
+ - `--disable-ask-question`: Disable the default behavior of AI assistant to ask questions for clarification during the code generation process.
84
86
  - `--disable-cache`: Disables caching for the application, which can be useful if caching is causing issues or if you want to ensure fresh data is used for each operation.
85
87
  - `--help`: Displays the help message with all available options.
86
88
 
@@ -0,0 +1,11 @@
1
+ import url from 'node:url';
2
+ import { register } from 'node:module';
3
+ import path from 'path';
4
+
5
+ const __filename = url.fileURLToPath(import.meta.url);
6
+ register('ts-node/esm', url.pathToFileURL(__filename));
7
+
8
+ const project = path.resolve('./tsconfig.json');
9
+ (await import('ts-node')).register({ project });
10
+
11
+ (await import('../src/main/codegen.ts')).runCodegen();
package/bin/genaicode.cjs CHANGED
@@ -5,4 +5,18 @@ const pleaseUpgradeNode = require('please-upgrade-node');
5
5
  const pkg = require('../package.json');
6
6
  pleaseUpgradeNode(pkg);
7
7
 
8
- import('../src/main/codegen.js').then(({ runCodegen }) => runCodegen());
8
+ const devMode = require('fs').existsSync(`${__dirname}/../src`);
9
+ const forceDist = process.argv.indexOf('--force-dist') >= 0;
10
+
11
+ if (devMode && !forceDist) {
12
+ pleaseUpgradeNode({
13
+ name: "genaicode-dev.js",
14
+ engines: {
15
+ node: ">=20",
16
+ },
17
+ });
18
+
19
+ import('./genaicode-dev.js');
20
+ } else {
21
+ import('../dist/main/codegen.js').then(({ runCodegen }) => runCodegen());
22
+ }
@@ -0,0 +1,6 @@
1
+ import { FunctionCall, FunctionDef, PromptItem } from './common.js';
2
+ import { CodegenOptions } from '../main/codegen-types.js';
3
+ /**
4
+ * This function generates content using the Anthropic Claude model via Vertex AI.
5
+ */
6
+ export declare function generateContent(prompt: PromptItem[], functionDefs: FunctionDef[], requiredFunctionName: string | null, temperature: number, cheap: boolean | undefined, options: CodegenOptions): Promise<FunctionCall[]>;
@@ -0,0 +1,135 @@
1
+ import { FunctionCallingMode, GoogleGenerativeAI, HarmBlockThreshold, HarmCategory, } from '@google/generative-ai';
2
+ import assert from 'node:assert';
3
+ import { printTokenUsageAndCost, processFunctionCalls } from './common.js';
4
+ import { abortController } from '../main/interactive/codegen-worker.js';
5
+ /**
6
+ * This function generates content using the Anthropic Claude model via Vertex AI.
7
+ */
8
+ export async function generateContent(prompt, functionDefs, requiredFunctionName, temperature, cheap = false, options) {
9
+ const messages = prompt
10
+ .filter((item) => item.type === 'user' || item.type === 'assistant')
11
+ .map((item) => {
12
+ if (item.type === 'user') {
13
+ const content = {
14
+ role: 'user',
15
+ parts: [
16
+ ...(item.functionResponses ?? []).map((response) => ({
17
+ functionResponse: {
18
+ name: response.name,
19
+ response: { name: response.name, content: response.content },
20
+ },
21
+ })),
22
+ ...(item.images ?? []).map((image) => ({
23
+ inlineData: {
24
+ mimeType: image.mediaType,
25
+ data: image.base64url,
26
+ },
27
+ })),
28
+ { text: item.text },
29
+ ],
30
+ };
31
+ return content;
32
+ }
33
+ else {
34
+ assert(item.type === 'assistant');
35
+ const content = {
36
+ role: 'model',
37
+ parts: [
38
+ ...(item.text ? [{ text: item.text }] : []),
39
+ ...item.functionCalls.map((call) => ({
40
+ functionCall: {
41
+ name: call.name,
42
+ args: call.args ?? {},
43
+ },
44
+ })),
45
+ ],
46
+ };
47
+ return content;
48
+ }
49
+ });
50
+ const req = {
51
+ contents: messages,
52
+ tools: [
53
+ {
54
+ functionDeclarations: functionDefs,
55
+ },
56
+ ],
57
+ toolConfig: {
58
+ functionCallingConfig: {
59
+ mode: cheap ? undefined : FunctionCallingMode.ANY,
60
+ ...(!cheap && requiredFunctionName ? { allowedFunctionNames: [requiredFunctionName] } : {}),
61
+ },
62
+ },
63
+ };
64
+ const model = getModel(cheap ? 'gemini-1.5-flash-001' : 'gemini-1.5-pro-001', temperature, prompt.find((item) => item.type === 'systemPrompt').systemPrompt, options.geminiBlockNone);
65
+ const result = await model.generateContent(req, { signal: abortController?.signal });
66
+ // Print token usage
67
+ const usageMetadata = result.response.usageMetadata;
68
+ const usage = {
69
+ inputTokens: usageMetadata.promptTokenCount,
70
+ outputTokens: usageMetadata.candidatesTokenCount,
71
+ totalTokens: usageMetadata.totalTokenCount,
72
+ };
73
+ printTokenUsageAndCost(usage, 0.000125 / 1000, 0.000375 / 1000);
74
+ if (result.response.promptFeedback) {
75
+ console.log('Prompt feedback:');
76
+ console.log(JSON.stringify(result.response.promptFeedback, null, 2));
77
+ }
78
+ if (!result.response.candidates?.length) {
79
+ console.log('Response:', result);
80
+ throw new Error('No candidates found');
81
+ }
82
+ const functionCalls = result.response.candidates
83
+ .map((candidate) => candidate.content.parts?.map((part) => part.functionCall))
84
+ .flat()
85
+ .filter((functionCall) => !!functionCall)
86
+ .map((call) => ({ name: call.name, args: call.args }));
87
+ if (functionCalls.length === 0) {
88
+ const textResponse = result.response.candidates
89
+ .map((candidate) => candidate.content.parts?.map((part) => part.text))
90
+ .flat()
91
+ .filter((text) => !!text)
92
+ .join('\n');
93
+ console.log('No function calls, output text response if it exists:', textResponse);
94
+ }
95
+ return processFunctionCalls(functionCalls);
96
+ }
97
+ function getModel(model, temperature, systemPrompt, geminiBlockNone) {
98
+ assert(process.env.API_KEY, 'API_KEY environment variable is not set');
99
+ const genAI = new GoogleGenerativeAI(process.env.API_KEY);
100
+ return genAI.getGenerativeModel({
101
+ model,
102
+ generationConfig: {
103
+ maxOutputTokens: 8192,
104
+ temperature,
105
+ topP: 0.95,
106
+ },
107
+ safetySettings: [
108
+ {
109
+ category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
110
+ threshold: geminiBlockNone ? HarmBlockThreshold.BLOCK_NONE : HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
111
+ },
112
+ {
113
+ category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
114
+ threshold: geminiBlockNone ? HarmBlockThreshold.BLOCK_NONE : HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
115
+ },
116
+ {
117
+ category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
118
+ threshold: geminiBlockNone ? HarmBlockThreshold.BLOCK_NONE : HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
119
+ },
120
+ {
121
+ category: HarmCategory.HARM_CATEGORY_HARASSMENT,
122
+ threshold: geminiBlockNone ? HarmBlockThreshold.BLOCK_NONE : HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
123
+ },
124
+ ],
125
+ systemInstruction: {
126
+ role: 'system',
127
+ parts: [
128
+ {
129
+ text: systemPrompt,
130
+ },
131
+ ],
132
+ },
133
+ });
134
+ }
135
+ //# sourceMappingURL=ai-studio.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-studio.js","sourceRoot":"","sources":["../../src/ai-service/ai-studio.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,mBAAmB,EAGnB,kBAAkB,EAClB,kBAAkB,EAClB,YAAY,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAA6B,sBAAsB,EAAE,oBAAoB,EAAc,MAAM,aAAa,CAAC;AAElH,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAExE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,MAAoB,EACpB,YAA2B,EAC3B,oBAAmC,EACnC,WAAmB,EACnB,KAAK,GAAG,KAAK,EACb,OAAuB;IAEvB,MAAM,QAAQ,GAAc,MAAM;SAC/B,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,KAAK,WAAW,CAAC;SACnE,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QACZ,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE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CAAC"}
@@ -0,0 +1,6 @@
1
+ import { FunctionCall, PromptItem, FunctionDef } from './common.js';
2
+ import { CodegenOptions } from '../main/codegen-types.js';
3
+ /**
4
+ * This function generates content using the Anthropic Claude model.
5
+ */
6
+ export declare function generateContent(prompt: PromptItem[], functionDefs: FunctionDef[], requiredFunctionName: string | null, temperature: number, cheap: boolean | undefined, options: CodegenOptions): Promise<FunctionCall[]>;
@@ -0,0 +1,135 @@
1
+ import assert from 'node:assert';
2
+ import Anthropic from '@anthropic-ai/sdk';
3
+ import { printTokenUsageAndCost, processFunctionCalls } from './common.js';
4
+ import { abortController } from '../main/interactive/codegen-worker.js';
5
+ /**
6
+ * This function generates content using the Anthropic Claude model.
7
+ */
8
+ export async function generateContent(prompt, functionDefs, requiredFunctionName, temperature, cheap = false, options) {
9
+ const anthropic = new Anthropic({
10
+ defaultHeaders: {
11
+ 'anthropic-beta': 'max-tokens-3-5-sonnet-2024-07-15' + (!options.disableCache ? ',prompt-caching-2024-07-31' : ''),
12
+ },
13
+ });
14
+ const messages = prompt
15
+ .filter((item) => item.type !== 'systemPrompt')
16
+ .map((item) => {
17
+ if (item.type === 'user') {
18
+ const content = [];
19
+ if (item.functionResponses) {
20
+ content.push(...item.functionResponses.map((response) => ({
21
+ tool_use_id: response.call_id ?? response.name,
22
+ content: response.content,
23
+ type: 'tool_result',
24
+ is_error: response.isError === true,
25
+ })));
26
+ }
27
+ if (item.images) {
28
+ content.push(...item.images.map((image) => ({
29
+ type: 'image',
30
+ source: {
31
+ type: 'base64',
32
+ media_type: image.mediaType,
33
+ data: image.base64url,
34
+ },
35
+ })));
36
+ }
37
+ content.push({
38
+ type: 'text',
39
+ text: item.text,
40
+ ...(item.cache && !options.disableCache ? { cache_control: { type: 'ephemeral' } } : {}),
41
+ });
42
+ const message = {
43
+ role: 'user',
44
+ content,
45
+ };
46
+ return message;
47
+ }
48
+ else {
49
+ assert(item.type === 'assistant');
50
+ const message = {
51
+ role: 'assistant',
52
+ content: [
53
+ ...(item.text ? [{ type: 'text', text: item.text }] : []),
54
+ ...item.functionCalls.map((call) => ({
55
+ id: call.id ?? call.name,
56
+ name: call.name,
57
+ input: call.args ?? {},
58
+ type: 'tool_use',
59
+ })),
60
+ ],
61
+ };
62
+ return message;
63
+ }
64
+ });
65
+ const model = cheap ? 'claude-3-haiku-20240307' : 'claude-3-5-sonnet-20240620';
66
+ console.log(`Using Anthropic model: ${model}`);
67
+ let retryCount = 0;
68
+ let response;
69
+ while (retryCount < 3) {
70
+ try {
71
+ response = await anthropic.beta.promptCaching.messages.create({
72
+ model: model,
73
+ system: prompt.find((item) => item.type === 'systemPrompt').systemPrompt,
74
+ messages: messages,
75
+ tools: functionDefs.map((fd) => ({
76
+ name: fd.name,
77
+ description: fd.description,
78
+ input_schema: fd.parameters,
79
+ })),
80
+ tool_choice: requiredFunctionName
81
+ ? { type: 'tool', name: requiredFunctionName }
82
+ : { type: 'any' },
83
+ max_tokens: cheap ? 4096 : 8192,
84
+ temperature: temperature,
85
+ }, {
86
+ signal: abortController?.signal,
87
+ });
88
+ break; // Exit loop if successful
89
+ }
90
+ catch (error) {
91
+ if (error instanceof Anthropic.APIError && error.headers?.['retry-after']) {
92
+ let retryAfter;
93
+ if (error.headers['retry-after'] === '0') {
94
+ retryAfter = (new Date(error.headers['anthropic-ratelimit-tokens-reset']).getTime() - Date.now()) / 1000;
95
+ }
96
+ else {
97
+ retryAfter = Math.max(parseInt(error.headers['retry-after'], 10), 10);
98
+ }
99
+ console.log(`Rate limited. Retrying after ${retryAfter} seconds. Attempt ${retryCount + 1} of 3.`);
100
+ await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000));
101
+ retryCount++;
102
+ }
103
+ else {
104
+ console.error('An error occurred:', error);
105
+ throw error; // Re-throw the error if it's not a rate limit error
106
+ }
107
+ }
108
+ }
109
+ if (retryCount === 3) {
110
+ console.error('Failed to complete request after 3 attempts due to rate limiting.');
111
+ throw new Error('Rate limit exceeded. Operation aborted.');
112
+ }
113
+ // Print token usage for Anthropic
114
+ const usage = {
115
+ cacheCreateTokens: response.usage.cache_creation_input_tokens,
116
+ cacheReadTokens: response.usage.cache_read_input_tokens,
117
+ inputTokens: response.usage.input_tokens,
118
+ outputTokens: response.usage.output_tokens,
119
+ totalTokens: response.usage.input_tokens + response.usage.output_tokens,
120
+ };
121
+ printTokenUsageAndCost(usage, 3 / 1000 / 1000, 15 / 1000 / 1000);
122
+ const responseMessages = response.content.filter((item) => item.type !== 'tool_use');
123
+ if (responseMessages.length > 0) {
124
+ console.log('Response messages', responseMessages);
125
+ }
126
+ const functionCalls = response.content
127
+ .filter((item) => item.type === 'tool_use')
128
+ .map((item) => ({
129
+ id: item.id,
130
+ name: item.name,
131
+ args: item.input,
132
+ }));
133
+ return processFunctionCalls(functionCalls);
134
+ }
135
+ //# sourceMappingURL=anthropic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../src/ai-service/anthropic.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAyC,MAAM,aAAa,CAAC;AASlH,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAExE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,MAAoB,EACpB,YAA2B,EAC3B,oBAAmC,EACnC,WAAmB,EACnB,KAAK,GAAG,KAAK,EACb,OAAuB;IAEvB,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC;QAC9B,cAAc,EAAE;YACd,gBAAgB,EACd,kCAAkC,GAAG,CAAC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,4BAA4B,CAAC,CAAC,CAAC,EAAE,CAAC;SACnG;KACF,CAAC,CAAC;IAEH,MAAM,QAAQ,GAAoC,MAAM;SACrD,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAA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OAAO;SACpC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,UAAU,CAAC;SAC1C,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACd,EAAE,EAAE,IAAI,CAAC,EAAE;QACX,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,IAAI,EAAE,IAAI,CAAC,KAAgC;KAC5C,CAAC,CAAC,CAAC;IAEN,OAAO,oBAAoB,CAAC,aAAa,CAAC,CAAC;AAC7C,CAAC"}
@@ -0,0 +1,5 @@
1
+ import { FunctionCall, PromptItem, FunctionDef } from './common.js';
2
+ /**
3
+ * This function generates content using the OpenAI chat model.
4
+ */
5
+ export declare function generateContent(prompt: PromptItem[], functionDefs: FunctionDef[], requiredFunctionName: string | null, temperature: number, cheap?: boolean): Promise<FunctionCall[]>;
@@ -0,0 +1,132 @@
1
+ import OpenAI, { APIError } from 'openai';
2
+ import assert from 'node:assert';
3
+ import { printTokenUsageAndCost, processFunctionCalls } from './common.js';
4
+ import { abortController } from '../main/interactive/codegen-worker.js';
5
+ /**
6
+ * This function generates content using the OpenAI chat model.
7
+ */
8
+ export async function generateContent(prompt, functionDefs, requiredFunctionName, temperature, cheap = false) {
9
+ const openai = new OpenAI();
10
+ const messages = prompt
11
+ .map((item) => {
12
+ if (item.type === 'systemPrompt') {
13
+ return {
14
+ role: 'system',
15
+ content: item.systemPrompt,
16
+ };
17
+ }
18
+ else if (item.type === 'user') {
19
+ const messages = [];
20
+ if (item.functionResponses) {
21
+ messages.push(...item.functionResponses.map((response) => ({
22
+ role: 'tool',
23
+ name: response.name,
24
+ content: response.content ?? '',
25
+ tool_call_id: response.name,
26
+ })));
27
+ }
28
+ if ((item.images?.length ?? 0) > 0) {
29
+ messages.push({
30
+ role: 'user',
31
+ content: [
32
+ ...item.images.map((image) => ({
33
+ type: 'image_url',
34
+ image_url: {
35
+ url: 'data:' + image.mediaType + ';base64,' + image.base64url,
36
+ },
37
+ })),
38
+ {
39
+ type: 'text',
40
+ text: item.text,
41
+ },
42
+ ],
43
+ });
44
+ }
45
+ else {
46
+ messages.push({
47
+ role: 'user',
48
+ content: item.text,
49
+ });
50
+ }
51
+ return messages;
52
+ }
53
+ else {
54
+ assert(item.type === 'assistant');
55
+ const message = {
56
+ role: 'assistant',
57
+ ...(item.text ? { content: item.text } : {}),
58
+ tool_calls: item.functionCalls?.map((call) => ({
59
+ type: 'function',
60
+ function: { name: call.name, arguments: JSON.stringify(call.args ?? {}) },
61
+ id: call.name,
62
+ })),
63
+ };
64
+ return message;
65
+ }
66
+ })
67
+ .flat();
68
+ const model = cheap ? 'gpt-4o-mini' : 'gpt-4o-2024-08-06';
69
+ console.log(`Using OpenAI model: ${model}`);
70
+ let retryCount = 0;
71
+ let response = undefined;
72
+ while (retryCount < 3) {
73
+ try {
74
+ response = await openai.chat.completions.create({
75
+ model: model,
76
+ messages,
77
+ tools: functionDefs.map((funDef) => ({ type: 'function', function: funDef })),
78
+ tool_choice: requiredFunctionName
79
+ ? { type: 'function', function: { name: requiredFunctionName } }
80
+ : 'required',
81
+ temperature: temperature,
82
+ }, { signal: abortController?.signal });
83
+ break; // Exit loop if successful
84
+ }
85
+ catch (error) {
86
+ if (error instanceof APIError && error.headers?.['x-ratelimit-limit-tokens']) {
87
+ const rateLimitTokens = parseInt(error.headers['x-ratelimit-limit-tokens'], 10);
88
+ const retryAfter = error.headers['retry-after'] ? parseInt(error.headers['retry-after'], 10) : 1;
89
+ console.log(`Rate limited. Token limit: ${rateLimitTokens}. Retrying after ${retryAfter} seconds. Attempt ${retryCount + 1} of 3.`);
90
+ await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000));
91
+ retryCount++;
92
+ }
93
+ else {
94
+ console.error('An error occurred:', error);
95
+ throw error; // Re-throw the error if it's not a rate limit error
96
+ }
97
+ }
98
+ }
99
+ if (retryCount === 3) {
100
+ console.error('Failed to complete request after 3 attempts due to rate limiting.');
101
+ throw new Error('Rate limit exceeded. Operation aborted.');
102
+ }
103
+ assert(response);
104
+ // Print token usage for chat gpt
105
+ const usage = {
106
+ inputTokens: response.usage.prompt_tokens,
107
+ outputTokens: response.usage.completion_tokens,
108
+ totalTokens: response.usage.total_tokens,
109
+ };
110
+ printTokenUsageAndCost(usage, 0.000005, 0.000015);
111
+ const responseMessage = response.choices[0].message;
112
+ if (responseMessage.content) {
113
+ console.log('Message', responseMessage.content);
114
+ }
115
+ const toolCalls = responseMessage.tool_calls;
116
+ if (toolCalls) {
117
+ const functionCalls = toolCalls.map((call) => {
118
+ const name = call.function.name;
119
+ const args = JSON.parse(call.function.arguments);
120
+ return {
121
+ id: call.id,
122
+ name,
123
+ args,
124
+ };
125
+ });
126
+ return processFunctionCalls(functionCalls);
127
+ }
128
+ else {
129
+ throw new Error('No tool calls found in response');
130
+ }
131
+ }
132
+ //# sourceMappingURL=chat-gpt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat-gpt.js","sourceRoot":"","sources":["../../src/ai-service/chat-gpt.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,EAAE,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC1C,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAyC,MAAM,aAAa,CAAC;AAElH,OAAO,EAAE,eAAe,EAAE,MAAM,uCAAuC,CAAC;AAExE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,MAAoB,EACpB,YAA2B,EAC3B,oBAAmC,EACnC,WAAmB,EACnB,KAAK,GAAG,KAAK;IAEb,MAAM,MAAM,GAAG,IAAI,MAAM,EAAE,CAAC;IAE5B,MAAM,QAAQ,GAAsC,MAAM;SACvD,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QACZ,IAAI,IAAI,CAAC,IAAI,KAAK,cAAc,EAAE,CAAC;YACjC,OAAO;gBACL,IAAI,EAAE,QAAiB;gBACvB,OAAO,EAAE,IAAI,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,KAAK,GAAG;QACZ,WAAW,EAAE,QAAQ,CAAC,KAAM,CAAC,aAAa;QAC1C,YAAY,EAAE,QAAQ,CAAC,KAAM,CAAC,iBAAiB;QAC/C,WAAW,EAAE,QAAQ,CAAC,KAAM,CAAC,YAAY;KAC1C,CAAC;IACF,sBAAsB,CAAC,KAAK,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAElD,MAAM,eAAe,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;IAEpD,IAAI,eAAe,CAAC,OAAO,EAAE,CAAC;QAC5B,OAAO,CAAC,GAAG,CAAC,SAAS,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC;IAClD,CAAC;IAED,MAAM,SAAS,GAAG,eAAe,CAAC,UAAU,CAAC;IAC7C,IAAI,SAAS,EAAE,CAAC;QACd,MAAM,aAAa,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;YAC3C,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;YAChC,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;YAEjD,OAAO;gBACL,EAAE,EAAE,IAAI,CAAC,EAAE;gBACX,IAAI;gBACJ,IAAI;aACL,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,OAAO,oBAAoB,CAAC,aAAa,CAAC,CAAC;IAC7C,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;IACrD,CAAC;AACH,CAAC"}
@@ -0,0 +1,58 @@
1
+ import { CodegenOptions } from '../main/codegen-types.js';
2
+ interface TokenUsage {
3
+ inputTokens: number | undefined | null;
4
+ outputTokens: number | undefined | null;
5
+ totalTokens: number | undefined | null;
6
+ cacheCreateTokens?: number | null;
7
+ cacheReadTokens?: number | null;
8
+ }
9
+ export interface FunctionDef {
10
+ name: string;
11
+ description: string;
12
+ parameters: {
13
+ type: 'object';
14
+ properties: Record<string, unknown>;
15
+ required: string[];
16
+ };
17
+ }
18
+ export interface FunctionCall<T = Record<string, unknown>> {
19
+ id?: string;
20
+ name: string;
21
+ args?: T;
22
+ }
23
+ export interface PromptItem {
24
+ type: string;
25
+ systemPrompt?: string;
26
+ text?: string;
27
+ functionResponses?: {
28
+ call_id?: string;
29
+ name: string;
30
+ content?: string;
31
+ isError?: boolean;
32
+ }[];
33
+ images?: {
34
+ mediaType: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';
35
+ base64url: string;
36
+ }[];
37
+ functionCalls?: FunctionCall[];
38
+ cache?: boolean;
39
+ }
40
+ export type GenerateContentFunction = (prompt: PromptItem[], functionDefs: FunctionDef[], requiredFunctionName: string, temperature: number, cheap: boolean, options: CodegenOptions) => Promise<FunctionCall[]>;
41
+ export type GenerateImageFunction = (prompt: string, contextImagePath: string | undefined, size: {
42
+ width: number;
43
+ height: number;
44
+ }, cheap: boolean) => Promise<string>;
45
+ /**
46
+ * Common function to print token usage and estimated cost
47
+ * @param {TokenUsage} usage Token usage object
48
+ * @param {number} inputCostPerToken Cost per input token
49
+ * @param {number} outputCostPerToken Cost per output token
50
+ */
51
+ export declare function printTokenUsageAndCost(usage: TokenUsage, inputCostPerToken: number, outputCostPerToken: number): void;
52
+ /**
53
+ * Common function to process function calls and explanations
54
+ * @param {FunctionCall[]} functionCalls Array of function calls
55
+ * @returns {FunctionCall[]} Processed function calls
56
+ */
57
+ export declare function processFunctionCalls(functionCalls: FunctionCall[]): FunctionCall[];
58
+ export {};
@@ -0,0 +1,38 @@
1
+ import assert from 'node:assert';
2
+ import { functionDefs } from '../prompt/function-calling.js';
3
+ /**
4
+ * Common function to print token usage and estimated cost
5
+ * @param {TokenUsage} usage Token usage object
6
+ * @param {number} inputCostPerToken Cost per input token
7
+ * @param {number} outputCostPerToken Cost per output token
8
+ */
9
+ export function printTokenUsageAndCost(usage, inputCostPerToken, outputCostPerToken) {
10
+ console.log('Token Usage:');
11
+ console.log(' - Input tokens: ', usage.inputTokens);
12
+ console.log(' - Output tokens: ', usage.outputTokens);
13
+ console.log(' - Total tokens: ', usage.totalTokens);
14
+ if (usage.cacheCreateTokens) {
15
+ console.log(' - Cache create tokens: ', usage.cacheCreateTokens);
16
+ }
17
+ if (usage.cacheReadTokens) {
18
+ console.log(' - Cache read tokens: ', usage.cacheReadTokens);
19
+ }
20
+ const inputCost = (usage.inputTokens ?? 0) * inputCostPerToken +
21
+ (usage.cacheCreateTokens ?? 0) * inputCostPerToken * 1.25 +
22
+ (usage.cacheReadTokens ?? 0) * inputCostPerToken * 0.2;
23
+ const outputCost = (usage.outputTokens ?? 0) * outputCostPerToken;
24
+ const totalCost = inputCost + outputCost;
25
+ console.log(' - Estimated cost: ', totalCost.toFixed(6), ' USD');
26
+ }
27
+ /**
28
+ * Common function to process function calls and explanations
29
+ * @param {FunctionCall[]} functionCalls Array of function calls
30
+ * @returns {FunctionCall[]} Processed function calls
31
+ */
32
+ export function processFunctionCalls(functionCalls) {
33
+ const unknownFunctionCalls = functionCalls.filter((call) => !functionDefs.some((fd) => fd.name === call.name));
34
+ assert(unknownFunctionCalls.length === 0, 'Unknown function name: ' + unknownFunctionCalls.map((call) => call.name).join(', '));
35
+ console.log('Explanations:', functionCalls.filter((fn) => fn.name === 'explanation').map((call) => call.args?.text));
36
+ return functionCalls; // .filter((fn) => fn.name !== 'explanation');
37
+ }
38
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/ai-service/common.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AA6D7D;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,KAAiB,EAAE,iBAAyB,EAAE,kBAA0B;IAC7G,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC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