@warlock.js/core 4.8.0 → 4.8.1

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 (769) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/esm/connectors/ai-connector.mjs +1 -1
  3. package/package.json +12 -9
  4. package/esm/ai/src/agent/agent-input-builder.mjs +0 -133
  5. package/esm/ai/src/agent/agent-input-builder.mjs.map +0 -1
  6. package/esm/ai/src/agent/agent-log-event.mjs +0 -101
  7. package/esm/ai/src/agent/agent-log-event.mjs.map +0 -1
  8. package/esm/ai/src/agent/agent-stream.mjs +0 -82
  9. package/esm/ai/src/agent/agent-stream.mjs.map +0 -1
  10. package/esm/ai/src/agent/agent-to-stream-event.mjs +0 -86
  11. package/esm/ai/src/agent/agent-to-stream-event.mjs.map +0 -1
  12. package/esm/ai/src/agent/agent.mjs +0 -1276
  13. package/esm/ai/src/agent/agent.mjs.map +0 -1
  14. package/esm/ai/src/agent/index.mjs +0 -5
  15. package/esm/ai/src/agent/json-stream-guard.mjs +0 -400
  16. package/esm/ai/src/agent/json-stream-guard.mjs.map +0 -1
  17. package/esm/ai/src/agent/signature.mjs +0 -57
  18. package/esm/ai/src/agent/signature.mjs.map +0 -1
  19. package/esm/ai/src/agent/snapshot.mjs +0 -101
  20. package/esm/ai/src/agent/snapshot.mjs.map +0 -1
  21. package/esm/ai/src/agent/spawn-sub-agent.mjs +0 -68
  22. package/esm/ai/src/agent/spawn-sub-agent.mjs.map +0 -1
  23. package/esm/ai/src/ai.mjs +0 -191
  24. package/esm/ai/src/ai.mjs.map +0 -1
  25. package/esm/ai/src/batch/batch.mjs +0 -198
  26. package/esm/ai/src/batch/batch.mjs.map +0 -1
  27. package/esm/ai/src/batch/index.mjs +0 -3
  28. package/esm/ai/src/batch/run-batch-item.mjs +0 -100
  29. package/esm/ai/src/batch/run-batch-item.mjs.map +0 -1
  30. package/esm/ai/src/batch/run-with-concurrency.mjs +0 -39
  31. package/esm/ai/src/batch/run-with-concurrency.mjs.map +0 -1
  32. package/esm/ai/src/checkpoint/memory.mjs +0 -0
  33. package/esm/ai/src/checkpoint/memory.mjs.map +0 -1
  34. package/esm/ai/src/checkpoint/pg.mjs +0 -265
  35. package/esm/ai/src/checkpoint/pg.mjs.map +0 -1
  36. package/esm/ai/src/checkpoint/redis.mjs +0 -200
  37. package/esm/ai/src/checkpoint/redis.mjs.map +0 -1
  38. package/esm/ai/src/config.mjs +0 -59
  39. package/esm/ai/src/config.mjs.map +0 -1
  40. package/esm/ai/src/contracts/end.type.mjs +0 -47
  41. package/esm/ai/src/contracts/end.type.mjs.map +0 -1
  42. package/esm/ai/src/errors/agent-cancelled-error.mjs +0 -43
  43. package/esm/ai/src/errors/agent-cancelled-error.mjs.map +0 -1
  44. package/esm/ai/src/errors/agent-drift-error.mjs +0 -31
  45. package/esm/ai/src/errors/agent-drift-error.mjs.map +0 -1
  46. package/esm/ai/src/errors/agent-execution-error.mjs +0 -35
  47. package/esm/ai/src/errors/agent-execution-error.mjs.map +0 -1
  48. package/esm/ai/src/errors/agent-max-trips-error.mjs +0 -41
  49. package/esm/ai/src/errors/agent-max-trips-error.mjs.map +0 -1
  50. package/esm/ai/src/errors/ai-error.mjs +0 -68
  51. package/esm/ai/src/errors/ai-error.mjs.map +0 -1
  52. package/esm/ai/src/errors/budget-exceeded-error.mjs +0 -31
  53. package/esm/ai/src/errors/budget-exceeded-error.mjs.map +0 -1
  54. package/esm/ai/src/errors/content-filter-error.mjs +0 -28
  55. package/esm/ai/src/errors/content-filter-error.mjs.map +0 -1
  56. package/esm/ai/src/errors/context-length-exceeded-error.mjs +0 -31
  57. package/esm/ai/src/errors/context-length-exceeded-error.mjs.map +0 -1
  58. package/esm/ai/src/errors/guardrail-violation-error.mjs +0 -41
  59. package/esm/ai/src/errors/guardrail-violation-error.mjs.map +0 -1
  60. package/esm/ai/src/errors/index.mjs +0 -40
  61. package/esm/ai/src/errors/invalid-request-error.mjs +0 -31
  62. package/esm/ai/src/errors/invalid-request-error.mjs.map +0 -1
  63. package/esm/ai/src/errors/max-iterations-error.mjs +0 -32
  64. package/esm/ai/src/errors/max-iterations-error.mjs.map +0 -1
  65. package/esm/ai/src/errors/max-steps-exceeded-error.mjs +0 -21
  66. package/esm/ai/src/errors/max-steps-exceeded-error.mjs.map +0 -1
  67. package/esm/ai/src/errors/orchestrator-cancelled-error.mjs +0 -31
  68. package/esm/ai/src/errors/orchestrator-cancelled-error.mjs.map +0 -1
  69. package/esm/ai/src/errors/orchestrator-config-error.mjs +0 -30
  70. package/esm/ai/src/errors/orchestrator-config-error.mjs.map +0 -1
  71. package/esm/ai/src/errors/orchestrator-drift-error.mjs +0 -37
  72. package/esm/ai/src/errors/orchestrator-drift-error.mjs.map +0 -1
  73. package/esm/ai/src/errors/orchestrator-failed-error.mjs +0 -36
  74. package/esm/ai/src/errors/orchestrator-failed-error.mjs.map +0 -1
  75. package/esm/ai/src/errors/outbound-policy-error.mjs +0 -32
  76. package/esm/ai/src/errors/outbound-policy-error.mjs.map +0 -1
  77. package/esm/ai/src/errors/planner-cancelled-error.mjs +0 -29
  78. package/esm/ai/src/errors/planner-cancelled-error.mjs.map +0 -1
  79. package/esm/ai/src/errors/planner-drift-error.mjs +0 -33
  80. package/esm/ai/src/errors/planner-drift-error.mjs.map +0 -1
  81. package/esm/ai/src/errors/planner-failed-error.mjs +0 -37
  82. package/esm/ai/src/errors/planner-failed-error.mjs.map +0 -1
  83. package/esm/ai/src/errors/planner-plan-invalid-error.mjs +0 -25
  84. package/esm/ai/src/errors/planner-plan-invalid-error.mjs.map +0 -1
  85. package/esm/ai/src/errors/prompt-refinement-error.mjs +0 -27
  86. package/esm/ai/src/errors/prompt-refinement-error.mjs.map +0 -1
  87. package/esm/ai/src/errors/provider-auth-error.mjs +0 -26
  88. package/esm/ai/src/errors/provider-auth-error.mjs.map +0 -1
  89. package/esm/ai/src/errors/provider-error.mjs +0 -42
  90. package/esm/ai/src/errors/provider-error.mjs.map +0 -1
  91. package/esm/ai/src/errors/provider-rate-limit-error.mjs +0 -31
  92. package/esm/ai/src/errors/provider-rate-limit-error.mjs.map +0 -1
  93. package/esm/ai/src/errors/provider-timeout-error.mjs +0 -26
  94. package/esm/ai/src/errors/provider-timeout-error.mjs.map +0 -1
  95. package/esm/ai/src/errors/quota-exceeded-error.mjs +0 -40
  96. package/esm/ai/src/errors/quota-exceeded-error.mjs.map +0 -1
  97. package/esm/ai/src/errors/routing-error.mjs +0 -23
  98. package/esm/ai/src/errors/routing-error.mjs.map +0 -1
  99. package/esm/ai/src/errors/schema-validation-error.mjs +0 -37
  100. package/esm/ai/src/errors/schema-validation-error.mjs.map +0 -1
  101. package/esm/ai/src/errors/step-failed-error.mjs +0 -19
  102. package/esm/ai/src/errors/step-failed-error.mjs.map +0 -1
  103. package/esm/ai/src/errors/supervisor-cancelled-error.mjs +0 -29
  104. package/esm/ai/src/errors/supervisor-cancelled-error.mjs.map +0 -1
  105. package/esm/ai/src/errors/supervisor-drift-error.mjs +0 -30
  106. package/esm/ai/src/errors/supervisor-drift-error.mjs.map +0 -1
  107. package/esm/ai/src/errors/supervisor-failed-error.mjs +0 -43
  108. package/esm/ai/src/errors/supervisor-failed-error.mjs.map +0 -1
  109. package/esm/ai/src/errors/supervisor-routing-error.mjs +0 -39
  110. package/esm/ai/src/errors/supervisor-routing-error.mjs.map +0 -1
  111. package/esm/ai/src/errors/tool-execution-error.mjs +0 -32
  112. package/esm/ai/src/errors/tool-execution-error.mjs.map +0 -1
  113. package/esm/ai/src/errors/workflow-cancelled-error.mjs +0 -23
  114. package/esm/ai/src/errors/workflow-cancelled-error.mjs.map +0 -1
  115. package/esm/ai/src/errors/workflow-drift-error.mjs +0 -24
  116. package/esm/ai/src/errors/workflow-drift-error.mjs.map +0 -1
  117. package/esm/ai/src/errors/workflow-error.mjs +0 -18
  118. package/esm/ai/src/errors/workflow-error.mjs.map +0 -1
  119. package/esm/ai/src/eval/dataset.mjs +0 -112
  120. package/esm/ai/src/eval/dataset.mjs.map +0 -1
  121. package/esm/ai/src/eval/eval-runner.mjs +0 -135
  122. package/esm/ai/src/eval/eval-runner.mjs.map +0 -1
  123. package/esm/ai/src/eval/index.mjs +0 -48
  124. package/esm/ai/src/eval/index.mjs.map +0 -1
  125. package/esm/ai/src/eval/judge-scorer.mjs +0 -87
  126. package/esm/ai/src/eval/judge-scorer.mjs.map +0 -1
  127. package/esm/ai/src/eval/regression.mjs +0 -51
  128. package/esm/ai/src/eval/regression.mjs.map +0 -1
  129. package/esm/ai/src/eval/report-json.mjs +0 -33
  130. package/esm/ai/src/eval/report-json.mjs.map +0 -1
  131. package/esm/ai/src/eval/report-junit.mjs +0 -60
  132. package/esm/ai/src/eval/report-junit.mjs.map +0 -1
  133. package/esm/ai/src/eval/scorers.mjs +0 -101
  134. package/esm/ai/src/eval/scorers.mjs.map +0 -1
  135. package/esm/ai/src/guard/detectors/index.mjs +0 -6
  136. package/esm/ai/src/guard/detectors/injection.mjs +0 -254
  137. package/esm/ai/src/guard/detectors/injection.mjs.map +0 -1
  138. package/esm/ai/src/guard/detectors/moderation.mjs +0 -134
  139. package/esm/ai/src/guard/detectors/moderation.mjs.map +0 -1
  140. package/esm/ai/src/guard/detectors/pii.mjs +0 -199
  141. package/esm/ai/src/guard/detectors/pii.mjs.map +0 -1
  142. package/esm/ai/src/guard/detectors/topic.mjs +0 -99
  143. package/esm/ai/src/guard/detectors/topic.mjs.map +0 -1
  144. package/esm/ai/src/guard/errors.mjs +0 -18
  145. package/esm/ai/src/guard/errors.mjs.map +0 -1
  146. package/esm/ai/src/guard/guard.mjs +0 -209
  147. package/esm/ai/src/guard/guard.mjs.map +0 -1
  148. package/esm/ai/src/guard/guardrail.mjs +0 -22
  149. package/esm/ai/src/guard/guardrail.mjs.map +0 -1
  150. package/esm/ai/src/human/errors.mjs +0 -60
  151. package/esm/ai/src/human/errors.mjs.map +0 -1
  152. package/esm/ai/src/human/human-approval.mjs +0 -170
  153. package/esm/ai/src/human/human-approval.mjs.map +0 -1
  154. package/esm/ai/src/human/policy.mjs +0 -67
  155. package/esm/ai/src/human/policy.mjs.map +0 -1
  156. package/esm/ai/src/human/register.mjs +0 -37
  157. package/esm/ai/src/human/register.mjs.map +0 -1
  158. package/esm/ai/src/human/resume-seed.mjs +0 -53
  159. package/esm/ai/src/human/resume-seed.mjs.map +0 -1
  160. package/esm/ai/src/human/resume.mjs +0 -121
  161. package/esm/ai/src/human/resume.mjs.map +0 -1
  162. package/esm/ai/src/human/stores/index.mjs +0 -5
  163. package/esm/ai/src/human/stores/memory.mjs +0 -91
  164. package/esm/ai/src/human/stores/memory.mjs.map +0 -1
  165. package/esm/ai/src/human/stores/pg.mjs +0 -220
  166. package/esm/ai/src/human/stores/pg.mjs.map +0 -1
  167. package/esm/ai/src/human/stores/redis.mjs +0 -201
  168. package/esm/ai/src/human/stores/redis.mjs.map +0 -1
  169. package/esm/ai/src/image/image-cost.mjs +0 -55
  170. package/esm/ai/src/image/image-cost.mjs.map +0 -1
  171. package/esm/ai/src/image/image.mjs +0 -112
  172. package/esm/ai/src/image/image.mjs.map +0 -1
  173. package/esm/ai/src/image/index.mjs +0 -4
  174. package/esm/ai/src/index.mjs +0 -196
  175. package/esm/ai/src/memory/derive-id.mjs +0 -24
  176. package/esm/ai/src/memory/derive-id.mjs.map +0 -1
  177. package/esm/ai/src/memory/episodic-memory.mjs +0 -106
  178. package/esm/ai/src/memory/episodic-memory.mjs.map +0 -1
  179. package/esm/ai/src/memory/memory.mjs +0 -166
  180. package/esm/ai/src/memory/memory.mjs.map +0 -1
  181. package/esm/ai/src/memory/procedural-memory.mjs +0 -103
  182. package/esm/ai/src/memory/procedural-memory.mjs.map +0 -1
  183. package/esm/ai/src/memory/semantic-memory.mjs +0 -80
  184. package/esm/ai/src/memory/semantic-memory.mjs.map +0 -1
  185. package/esm/ai/src/memory/working-memory.mjs +0 -62
  186. package/esm/ai/src/memory/working-memory.mjs.map +0 -1
  187. package/esm/ai/src/middleware/builtins/budget.mjs +0 -219
  188. package/esm/ai/src/middleware/builtins/budget.mjs.map +0 -1
  189. package/esm/ai/src/middleware/builtins/guardrail.mjs +0 -76
  190. package/esm/ai/src/middleware/builtins/guardrail.mjs.map +0 -1
  191. package/esm/ai/src/middleware/builtins/semantic-cache.mjs +0 -149
  192. package/esm/ai/src/middleware/builtins/semantic-cache.mjs.map +0 -1
  193. package/esm/ai/src/middleware/helpers/compose.mjs +0 -52
  194. package/esm/ai/src/middleware/helpers/compose.mjs.map +0 -1
  195. package/esm/ai/src/middleware/helpers/for-tool.mjs +0 -80
  196. package/esm/ai/src/middleware/helpers/for-tool.mjs.map +0 -1
  197. package/esm/ai/src/middleware/index.mjs +0 -10
  198. package/esm/ai/src/middleware/pipeline.mjs +0 -100
  199. package/esm/ai/src/middleware/pipeline.mjs.map +0 -1
  200. package/esm/ai/src/middleware/utils/extract-user-text.mjs +0 -47
  201. package/esm/ai/src/middleware/utils/extract-user-text.mjs.map +0 -1
  202. package/esm/ai/src/middleware/utils/namespaced-state.mjs +0 -60
  203. package/esm/ai/src/middleware/utils/namespaced-state.mjs.map +0 -1
  204. package/esm/ai/src/mock/index.mjs +0 -4
  205. package/esm/ai/src/mock/mock-agent.mjs +0 -3
  206. package/esm/ai/src/mock/mock-router.mjs +0 -58
  207. package/esm/ai/src/mock/mock-router.mjs.map +0 -1
  208. package/esm/ai/src/model/fallback-model.mjs +0 -218
  209. package/esm/ai/src/model/fallback-model.mjs.map +0 -1
  210. package/esm/ai/src/model/index.mjs +0 -3
  211. package/esm/ai/src/object-stream/index.mjs +0 -4
  212. package/esm/ai/src/object-stream/parse-partial-json.mjs +0 -78
  213. package/esm/ai/src/object-stream/parse-partial-json.mjs.map +0 -1
  214. package/esm/ai/src/object-stream/stream-object.mjs +0 -97
  215. package/esm/ai/src/object-stream/stream-object.mjs.map +0 -1
  216. package/esm/ai/src/observe/index.mjs +0 -4
  217. package/esm/ai/src/observe/observer-registry.mjs +0 -35
  218. package/esm/ai/src/observe/observer-registry.mjs.map +0 -1
  219. package/esm/ai/src/observe/resolve-observers.mjs +0 -73
  220. package/esm/ai/src/observe/resolve-observers.mjs.map +0 -1
  221. package/esm/ai/src/orchestrator/as-tool.mjs +0 -98
  222. package/esm/ai/src/orchestrator/as-tool.mjs.map +0 -1
  223. package/esm/ai/src/orchestrator/checkpoint.mjs +0 -75
  224. package/esm/ai/src/orchestrator/checkpoint.mjs.map +0 -1
  225. package/esm/ai/src/orchestrator/commands.mjs +0 -34
  226. package/esm/ai/src/orchestrator/commands.mjs.map +0 -1
  227. package/esm/ai/src/orchestrator/compaction.mjs +0 -206
  228. package/esm/ai/src/orchestrator/compaction.mjs.map +0 -1
  229. package/esm/ai/src/orchestrator/dispatch.mjs +0 -171
  230. package/esm/ai/src/orchestrator/dispatch.mjs.map +0 -1
  231. package/esm/ai/src/orchestrator/emitter.mjs +0 -85
  232. package/esm/ai/src/orchestrator/emitter.mjs.map +0 -1
  233. package/esm/ai/src/orchestrator/execution.mjs +0 -395
  234. package/esm/ai/src/orchestrator/execution.mjs.map +0 -1
  235. package/esm/ai/src/orchestrator/index.mjs +0 -11
  236. package/esm/ai/src/orchestrator/load.mjs +0 -49
  237. package/esm/ai/src/orchestrator/load.mjs.map +0 -1
  238. package/esm/ai/src/orchestrator/lock.mjs +0 -75
  239. package/esm/ai/src/orchestrator/lock.mjs.map +0 -1
  240. package/esm/ai/src/orchestrator/memory.mjs +0 -141
  241. package/esm/ai/src/orchestrator/memory.mjs.map +0 -1
  242. package/esm/ai/src/orchestrator/orchestrator-stream.mjs +0 -98
  243. package/esm/ai/src/orchestrator/orchestrator-stream.mjs.map +0 -1
  244. package/esm/ai/src/orchestrator/orchestrator.mjs +0 -206
  245. package/esm/ai/src/orchestrator/orchestrator.mjs.map +0 -1
  246. package/esm/ai/src/orchestrator/resume.mjs +0 -74
  247. package/esm/ai/src/orchestrator/resume.mjs.map +0 -1
  248. package/esm/ai/src/orchestrator/session-lock.mjs +0 -83
  249. package/esm/ai/src/orchestrator/session-lock.mjs.map +0 -1
  250. package/esm/ai/src/orchestrator/signature.mjs +0 -120
  251. package/esm/ai/src/orchestrator/signature.mjs.map +0 -1
  252. package/esm/ai/src/orchestrator/window.mjs +0 -56
  253. package/esm/ai/src/orchestrator/window.mjs.map +0 -1
  254. package/esm/ai/src/planner/dag-scheduler.mjs +0 -97
  255. package/esm/ai/src/planner/dag-scheduler.mjs.map +0 -1
  256. package/esm/ai/src/planner/index.mjs +0 -6
  257. package/esm/ai/src/planner/plan-prompt.mjs +0 -31
  258. package/esm/ai/src/planner/plan-prompt.mjs.map +0 -1
  259. package/esm/ai/src/planner/plan-schema.mjs +0 -120
  260. package/esm/ai/src/planner/plan-schema.mjs.map +0 -1
  261. package/esm/ai/src/planner/planner-run.mjs +0 -769
  262. package/esm/ai/src/planner/planner-run.mjs.map +0 -1
  263. package/esm/ai/src/planner/planner.mjs +0 -144
  264. package/esm/ai/src/planner/planner.mjs.map +0 -1
  265. package/esm/ai/src/planner/signature.mjs +0 -27
  266. package/esm/ai/src/planner/signature.mjs.map +0 -1
  267. package/esm/ai/src/planner/snapshot.mjs +0 -95
  268. package/esm/ai/src/planner/snapshot.mjs.map +0 -1
  269. package/esm/ai/src/prompt/errors.mjs +0 -73
  270. package/esm/ai/src/prompt/errors.mjs.map +0 -1
  271. package/esm/ai/src/prompt/index.mjs +0 -4
  272. package/esm/ai/src/prompt/prompt-langfuse-sync.mjs +0 -104
  273. package/esm/ai/src/prompt/prompt-langfuse-sync.mjs.map +0 -1
  274. package/esm/ai/src/prompt/prompt-validate.mjs +0 -170
  275. package/esm/ai/src/prompt/prompt-validate.mjs.map +0 -1
  276. package/esm/ai/src/prompt/prompt.mjs +0 -218
  277. package/esm/ai/src/prompt/prompt.mjs.map +0 -1
  278. package/esm/ai/src/prompts/index.mjs +0 -3
  279. package/esm/ai/src/prompts/prompts-manager.mjs +0 -410
  280. package/esm/ai/src/prompts/prompts-manager.mjs.map +0 -1
  281. package/esm/ai/src/prompts/prompts-validate.mjs +0 -0
  282. package/esm/ai/src/prompts/prompts-validate.mjs.map +0 -1
  283. package/esm/ai/src/rag/as-tool.mjs +0 -48
  284. package/esm/ai/src/rag/as-tool.mjs.map +0 -1
  285. package/esm/ai/src/rag/chunk/chunk.mjs +0 -44
  286. package/esm/ai/src/rag/chunk/chunk.mjs.map +0 -1
  287. package/esm/ai/src/rag/chunk/fixed.mjs +0 -32
  288. package/esm/ai/src/rag/chunk/fixed.mjs.map +0 -1
  289. package/esm/ai/src/rag/chunk/markdown.mjs +0 -75
  290. package/esm/ai/src/rag/chunk/markdown.mjs.map +0 -1
  291. package/esm/ai/src/rag/chunk/recursive.mjs +0 -132
  292. package/esm/ai/src/rag/chunk/recursive.mjs.map +0 -1
  293. package/esm/ai/src/rag/chunk/sentence.mjs +0 -73
  294. package/esm/ai/src/rag/chunk/sentence.mjs.map +0 -1
  295. package/esm/ai/src/rag/hybrid/bm25.mjs +0 -51
  296. package/esm/ai/src/rag/hybrid/bm25.mjs.map +0 -1
  297. package/esm/ai/src/rag/hybrid/hybrid-rank.mjs +0 -29
  298. package/esm/ai/src/rag/hybrid/hybrid-rank.mjs.map +0 -1
  299. package/esm/ai/src/rag/hybrid/rrf.mjs +0 -30
  300. package/esm/ai/src/rag/hybrid/rrf.mjs.map +0 -1
  301. package/esm/ai/src/rag/index.mjs +0 -18
  302. package/esm/ai/src/rag/loaders/errors.mjs +0 -25
  303. package/esm/ai/src/rag/loaders/errors.mjs.map +0 -1
  304. package/esm/ai/src/rag/loaders/index.mjs +0 -7
  305. package/esm/ai/src/rag/loaders/load-html.mjs +0 -138
  306. package/esm/ai/src/rag/loaders/load-html.mjs.map +0 -1
  307. package/esm/ai/src/rag/loaders/load-pdf.mjs +0 -150
  308. package/esm/ai/src/rag/loaders/load-pdf.mjs.map +0 -1
  309. package/esm/ai/src/rag/loaders/load-text.mjs +0 -60
  310. package/esm/ai/src/rag/loaders/load-text.mjs.map +0 -1
  311. package/esm/ai/src/rag/loaders/load-web.mjs +0 -89
  312. package/esm/ai/src/rag/loaders/load-web.mjs.map +0 -1
  313. package/esm/ai/src/rag/rag.mjs +0 -126
  314. package/esm/ai/src/rag/rag.mjs.map +0 -1
  315. package/esm/ai/src/rag/rerank/keyword-reranker.mjs +0 -58
  316. package/esm/ai/src/rag/rerank/keyword-reranker.mjs.map +0 -1
  317. package/esm/ai/src/rag/rerank/llm-reranker.mjs +0 -85
  318. package/esm/ai/src/rag/rerank/llm-reranker.mjs.map +0 -1
  319. package/esm/ai/src/rag/retrieve.mjs +0 -68
  320. package/esm/ai/src/rag/retrieve.mjs.map +0 -1
  321. package/esm/ai/src/rag/store/cache-vector-store.mjs +0 -48
  322. package/esm/ai/src/rag/store/cache-vector-store.mjs.map +0 -1
  323. package/esm/ai/src/rag/store/pg-vector-store.mjs +0 -328
  324. package/esm/ai/src/rag/store/pg-vector-store.mjs.map +0 -1
  325. package/esm/ai/src/rag/transforms/multi-query.mjs +0 -41
  326. package/esm/ai/src/rag/transforms/multi-query.mjs.map +0 -1
  327. package/esm/ai/src/security/index.mjs +0 -5
  328. package/esm/ai/src/security/outbound-policy.mjs +0 -187
  329. package/esm/ai/src/security/outbound-policy.mjs.map +0 -1
  330. package/esm/ai/src/security/private-ip.mjs +0 -48
  331. package/esm/ai/src/security/private-ip.mjs.map +0 -1
  332. package/esm/ai/src/security/redact.mjs +0 -60
  333. package/esm/ai/src/security/redact.mjs.map +0 -1
  334. package/esm/ai/src/serve/serve.mjs +0 -90
  335. package/esm/ai/src/serve/serve.mjs.map +0 -1
  336. package/esm/ai/src/serve/sse.mjs +0 -25
  337. package/esm/ai/src/serve/sse.mjs.map +0 -1
  338. package/esm/ai/src/serve/stream-to-sse.mjs +0 -37
  339. package/esm/ai/src/serve/stream-to-sse.mjs.map +0 -1
  340. package/esm/ai/src/skills/catalog.mjs +0 -140
  341. package/esm/ai/src/skills/catalog.mjs.map +0 -1
  342. package/esm/ai/src/skills/index.mjs +0 -11
  343. package/esm/ai/src/skills/load-skill-tool.mjs +0 -65
  344. package/esm/ai/src/skills/load-skill-tool.mjs.map +0 -1
  345. package/esm/ai/src/skills/save-skill-tool.mjs +0 -65
  346. package/esm/ai/src/skills/save-skill-tool.mjs.map +0 -1
  347. package/esm/ai/src/skills/skills.mjs +0 -109
  348. package/esm/ai/src/skills/skills.mjs.map +0 -1
  349. package/esm/ai/src/skills/sources/directory-source.mjs +0 -108
  350. package/esm/ai/src/skills/sources/directory-source.mjs.map +0 -1
  351. package/esm/ai/src/skills/sources/index.mjs +0 -27
  352. package/esm/ai/src/skills/sources/index.mjs.map +0 -1
  353. package/esm/ai/src/skills/sources/parse-frontmatter.mjs +0 -46
  354. package/esm/ai/src/skills/sources/parse-frontmatter.mjs.map +0 -1
  355. package/esm/ai/src/skills/sources/store-source.mjs +0 -15
  356. package/esm/ai/src/skills/sources/store-source.mjs.map +0 -1
  357. package/esm/ai/src/skills/sources/url-source.mjs +0 -117
  358. package/esm/ai/src/skills/sources/url-source.mjs.map +0 -1
  359. package/esm/ai/src/snapshot/memory.mjs +0 -81
  360. package/esm/ai/src/snapshot/memory.mjs.map +0 -1
  361. package/esm/ai/src/snapshot/pg.mjs +0 -146
  362. package/esm/ai/src/snapshot/pg.mjs.map +0 -1
  363. package/esm/ai/src/snapshot/redis.mjs +0 -101
  364. package/esm/ai/src/snapshot/redis.mjs.map +0 -1
  365. package/esm/ai/src/speech/index.mjs +0 -3
  366. package/esm/ai/src/speech/speech.mjs +0 -122
  367. package/esm/ai/src/speech/speech.mjs.map +0 -1
  368. package/esm/ai/src/supervisor/as-tool.mjs +0 -74
  369. package/esm/ai/src/supervisor/as-tool.mjs.map +0 -1
  370. package/esm/ai/src/supervisor/cancellation.mjs +0 -22
  371. package/esm/ai/src/supervisor/cancellation.mjs.map +0 -1
  372. package/esm/ai/src/supervisor/decide.mjs +0 -272
  373. package/esm/ai/src/supervisor/decide.mjs.map +0 -1
  374. package/esm/ai/src/supervisor/emitter.mjs +0 -47
  375. package/esm/ai/src/supervisor/emitter.mjs.map +0 -1
  376. package/esm/ai/src/supervisor/entries.mjs +0 -206
  377. package/esm/ai/src/supervisor/entries.mjs.map +0 -1
  378. package/esm/ai/src/supervisor/execution.mjs +0 -1921
  379. package/esm/ai/src/supervisor/execution.mjs.map +0 -1
  380. package/esm/ai/src/supervisor/fan-out.mjs +0 -65
  381. package/esm/ai/src/supervisor/fan-out.mjs.map +0 -1
  382. package/esm/ai/src/supervisor/index.mjs +0 -14
  383. package/esm/ai/src/supervisor/router-factory.mjs +0 -141
  384. package/esm/ai/src/supervisor/router-factory.mjs.map +0 -1
  385. package/esm/ai/src/supervisor/router-prompt.mjs +0 -52
  386. package/esm/ai/src/supervisor/router-prompt.mjs.map +0 -1
  387. package/esm/ai/src/supervisor/signature.mjs +0 -89
  388. package/esm/ai/src/supervisor/signature.mjs.map +0 -1
  389. package/esm/ai/src/supervisor/snapshot.mjs +0 -69
  390. package/esm/ai/src/supervisor/snapshot.mjs.map +0 -1
  391. package/esm/ai/src/supervisor/supervisor-stream.mjs +0 -89
  392. package/esm/ai/src/supervisor/supervisor-stream.mjs.map +0 -1
  393. package/esm/ai/src/supervisor/supervisor.mjs +0 -144
  394. package/esm/ai/src/supervisor/supervisor.mjs.map +0 -1
  395. package/esm/ai/src/system-prompt/index.mjs +0 -7
  396. package/esm/ai/src/system-prompt/instruction.mjs +0 -57
  397. package/esm/ai/src/system-prompt/instruction.mjs.map +0 -1
  398. package/esm/ai/src/system-prompt/persona.mjs +0 -57
  399. package/esm/ai/src/system-prompt/persona.mjs.map +0 -1
  400. package/esm/ai/src/system-prompt/refined-system-prompt.mjs +0 -461
  401. package/esm/ai/src/system-prompt/refined-system-prompt.mjs.map +0 -1
  402. package/esm/ai/src/system-prompt/render-placeholders.mjs +0 -58
  403. package/esm/ai/src/system-prompt/render-placeholders.mjs.map +0 -1
  404. package/esm/ai/src/system-prompt/system-prompt.mjs +0 -286
  405. package/esm/ai/src/system-prompt/system-prompt.mjs.map +0 -1
  406. package/esm/ai/src/team/gates.mjs +0 -48
  407. package/esm/ai/src/team/gates.mjs.map +0 -1
  408. package/esm/ai/src/team/index.mjs +0 -3
  409. package/esm/ai/src/team/team.mjs +0 -94
  410. package/esm/ai/src/team/team.mjs.map +0 -1
  411. package/esm/ai/src/tool/executable-as-tool.mjs +0 -81
  412. package/esm/ai/src/tool/executable-as-tool.mjs.map +0 -1
  413. package/esm/ai/src/tool/index.mjs +0 -4
  414. package/esm/ai/src/tool/tool.mjs +0 -185
  415. package/esm/ai/src/tool/tool.mjs.map +0 -1
  416. package/esm/ai/src/transcribe/audio-input.mjs +0 -84
  417. package/esm/ai/src/transcribe/audio-input.mjs.map +0 -1
  418. package/esm/ai/src/transcribe/index.mjs +0 -4
  419. package/esm/ai/src/transcribe/transcribe.mjs +0 -127
  420. package/esm/ai/src/transcribe/transcribe.mjs.map +0 -1
  421. package/esm/ai/src/utils/compute-cost.mjs +0 -112
  422. package/esm/ai/src/utils/compute-cost.mjs.map +0 -1
  423. package/esm/ai/src/utils/extract-json-lenient.mjs +0 -97
  424. package/esm/ai/src/utils/extract-json-lenient.mjs.map +0 -1
  425. package/esm/ai/src/utils/extract-json-payload.mjs +0 -39
  426. package/esm/ai/src/utils/extract-json-payload.mjs.map +0 -1
  427. package/esm/ai/src/utils/generate-run-id.mjs +0 -23
  428. package/esm/ai/src/utils/generate-run-id.mjs.map +0 -1
  429. package/esm/ai/src/utils/index.mjs +0 -12
  430. package/esm/ai/src/utils/json-schema.mjs +0 -89
  431. package/esm/ai/src/utils/json-schema.mjs.map +0 -1
  432. package/esm/ai/src/utils/prepare-attachment-part.mjs +0 -232
  433. package/esm/ai/src/utils/prepare-attachment-part.mjs.map +0 -1
  434. package/esm/ai/src/utils/resolve-attachment.mjs +0 -74
  435. package/esm/ai/src/utils/resolve-attachment.mjs.map +0 -1
  436. package/esm/ai/src/utils/run-context.mjs +0 -89
  437. package/esm/ai/src/utils/run-context.mjs.map +0 -1
  438. package/esm/ai/src/utils/safe-json-parse.mjs +0 -22
  439. package/esm/ai/src/utils/safe-json-parse.mjs.map +0 -1
  440. package/esm/ai/src/utils/stamp-report-lineage.mjs +0 -45
  441. package/esm/ai/src/utils/stamp-report-lineage.mjs.map +0 -1
  442. package/esm/ai/src/vcr/cassette-io.mjs +0 -57
  443. package/esm/ai/src/vcr/cassette-io.mjs.map +0 -1
  444. package/esm/ai/src/vcr/errors.mjs +0 -37
  445. package/esm/ai/src/vcr/errors.mjs.map +0 -1
  446. package/esm/ai/src/vcr/hash-request.mjs +0 -118
  447. package/esm/ai/src/vcr/hash-request.mjs.map +0 -1
  448. package/esm/ai/src/vcr/index.mjs +0 -5
  449. package/esm/ai/src/vcr/vcr.mjs +0 -248
  450. package/esm/ai/src/vcr/vcr.mjs.map +0 -1
  451. package/esm/ai/src/workflow/as-tool.mjs +0 -49
  452. package/esm/ai/src/workflow/as-tool.mjs.map +0 -1
  453. package/esm/ai/src/workflow/cancellation.mjs +0 -44
  454. package/esm/ai/src/workflow/cancellation.mjs.map +0 -1
  455. package/esm/ai/src/workflow/emitter.mjs +0 -40
  456. package/esm/ai/src/workflow/emitter.mjs.map +0 -1
  457. package/esm/ai/src/workflow/engine.mjs +0 -363
  458. package/esm/ai/src/workflow/engine.mjs.map +0 -1
  459. package/esm/ai/src/workflow/index.mjs +0 -5
  460. package/esm/ai/src/workflow/retry.mjs +0 -32
  461. package/esm/ai/src/workflow/retry.mjs.map +0 -1
  462. package/esm/ai/src/workflow/router.mjs +0 -56
  463. package/esm/ai/src/workflow/router.mjs.map +0 -1
  464. package/esm/ai/src/workflow/run-scoped-emitter.mjs +0 -32
  465. package/esm/ai/src/workflow/run-scoped-emitter.mjs.map +0 -1
  466. package/esm/ai/src/workflow/signature.mjs +0 -34
  467. package/esm/ai/src/workflow/signature.mjs.map +0 -1
  468. package/esm/ai/src/workflow/snapshot.mjs +0 -77
  469. package/esm/ai/src/workflow/snapshot.mjs.map +0 -1
  470. package/esm/ai/src/workflow/state.mjs +0 -37
  471. package/esm/ai/src/workflow/state.mjs.map +0 -1
  472. package/esm/ai/src/workflow/step-runner.mjs +0 -370
  473. package/esm/ai/src/workflow/step-runner.mjs.map +0 -1
  474. package/esm/ai/src/workflow/step.mjs +0 -37
  475. package/esm/ai/src/workflow/step.mjs.map +0 -1
  476. package/esm/ai/src/workflow/workflow.mjs +0 -122
  477. package/esm/ai/src/workflow/workflow.mjs.map +0 -1
  478. package/esm/ai-openai/src/embedder.mjs +0 -4
  479. package/esm/ai-openai/src/image.mjs +0 -5
  480. package/esm/ai-openai/src/index.mjs +0 -7
  481. package/esm/ai-openai/src/model.mjs +0 -5
  482. package/esm/ai-openai/src/sdk.mjs +0 -9
  483. package/esm/ai-openai/src/speech.mjs +0 -5
  484. package/esm/ai-openai/src/transcription.mjs +0 -6
  485. package/esm/ai-openai/src/utils/index.mjs +0 -5
  486. package/esm/ai-openai/src/utils/to-openai-messages.mjs +0 -3
  487. package/esm/ai-openai/src/utils/to-openai-tools.mjs +0 -3
  488. package/esm/ai-openai/src/utils/wrap-openai-error.mjs +0 -4
  489. package/esm/node_modules/langfuse/lib/index.mjs +0 -1827
  490. package/esm/node_modules/langfuse/lib/index.mjs.map +0 -1
  491. package/esm/node_modules/langfuse-core/lib/index.mjs +0 -1770
  492. package/esm/node_modules/langfuse-core/lib/index.mjs.map +0 -1
  493. package/esm/node_modules/mustache/mustache.mjs +0 -587
  494. package/esm/node_modules/mustache/mustache.mjs.map +0 -1
  495. package/esm/node_modules/openai/_vendor/partial-json-parser/parser.mjs +0 -180
  496. package/esm/node_modules/openai/_vendor/partial-json-parser/parser.mjs.map +0 -1
  497. package/esm/node_modules/openai/auth/workload-identity-auth.mjs +0 -80
  498. package/esm/node_modules/openai/auth/workload-identity-auth.mjs.map +0 -1
  499. package/esm/node_modules/openai/azure.mjs +0 -82
  500. package/esm/node_modules/openai/azure.mjs.map +0 -1
  501. package/esm/node_modules/openai/client.mjs +0 -638
  502. package/esm/node_modules/openai/client.mjs.map +0 -1
  503. package/esm/node_modules/openai/core/api-promise.mjs +0 -75
  504. package/esm/node_modules/openai/core/api-promise.mjs.map +0 -1
  505. package/esm/node_modules/openai/core/error.mjs +0 -110
  506. package/esm/node_modules/openai/core/error.mjs.map +0 -1
  507. package/esm/node_modules/openai/core/pagination.mjs +0 -160
  508. package/esm/node_modules/openai/core/pagination.mjs.map +0 -1
  509. package/esm/node_modules/openai/core/resource.mjs +0 -10
  510. package/esm/node_modules/openai/core/resource.mjs.map +0 -1
  511. package/esm/node_modules/openai/core/streaming.mjs +0 -238
  512. package/esm/node_modules/openai/core/streaming.mjs.map +0 -1
  513. package/esm/node_modules/openai/index.mjs +0 -8
  514. package/esm/node_modules/openai/internal/decoders/line.mjs +0 -91
  515. package/esm/node_modules/openai/internal/decoders/line.mjs.map +0 -1
  516. package/esm/node_modules/openai/internal/detect-platform.mjs +0 -123
  517. package/esm/node_modules/openai/internal/detect-platform.mjs.map +0 -1
  518. package/esm/node_modules/openai/internal/errors.mjs +0 -26
  519. package/esm/node_modules/openai/internal/errors.mjs.map +0 -1
  520. package/esm/node_modules/openai/internal/headers.mjs +0 -65
  521. package/esm/node_modules/openai/internal/headers.mjs.map +0 -1
  522. package/esm/node_modules/openai/internal/parse.mjs +0 -41
  523. package/esm/node_modules/openai/internal/parse.mjs.map +0 -1
  524. package/esm/node_modules/openai/internal/qs/formats.mjs +0 -12
  525. package/esm/node_modules/openai/internal/qs/formats.mjs.map +0 -1
  526. package/esm/node_modules/openai/internal/qs/stringify.mjs +0 -179
  527. package/esm/node_modules/openai/internal/qs/stringify.mjs.map +0 -1
  528. package/esm/node_modules/openai/internal/qs/utils.mjs +0 -65
  529. package/esm/node_modules/openai/internal/qs/utils.mjs.map +0 -1
  530. package/esm/node_modules/openai/internal/request-options.mjs +0 -11
  531. package/esm/node_modules/openai/internal/request-options.mjs.map +0 -1
  532. package/esm/node_modules/openai/internal/shims.mjs +0 -77
  533. package/esm/node_modules/openai/internal/shims.mjs.map +0 -1
  534. package/esm/node_modules/openai/internal/to-file.mjs +0 -63
  535. package/esm/node_modules/openai/internal/to-file.mjs.map +0 -1
  536. package/esm/node_modules/openai/internal/tslib.mjs +0 -16
  537. package/esm/node_modules/openai/internal/tslib.mjs.map +0 -1
  538. package/esm/node_modules/openai/internal/uploads.mjs +0 -94
  539. package/esm/node_modules/openai/internal/uploads.mjs.map +0 -1
  540. package/esm/node_modules/openai/internal/utils/base64.mjs +0 -22
  541. package/esm/node_modules/openai/internal/utils/base64.mjs.map +0 -1
  542. package/esm/node_modules/openai/internal/utils/bytes.mjs +0 -26
  543. package/esm/node_modules/openai/internal/utils/bytes.mjs.map +0 -1
  544. package/esm/node_modules/openai/internal/utils/env.mjs +0 -16
  545. package/esm/node_modules/openai/internal/utils/env.mjs.map +0 -1
  546. package/esm/node_modules/openai/internal/utils/log.mjs +0 -58
  547. package/esm/node_modules/openai/internal/utils/log.mjs.map +0 -1
  548. package/esm/node_modules/openai/internal/utils/path.mjs +0 -62
  549. package/esm/node_modules/openai/internal/utils/path.mjs.map +0 -1
  550. package/esm/node_modules/openai/internal/utils/query.mjs +0 -10
  551. package/esm/node_modules/openai/internal/utils/query.mjs.map +0 -1
  552. package/esm/node_modules/openai/internal/utils/sleep.mjs +0 -6
  553. package/esm/node_modules/openai/internal/utils/sleep.mjs.map +0 -1
  554. package/esm/node_modules/openai/internal/utils/uuid.mjs +0 -18
  555. package/esm/node_modules/openai/internal/utils/uuid.mjs.map +0 -1
  556. package/esm/node_modules/openai/internal/utils/values.mjs +0 -41
  557. package/esm/node_modules/openai/internal/utils/values.mjs.map +0 -1
  558. package/esm/node_modules/openai/lib/AbstractChatCompletionRunner.mjs +0 -247
  559. package/esm/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map +0 -1
  560. package/esm/node_modules/openai/lib/AssistantStream.mjs +0 -472
  561. package/esm/node_modules/openai/lib/AssistantStream.mjs.map +0 -1
  562. package/esm/node_modules/openai/lib/ChatCompletionRunner.mjs +0 -26
  563. package/esm/node_modules/openai/lib/ChatCompletionRunner.mjs.map +0 -1
  564. package/esm/node_modules/openai/lib/ChatCompletionStream.mjs +0 -423
  565. package/esm/node_modules/openai/lib/ChatCompletionStream.mjs.map +0 -1
  566. package/esm/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs +0 -26
  567. package/esm/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map +0 -1
  568. package/esm/node_modules/openai/lib/EventStream.mjs +0 -163
  569. package/esm/node_modules/openai/lib/EventStream.mjs.map +0 -1
  570. package/esm/node_modules/openai/lib/ResponsesParser.mjs +0 -94
  571. package/esm/node_modules/openai/lib/ResponsesParser.mjs.map +0 -1
  572. package/esm/node_modules/openai/lib/RunnableFunction.mjs +0 -8
  573. package/esm/node_modules/openai/lib/RunnableFunction.mjs.map +0 -1
  574. package/esm/node_modules/openai/lib/Util.mjs +0 -19
  575. package/esm/node_modules/openai/lib/Util.mjs.map +0 -1
  576. package/esm/node_modules/openai/lib/chatCompletionUtils.mjs +0 -11
  577. package/esm/node_modules/openai/lib/chatCompletionUtils.mjs.map +0 -1
  578. package/esm/node_modules/openai/lib/parser.mjs +0 -88
  579. package/esm/node_modules/openai/lib/parser.mjs.map +0 -1
  580. package/esm/node_modules/openai/lib/responses/ResponseStream.mjs +0 -231
  581. package/esm/node_modules/openai/lib/responses/ResponseStream.mjs.map +0 -1
  582. package/esm/node_modules/openai/resources/admin/admin.mjs +0 -15
  583. package/esm/node_modules/openai/resources/admin/admin.mjs.map +0 -1
  584. package/esm/node_modules/openai/resources/admin/organization/admin-api-keys.mjs +0 -81
  585. package/esm/node_modules/openai/resources/admin/organization/admin-api-keys.mjs.map +0 -1
  586. package/esm/node_modules/openai/resources/admin/organization/audit-logs.mjs +0 -31
  587. package/esm/node_modules/openai/resources/admin/organization/audit-logs.mjs.map +0 -1
  588. package/esm/node_modules/openai/resources/admin/organization/certificates.mjs +0 -153
  589. package/esm/node_modules/openai/resources/admin/organization/certificates.mjs.map +0 -1
  590. package/esm/node_modules/openai/resources/admin/organization/data-retention.mjs +0 -42
  591. package/esm/node_modules/openai/resources/admin/organization/data-retention.mjs.map +0 -1
  592. package/esm/node_modules/openai/resources/admin/organization/groups/groups.mjs +0 -106
  593. package/esm/node_modules/openai/resources/admin/organization/groups/groups.mjs.map +0 -1
  594. package/esm/node_modules/openai/resources/admin/organization/groups/roles.mjs +0 -88
  595. package/esm/node_modules/openai/resources/admin/organization/groups/roles.mjs.map +0 -1
  596. package/esm/node_modules/openai/resources/admin/organization/groups/users.mjs +0 -88
  597. package/esm/node_modules/openai/resources/admin/organization/groups/users.mjs.map +0 -1
  598. package/esm/node_modules/openai/resources/admin/organization/invites.mjs +0 -83
  599. package/esm/node_modules/openai/resources/admin/organization/invites.mjs.map +0 -1
  600. package/esm/node_modules/openai/resources/admin/organization/organization.mjs +0 -45
  601. package/esm/node_modules/openai/resources/admin/organization/organization.mjs.map +0 -1
  602. package/esm/node_modules/openai/resources/admin/organization/projects/api-keys.mjs +0 -72
  603. package/esm/node_modules/openai/resources/admin/organization/projects/api-keys.mjs.map +0 -1
  604. package/esm/node_modules/openai/resources/admin/organization/projects/certificates.mjs +0 -78
  605. package/esm/node_modules/openai/resources/admin/organization/projects/certificates.mjs.map +0 -1
  606. package/esm/node_modules/openai/resources/admin/organization/projects/data-retention.mjs +0 -46
  607. package/esm/node_modules/openai/resources/admin/organization/projects/data-retention.mjs.map +0 -1
  608. package/esm/node_modules/openai/resources/admin/organization/projects/groups/groups.mjs +0 -95
  609. package/esm/node_modules/openai/resources/admin/organization/projects/groups/groups.mjs.map +0 -1
  610. package/esm/node_modules/openai/resources/admin/organization/projects/groups/roles.mjs +0 -91
  611. package/esm/node_modules/openai/resources/admin/organization/projects/groups/roles.mjs.map +0 -1
  612. package/esm/node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs +0 -45
  613. package/esm/node_modules/openai/resources/admin/organization/projects/hosted-tool-permissions.mjs.map +0 -1
  614. package/esm/node_modules/openai/resources/admin/organization/projects/model-permissions.mjs +0 -63
  615. package/esm/node_modules/openai/resources/admin/organization/projects/model-permissions.mjs.map +0 -1
  616. package/esm/node_modules/openai/resources/admin/organization/projects/projects.mjs +0 -137
  617. package/esm/node_modules/openai/resources/admin/organization/projects/projects.mjs.map +0 -1
  618. package/esm/node_modules/openai/resources/admin/organization/projects/rate-limits.mjs +0 -51
  619. package/esm/node_modules/openai/resources/admin/organization/projects/rate-limits.mjs.map +0 -1
  620. package/esm/node_modules/openai/resources/admin/organization/projects/roles.mjs +0 -108
  621. package/esm/node_modules/openai/resources/admin/organization/projects/roles.mjs.map +0 -1
  622. package/esm/node_modules/openai/resources/admin/organization/projects/service-accounts.mjs +0 -112
  623. package/esm/node_modules/openai/resources/admin/organization/projects/service-accounts.mjs.map +0 -1
  624. package/esm/node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs +0 -106
  625. package/esm/node_modules/openai/resources/admin/organization/projects/spend-alerts.mjs.map +0 -1
  626. package/esm/node_modules/openai/resources/admin/organization/projects/users/roles.mjs +0 -91
  627. package/esm/node_modules/openai/resources/admin/organization/projects/users/roles.mjs.map +0 -1
  628. package/esm/node_modules/openai/resources/admin/organization/projects/users/users.mjs +0 -118
  629. package/esm/node_modules/openai/resources/admin/organization/projects/users/users.mjs.map +0 -1
  630. package/esm/node_modules/openai/resources/admin/organization/roles.mjs +0 -96
  631. package/esm/node_modules/openai/resources/admin/organization/roles.mjs.map +0 -1
  632. package/esm/node_modules/openai/resources/admin/organization/spend-alerts.mjs +0 -97
  633. package/esm/node_modules/openai/resources/admin/organization/spend-alerts.mjs.map +0 -1
  634. package/esm/node_modules/openai/resources/admin/organization/usage.mjs +0 -207
  635. package/esm/node_modules/openai/resources/admin/organization/usage.mjs.map +0 -1
  636. package/esm/node_modules/openai/resources/admin/organization/users/roles.mjs +0 -88
  637. package/esm/node_modules/openai/resources/admin/organization/users/roles.mjs.map +0 -1
  638. package/esm/node_modules/openai/resources/admin/organization/users/users.mjs +0 -82
  639. package/esm/node_modules/openai/resources/admin/organization/users/users.mjs.map +0 -1
  640. package/esm/node_modules/openai/resources/audio/audio.mjs +0 -21
  641. package/esm/node_modules/openai/resources/audio/audio.mjs.map +0 -1
  642. package/esm/node_modules/openai/resources/audio/speech.mjs +0 -39
  643. package/esm/node_modules/openai/resources/audio/speech.mjs.map +0 -1
  644. package/esm/node_modules/openai/resources/audio/transcriptions.mjs +0 -22
  645. package/esm/node_modules/openai/resources/audio/transcriptions.mjs.map +0 -1
  646. package/esm/node_modules/openai/resources/audio/translations.mjs +0 -21
  647. package/esm/node_modules/openai/resources/audio/translations.mjs.map +0 -1
  648. package/esm/node_modules/openai/resources/batches.mjs +0 -54
  649. package/esm/node_modules/openai/resources/batches.mjs.map +0 -1
  650. package/esm/node_modules/openai/resources/beta/assistants.mjs +0 -78
  651. package/esm/node_modules/openai/resources/beta/assistants.mjs.map +0 -1
  652. package/esm/node_modules/openai/resources/beta/beta.mjs +0 -24
  653. package/esm/node_modules/openai/resources/beta/beta.mjs.map +0 -1
  654. package/esm/node_modules/openai/resources/beta/chatkit/chatkit.mjs +0 -18
  655. package/esm/node_modules/openai/resources/beta/chatkit/chatkit.mjs.map +0 -1
  656. package/esm/node_modules/openai/resources/beta/chatkit/sessions.mjs +0 -49
  657. package/esm/node_modules/openai/resources/beta/chatkit/sessions.mjs.map +0 -1
  658. package/esm/node_modules/openai/resources/beta/chatkit/threads.mjs +0 -85
  659. package/esm/node_modules/openai/resources/beta/chatkit/threads.mjs.map +0 -1
  660. package/esm/node_modules/openai/resources/beta/realtime/realtime.mjs +0 -21
  661. package/esm/node_modules/openai/resources/beta/realtime/realtime.mjs.map +0 -1
  662. package/esm/node_modules/openai/resources/beta/realtime/sessions.mjs +0 -33
  663. package/esm/node_modules/openai/resources/beta/realtime/sessions.mjs.map +0 -1
  664. package/esm/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs +0 -33
  665. package/esm/node_modules/openai/resources/beta/realtime/transcription-sessions.mjs.map +0 -1
  666. package/esm/node_modules/openai/resources/beta/threads/messages.mjs +0 -83
  667. package/esm/node_modules/openai/resources/beta/threads/messages.mjs.map +0 -1
  668. package/esm/node_modules/openai/resources/beta/threads/runs/runs.mjs +0 -183
  669. package/esm/node_modules/openai/resources/beta/threads/runs/runs.mjs.map +0 -1
  670. package/esm/node_modules/openai/resources/beta/threads/runs/steps.mjs +0 -45
  671. package/esm/node_modules/openai/resources/beta/threads/runs/steps.mjs.map +0 -1
  672. package/esm/node_modules/openai/resources/beta/threads/threads.mjs +0 -101
  673. package/esm/node_modules/openai/resources/beta/threads/threads.mjs.map +0 -1
  674. package/esm/node_modules/openai/resources/chat/chat.mjs +0 -15
  675. package/esm/node_modules/openai/resources/chat/chat.mjs.map +0 -1
  676. package/esm/node_modules/openai/resources/chat/completions/completions.mjs +0 -123
  677. package/esm/node_modules/openai/resources/chat/completions/completions.mjs.map +0 -1
  678. package/esm/node_modules/openai/resources/chat/completions/index.mjs +0 -7
  679. package/esm/node_modules/openai/resources/chat/completions/messages.mjs +0 -35
  680. package/esm/node_modules/openai/resources/chat/completions/messages.mjs.map +0 -1
  681. package/esm/node_modules/openai/resources/chat/index.mjs +0 -5
  682. package/esm/node_modules/openai/resources/completions.mjs +0 -20
  683. package/esm/node_modules/openai/resources/completions.mjs.map +0 -1
  684. package/esm/node_modules/openai/resources/containers/containers.mjs +0 -57
  685. package/esm/node_modules/openai/resources/containers/containers.mjs.map +0 -1
  686. package/esm/node_modules/openai/resources/containers/files/content.mjs +0 -23
  687. package/esm/node_modules/openai/resources/containers/files/content.mjs.map +0 -1
  688. package/esm/node_modules/openai/resources/containers/files/files.mjs +0 -63
  689. package/esm/node_modules/openai/resources/containers/files/files.mjs.map +0 -1
  690. package/esm/node_modules/openai/resources/conversations/conversations.mjs +0 -57
  691. package/esm/node_modules/openai/resources/conversations/conversations.mjs.map +0 -1
  692. package/esm/node_modules/openai/resources/conversations/items.mjs +0 -57
  693. package/esm/node_modules/openai/resources/conversations/items.mjs.map +0 -1
  694. package/esm/node_modules/openai/resources/embeddings.mjs +0 -48
  695. package/esm/node_modules/openai/resources/embeddings.mjs.map +0 -1
  696. package/esm/node_modules/openai/resources/evals/evals.mjs +0 -73
  697. package/esm/node_modules/openai/resources/evals/evals.mjs.map +0 -1
  698. package/esm/node_modules/openai/resources/evals/runs/output-items.mjs +0 -35
  699. package/esm/node_modules/openai/resources/evals/runs/output-items.mjs.map +0 -1
  700. package/esm/node_modules/openai/resources/evals/runs/runs.mjs +0 -72
  701. package/esm/node_modules/openai/resources/evals/runs/runs.mjs.map +0 -1
  702. package/esm/node_modules/openai/resources/files.mjs +0 -111
  703. package/esm/node_modules/openai/resources/files.mjs.map +0 -1
  704. package/esm/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs +0 -15
  705. package/esm/node_modules/openai/resources/fine-tuning/alpha/alpha.mjs.map +0 -1
  706. package/esm/node_modules/openai/resources/fine-tuning/alpha/graders.mjs +0 -60
  707. package/esm/node_modules/openai/resources/fine-tuning/alpha/graders.mjs.map +0 -1
  708. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs +0 -15
  709. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs.map +0 -1
  710. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs +0 -102
  711. package/esm/node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs.map +0 -1
  712. package/esm/node_modules/openai/resources/fine-tuning/fine-tuning.mjs +0 -24
  713. package/esm/node_modules/openai/resources/fine-tuning/fine-tuning.mjs.map +0 -1
  714. package/esm/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +0 -34
  715. package/esm/node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs.map +0 -1
  716. package/esm/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs +0 -148
  717. package/esm/node_modules/openai/resources/fine-tuning/jobs/jobs.mjs.map +0 -1
  718. package/esm/node_modules/openai/resources/fine-tuning/methods.mjs +0 -8
  719. package/esm/node_modules/openai/resources/fine-tuning/methods.mjs.map +0 -1
  720. package/esm/node_modules/openai/resources/graders/grader-models.mjs +0 -8
  721. package/esm/node_modules/openai/resources/graders/grader-models.mjs.map +0 -1
  722. package/esm/node_modules/openai/resources/graders/graders.mjs +0 -15
  723. package/esm/node_modules/openai/resources/graders/graders.mjs.map +0 -1
  724. package/esm/node_modules/openai/resources/images.mjs +0 -46
  725. package/esm/node_modules/openai/resources/images.mjs.map +0 -1
  726. package/esm/node_modules/openai/resources/index.mjs +0 -27
  727. package/esm/node_modules/openai/resources/models.mjs +0 -44
  728. package/esm/node_modules/openai/resources/models.mjs.map +0 -1
  729. package/esm/node_modules/openai/resources/moderations.mjs +0 -23
  730. package/esm/node_modules/openai/resources/moderations.mjs.map +0 -1
  731. package/esm/node_modules/openai/resources/realtime/calls.mjs +0 -79
  732. package/esm/node_modules/openai/resources/realtime/calls.mjs.map +0 -1
  733. package/esm/node_modules/openai/resources/realtime/client-secrets.mjs +0 -39
  734. package/esm/node_modules/openai/resources/realtime/client-secrets.mjs.map +0 -1
  735. package/esm/node_modules/openai/resources/realtime/realtime.mjs +0 -18
  736. package/esm/node_modules/openai/resources/realtime/realtime.mjs.map +0 -1
  737. package/esm/node_modules/openai/resources/responses/input-items.mjs +0 -31
  738. package/esm/node_modules/openai/resources/responses/input-items.mjs.map +0 -1
  739. package/esm/node_modules/openai/resources/responses/input-tokens.mjs +0 -27
  740. package/esm/node_modules/openai/resources/responses/input-tokens.mjs.map +0 -1
  741. package/esm/node_modules/openai/resources/responses/responses.mjs +0 -110
  742. package/esm/node_modules/openai/resources/responses/responses.mjs.map +0 -1
  743. package/esm/node_modules/openai/resources/skills/content.mjs +0 -22
  744. package/esm/node_modules/openai/resources/skills/content.mjs.map +0 -1
  745. package/esm/node_modules/openai/resources/skills/skills.mjs +0 -69
  746. package/esm/node_modules/openai/resources/skills/skills.mjs.map +0 -1
  747. package/esm/node_modules/openai/resources/skills/versions/content.mjs +0 -23
  748. package/esm/node_modules/openai/resources/skills/versions/content.mjs.map +0 -1
  749. package/esm/node_modules/openai/resources/skills/versions/versions.mjs +0 -58
  750. package/esm/node_modules/openai/resources/skills/versions/versions.mjs.map +0 -1
  751. package/esm/node_modules/openai/resources/uploads/parts.mjs +0 -34
  752. package/esm/node_modules/openai/resources/uploads/parts.mjs.map +0 -1
  753. package/esm/node_modules/openai/resources/uploads/uploads.mjs +0 -84
  754. package/esm/node_modules/openai/resources/uploads/uploads.mjs.map +0 -1
  755. package/esm/node_modules/openai/resources/vector-stores/file-batches.mjs +0 -126
  756. package/esm/node_modules/openai/resources/vector-stores/file-batches.mjs.map +0 -1
  757. package/esm/node_modules/openai/resources/vector-stores/files.mjs +0 -147
  758. package/esm/node_modules/openai/resources/vector-stores/files.mjs.map +0 -1
  759. package/esm/node_modules/openai/resources/vector-stores/vector-stores.mjs +0 -87
  760. package/esm/node_modules/openai/resources/vector-stores/vector-stores.mjs.map +0 -1
  761. package/esm/node_modules/openai/resources/videos.mjs +0 -115
  762. package/esm/node_modules/openai/resources/videos.mjs.map +0 -1
  763. package/esm/node_modules/openai/resources/webhooks/index.mjs +0 -3
  764. package/esm/node_modules/openai/resources/webhooks/webhooks.mjs +0 -69
  765. package/esm/node_modules/openai/resources/webhooks/webhooks.mjs.map +0 -1
  766. package/esm/node_modules/openai/resources/webhooks.mjs +0 -4
  767. package/esm/node_modules/openai/streaming.mjs +0 -3
  768. package/esm/node_modules/openai/version.mjs +0 -6
  769. package/esm/node_modules/openai/version.mjs.map +0 -1
@@ -1,1770 +0,0 @@
1
- import mustache from "../../mustache/mustache.mjs";
2
-
3
- //#region ../@warlock.js/node_modules/langfuse-core/lib/index.mjs
4
- var SimpleEventEmitter = class {
5
- constructor() {
6
- this.events = {};
7
- this.events = {};
8
- }
9
- on(event, listener) {
10
- if (!this.events[event]) this.events[event] = [];
11
- this.events[event].push(listener);
12
- return () => {
13
- this.events[event] = this.events[event].filter((x) => x !== listener);
14
- };
15
- }
16
- emit(event, payload) {
17
- for (const listener of this.events[event] || []) listener(payload);
18
- for (const listener of this.events["*"] || []) listener(event, payload);
19
- }
20
- };
21
- const DEFAULT_PROMPT_CACHE_TTL_SECONDS = 60;
22
- var LangfusePromptCacheItem = class {
23
- constructor(value, ttlSeconds) {
24
- this.value = value;
25
- this._expiry = Date.now() + ttlSeconds * 1e3;
26
- }
27
- get isExpired() {
28
- return Date.now() > this._expiry;
29
- }
30
- };
31
- var LangfusePromptCache = class {
32
- constructor() {
33
- this._cache = /* @__PURE__ */ new Map();
34
- this._defaultTtlSeconds = DEFAULT_PROMPT_CACHE_TTL_SECONDS;
35
- this._refreshingKeys = /* @__PURE__ */ new Map();
36
- }
37
- getIncludingExpired(key) {
38
- return this._cache.get(key) ?? null;
39
- }
40
- set(key, value, ttlSeconds) {
41
- const effectiveTtlSeconds = ttlSeconds ?? this._defaultTtlSeconds;
42
- this._cache.set(key, new LangfusePromptCacheItem(value, effectiveTtlSeconds));
43
- }
44
- addRefreshingPromise(key, promise) {
45
- this._refreshingKeys.set(key, promise);
46
- promise.then(() => {
47
- this._refreshingKeys.delete(key);
48
- }).catch(() => {
49
- this._refreshingKeys.delete(key);
50
- });
51
- }
52
- isRefreshing(key) {
53
- return this._refreshingKeys.has(key);
54
- }
55
- invalidate(promptName) {
56
- console.log("invalidating", promptName, this._cache.keys());
57
- for (const key of this._cache.keys()) if (key.startsWith(promptName)) this._cache.delete(key);
58
- }
59
- };
60
- var LangfusePersistedProperty;
61
- (function(LangfusePersistedProperty) {
62
- LangfusePersistedProperty["Props"] = "props";
63
- LangfusePersistedProperty["Queue"] = "queue";
64
- LangfusePersistedProperty["OptedOut"] = "opted_out";
65
- })(LangfusePersistedProperty || (LangfusePersistedProperty = {}));
66
- var ChatMessageType;
67
- (function(ChatMessageType) {
68
- ChatMessageType["ChatMessage"] = "chatmessage";
69
- ChatMessageType["Placeholder"] = "placeholder";
70
- })(ChatMessageType || (ChatMessageType = {}));
71
- mustache.escape = function(text) {
72
- return text;
73
- };
74
- var BasePromptClient = class {
75
- constructor(prompt, isFallback = false, type) {
76
- this.name = prompt.name;
77
- this.version = prompt.version;
78
- this.config = prompt.config;
79
- this.labels = prompt.labels;
80
- this.tags = prompt.tags;
81
- this.isFallback = isFallback;
82
- this.type = type;
83
- this.commitMessage = prompt.commitMessage;
84
- }
85
- _transformToLangchainVariables(content) {
86
- return this.escapeJsonForLangchain(content).replace(/\{\{(\w+)\}\}/g, "{$1}");
87
- }
88
- /**
89
- * Escapes every curly brace that is part of a JSON object by doubling it.
90
- *
91
- * A curly brace is considered “JSON-related” when, after skipping any immediate
92
- * whitespace, the next non-whitespace character is a single (') or double (") quote.
93
- *
94
- * Braces that are already doubled (e.g. `{{variable}}` placeholders) are left untouched.
95
- *
96
- * @param text - Input string that may contain JSON snippets.
97
- * @returns The string with JSON-related braces doubled.
98
- */
99
- escapeJsonForLangchain(text) {
100
- const out = [];
101
- const stack = [];
102
- let i = 0;
103
- const n = text.length;
104
- while (i < n) {
105
- const ch = text[i];
106
- if (ch === "{") {
107
- if (i + 1 < n && text[i + 1] === "{") {
108
- out.push("{{");
109
- i += 2;
110
- continue;
111
- }
112
- let j = i + 1;
113
- while (j < n && /\s/.test(text[j])) j++;
114
- const isJson = j < n && (text[j] === "'" || text[j] === "\"");
115
- out.push(isJson ? "{{" : "{");
116
- stack.push(isJson);
117
- i += 1;
118
- continue;
119
- }
120
- if (ch === "}") {
121
- if (i + 1 < n && text[i + 1] === "}") {
122
- out.push("}}");
123
- i += 2;
124
- continue;
125
- }
126
- const isJson = stack.pop() ?? false;
127
- out.push(isJson ? "}}" : "}");
128
- i += 1;
129
- continue;
130
- }
131
- out.push(ch);
132
- i += 1;
133
- }
134
- return out.join("");
135
- }
136
- };
137
- var TextPromptClient = class extends BasePromptClient {
138
- constructor(prompt, isFallback = false) {
139
- super(prompt, isFallback, "text");
140
- this.promptResponse = prompt;
141
- this.prompt = prompt.prompt;
142
- }
143
- compile(variables, _placeholders) {
144
- return mustache.render(this.promptResponse.prompt, variables ?? {});
145
- }
146
- getLangchainPrompt(_options) {
147
- /**
148
- * Converts Langfuse prompt into string compatible with Langchain PromptTemplate.
149
- *
150
- * It specifically adapts the mustache-style double curly braces {{variable}} used in Langfuse
151
- * to the single curly brace {variable} format expected by Langchain.
152
- *
153
- * @returns {string} The string that can be plugged into Langchain's PromptTemplate.
154
- */
155
- return this._transformToLangchainVariables(this.prompt);
156
- }
157
- toJSON() {
158
- return JSON.stringify({
159
- name: this.name,
160
- prompt: this.prompt,
161
- version: this.version,
162
- isFallback: this.isFallback,
163
- tags: this.tags,
164
- labels: this.labels,
165
- type: this.type,
166
- config: this.config
167
- });
168
- }
169
- };
170
- var ChatPromptClient = class ChatPromptClient extends BasePromptClient {
171
- constructor(prompt, isFallback = false) {
172
- const normalizedPrompt = ChatPromptClient.normalizePrompt(prompt.prompt);
173
- const typedPrompt = {
174
- ...prompt,
175
- prompt: normalizedPrompt
176
- };
177
- super(typedPrompt, isFallback, "chat");
178
- this.promptResponse = typedPrompt;
179
- this.prompt = normalizedPrompt;
180
- }
181
- static normalizePrompt(prompt) {
182
- return prompt.map((item) => {
183
- if ("type" in item) return item;
184
- else return {
185
- type: ChatMessageType.ChatMessage,
186
- ...item
187
- };
188
- });
189
- }
190
- compile(variables, placeholders) {
191
- /**
192
- * Compiles the chat prompt by replacing placeholders and variables with provided values.
193
- *
194
- * First fills-in placeholders by from the provided placeholder parameter.
195
- * Then compiles variables into the message content.
196
- * Unresolved placeholders are included in the output as placeholder objects.
197
- * If you only want to fill-in placeholders, pass an empty object for variables.
198
- *
199
- * @param variables - Key-value pairs for Mustache variable substitution in message content
200
- * @param placeholders - Key-value pairs where keys are placeholder names and values can be ChatMessage arrays
201
- * @returns Array of ChatMessage objects and placeholder objects with placeholders replaced and variables rendered
202
- */
203
- const messagesWithPlaceholdersReplaced = [];
204
- const placeholderValues = placeholders ?? {};
205
- for (const item of this.prompt) if ("type" in item && item.type === ChatMessageType.Placeholder) {
206
- const placeholderValue = placeholderValues[item.name];
207
- if (Array.isArray(placeholderValue) && placeholderValue.length > 0 && placeholderValue.every((msg) => typeof msg === "object" && "role" in msg && "content" in msg)) messagesWithPlaceholdersReplaced.push(...placeholderValue);
208
- else if (Array.isArray(placeholderValue) && placeholderValue.length === 0);
209
- else if (placeholderValue !== void 0) messagesWithPlaceholdersReplaced.push(JSON.stringify(placeholderValue));
210
- else messagesWithPlaceholdersReplaced.push(item);
211
- } else if ("role" in item && "content" in item && item.type === ChatMessageType.ChatMessage) messagesWithPlaceholdersReplaced.push({
212
- role: item.role,
213
- content: item.content
214
- });
215
- return messagesWithPlaceholdersReplaced.map((item) => {
216
- if (typeof item === "object" && item !== null && "role" in item && "content" in item) return {
217
- ...item,
218
- content: mustache.render(item.content, variables ?? {})
219
- };
220
- else return item;
221
- });
222
- }
223
- getLangchainPrompt(options) {
224
- const messagesWithPlaceholdersReplaced = [];
225
- const placeholderValues = options?.placeholders ?? {};
226
- for (const item of this.prompt) if ("type" in item && item.type === ChatMessageType.Placeholder) {
227
- const placeholderValue = placeholderValues[item.name];
228
- if (Array.isArray(placeholderValue) && placeholderValue.length > 0 && placeholderValue.every((msg) => typeof msg === "object" && "role" in msg && "content" in msg)) messagesWithPlaceholdersReplaced.push(...placeholderValue.map((msg) => {
229
- return {
230
- role: msg.role,
231
- content: this._transformToLangchainVariables(msg.content)
232
- };
233
- }));
234
- else if (Array.isArray(placeholderValue) && placeholderValue.length === 0);
235
- else if (placeholderValue !== void 0) messagesWithPlaceholdersReplaced.push(JSON.stringify(placeholderValue));
236
- else messagesWithPlaceholdersReplaced.push({
237
- variableName: item.name,
238
- optional: false
239
- });
240
- } else if ("role" in item && "content" in item && item.type === ChatMessageType.ChatMessage) messagesWithPlaceholdersReplaced.push({
241
- role: item.role,
242
- content: this._transformToLangchainVariables(item.content)
243
- });
244
- return messagesWithPlaceholdersReplaced;
245
- }
246
- toJSON() {
247
- return JSON.stringify({
248
- name: this.name,
249
- prompt: this.promptResponse.prompt.map((item) => {
250
- if ("type" in item && item.type === ChatMessageType.ChatMessage) {
251
- const { type: _, ...messageWithoutType } = item;
252
- return messageWithoutType;
253
- }
254
- return item;
255
- }),
256
- version: this.version,
257
- isFallback: this.isFallback,
258
- tags: this.tags,
259
- labels: this.labels,
260
- type: this.type,
261
- config: this.config
262
- });
263
- }
264
- };
265
- function assert(truthyValue, message) {
266
- if (!truthyValue) throw new Error(message);
267
- }
268
- function removeTrailingSlash(url) {
269
- return url?.replace(/\/+$/, "");
270
- }
271
- async function retriable(fn, props = {}, log) {
272
- const { retryCount = 3, retryDelay = 5e3, retryCheck = () => true } = props;
273
- let lastError = null;
274
- for (let i = 0; i < retryCount + 1; i++) {
275
- if (i > 0) {
276
- await new Promise((resolve) => setTimeout(resolve, retryDelay));
277
- log(`Retrying ${i + 1} of ${retryCount + 1}`);
278
- }
279
- try {
280
- return await fn();
281
- } catch (e) {
282
- lastError = e;
283
- if (!retryCheck(e)) throw e;
284
- log(`Retriable error: ${JSON.stringify(e)}`);
285
- }
286
- }
287
- throw lastError;
288
- }
289
- function generateUUID(globalThis) {
290
- let d = (/* @__PURE__ */ new Date()).getTime();
291
- let d2 = globalThis && globalThis.performance && globalThis.performance.now && globalThis.performance.now() * 1e3 || 0;
292
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
293
- let r = Math.random() * 16;
294
- if (d > 0) {
295
- r = (d + r) % 16 | 0;
296
- d = Math.floor(d / 16);
297
- } else {
298
- r = (d2 + r) % 16 | 0;
299
- d2 = Math.floor(d2 / 16);
300
- }
301
- return (c === "x" ? r : r & 3 | 8).toString(16);
302
- });
303
- }
304
- function currentTimestamp() {
305
- return (/* @__PURE__ */ new Date()).getTime();
306
- }
307
- function currentISOTime() {
308
- return (/* @__PURE__ */ new Date()).toISOString();
309
- }
310
- function safeSetTimeout(fn, timeout) {
311
- const t = setTimeout(fn, timeout);
312
- t?.unref && t?.unref();
313
- return t;
314
- }
315
- function getEnv(key) {
316
- if (typeof process !== "undefined" && process.env[key]) return process.env[key];
317
- else if (typeof globalThis !== "undefined") return globalThis[key];
318
- }
319
- function configLangfuseSDK(params, secretRequired = true) {
320
- const { publicKey, secretKey, ...coreOptions } = params ?? {};
321
- const finalPublicKey = publicKey ?? getEnv("LANGFUSE_PUBLIC_KEY");
322
- const finalSecretKey = secretRequired ? secretKey ?? getEnv("LANGFUSE_SECRET_KEY") : void 0;
323
- const finalBaseUrl = coreOptions.baseUrl ?? getEnv("LANGFUSE_BASEURL");
324
- const finalCoreOptions = {
325
- ...coreOptions,
326
- baseUrl: finalBaseUrl
327
- };
328
- return {
329
- publicKey: finalPublicKey,
330
- ...secretRequired ? { secretKey: finalSecretKey } : void 0,
331
- ...finalCoreOptions
332
- };
333
- }
334
- const encodeQueryParams = (params) => {
335
- const queryParams = new URLSearchParams();
336
- Object.entries(params ?? {}).forEach(([key, value]) => {
337
- if (value !== void 0 && value !== null) if (value instanceof Date) queryParams.append(key, value.toISOString());
338
- else queryParams.append(key, value.toString());
339
- });
340
- return queryParams.toString();
341
- };
342
- var utils = /*#__PURE__*/ Object.freeze({
343
- __proto__: null,
344
- assert,
345
- configLangfuseSDK,
346
- currentISOTime,
347
- currentTimestamp,
348
- encodeQueryParams,
349
- generateUUID,
350
- getEnv,
351
- removeTrailingSlash,
352
- retriable,
353
- safeSetTimeout
354
- });
355
- const common_release_envs = [
356
- "VERCEL_GIT_COMMIT_SHA",
357
- "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA",
358
- "COMMIT_REF",
359
- "RENDER_GIT_COMMIT",
360
- "CI_COMMIT_SHA",
361
- "CIRCLE_SHA1",
362
- "CF_PAGES_COMMIT_SHA",
363
- "REACT_APP_GIT_SHA",
364
- "SOURCE_VERSION",
365
- "TRIGGER_DEPLOYMENT_ID"
366
- ];
367
- function getCommonReleaseEnvs() {
368
- for (const key of common_release_envs) {
369
- const value = getEnv(key);
370
- if (value) return value;
371
- }
372
- }
373
- let fs = null;
374
- let cryptoModule = null;
375
- const dynamicImport = (module) => {
376
- return import(
377
- /* webpackIgnore: true */
378
- module
379
- );
380
- };
381
- if (typeof globalThis.Deno !== "undefined") Promise.all([dynamicImport("node:fs"), dynamicImport("node:crypto")]).then(([importedFs, importedCrypto]) => {
382
- fs = importedFs;
383
- cryptoModule = importedCrypto;
384
- }).catch();
385
- else if (typeof process !== "undefined" && process.versions?.node) Promise.all([dynamicImport("fs"), dynamicImport("crypto")]).then(([importedFs, importedCrypto]) => {
386
- fs = importedFs;
387
- cryptoModule = importedCrypto;
388
- }).catch();
389
- else if (typeof crypto !== "undefined") cryptoModule = crypto;
390
- /**
391
- * A class for wrapping media objects for upload to Langfuse.
392
- *
393
- * This class handles the preparation and formatting of media content for Langfuse,
394
- * supporting both base64 data URIs and raw content bytes.
395
- */
396
- var LangfuseMedia = class LangfuseMedia {
397
- constructor(params) {
398
- const { obj, base64DataUri, contentType, contentBytes, filePath } = params;
399
- this.obj = obj;
400
- this._mediaId = void 0;
401
- if (base64DataUri) {
402
- const [contentBytesParsed, contentTypeParsed] = this.parseBase64DataUri(base64DataUri);
403
- this._contentBytes = contentBytesParsed;
404
- this._contentType = contentTypeParsed;
405
- this._source = "base64_data_uri";
406
- } else if (contentBytes && contentType) {
407
- this._contentBytes = contentBytes;
408
- this._contentType = contentType;
409
- this._source = "bytes";
410
- } else if (filePath && contentType) {
411
- if (!fs) throw new Error("File system support is not available in this environment");
412
- if (!fs.existsSync(filePath)) throw new Error(`File at path ${filePath} does not exist`);
413
- this._contentBytes = this.readFile(filePath);
414
- this._contentType = this._contentBytes ? contentType : void 0;
415
- this._source = this._contentBytes ? "file" : void 0;
416
- } else console.error("base64DataUri, or contentBytes and contentType, or filePath must be provided to LangfuseMedia");
417
- }
418
- readFile(filePath) {
419
- try {
420
- if (!fs) throw new Error("File system support is not available in this environment");
421
- return fs.readFileSync(filePath);
422
- } catch (error) {
423
- console.error(`Error reading file at path ${filePath}`, error);
424
- return;
425
- }
426
- }
427
- parseBase64DataUri(data) {
428
- try {
429
- if (!data || typeof data !== "string") throw new Error("Data URI is not a string");
430
- if (!data.startsWith("data:")) throw new Error("Data URI does not start with 'data:'");
431
- const [header, actualData] = data.slice(5).split(",", 2);
432
- if (!header || !actualData) throw new Error("Invalid URI");
433
- const headerParts = header.split(";");
434
- if (!headerParts.includes("base64")) throw new Error("Data is not base64 encoded");
435
- const contentType = headerParts[0];
436
- if (!contentType) throw new Error("Content type is empty");
437
- return [Buffer.from(actualData, "base64"), contentType];
438
- } catch (error) {
439
- console.error("Error parsing base64 data URI", error);
440
- return [void 0, void 0];
441
- }
442
- }
443
- get contentLength() {
444
- return this._contentBytes?.length;
445
- }
446
- get contentSha256Hash() {
447
- if (!this._contentBytes) return;
448
- if (!cryptoModule) {
449
- console.error("Crypto support is not available in this environment");
450
- return;
451
- }
452
- return cryptoModule.createHash("sha256").update(this._contentBytes).digest("base64");
453
- }
454
- toJSON() {
455
- if (!this._contentType || !this._source || !this._mediaId) return `<Upload handling failed for LangfuseMedia of type ${this._contentType}>`;
456
- return `@@@langfuseMedia:type=${this._contentType}|id=${this._mediaId}|source=${this._source}@@@`;
457
- }
458
- /**
459
- * Parses a media reference string into a ParsedMediaReference.
460
- *
461
- * Example reference string:
462
- * "@@@langfuseMedia:type=image/jpeg|id=some-uuid|source=base64DataUri@@@"
463
- *
464
- * @param referenceString - The reference string to parse.
465
- * @returns An object with the mediaId, source, and contentType.
466
- *
467
- * @throws Error if the reference string is invalid or missing required fields.
468
- */
469
- static parseReferenceString(referenceString) {
470
- const prefix = "@@@langfuseMedia:";
471
- const suffix = "@@@";
472
- if (!referenceString.startsWith(prefix)) throw new Error("Reference string does not start with '@@@langfuseMedia:type='");
473
- if (!referenceString.endsWith(suffix)) throw new Error("Reference string does not end with '@@@'");
474
- const pairs = referenceString.slice(17, -3).split("|");
475
- const parsedData = {};
476
- for (const pair of pairs) {
477
- const [key, value] = pair.split("=", 2);
478
- parsedData[key] = value;
479
- }
480
- if (!("type" in parsedData && "id" in parsedData && "source" in parsedData)) throw new Error("Missing required fields in reference string");
481
- return {
482
- mediaId: parsedData["id"],
483
- source: parsedData["source"],
484
- contentType: parsedData["type"]
485
- };
486
- }
487
- /**
488
- * Replaces the media reference strings in an object with base64 data URIs for the media content.
489
- *
490
- * This method recursively traverses an object (up to a maximum depth of 10) looking for media reference strings
491
- * in the format "@@@langfuseMedia:...@@@". When found, it fetches the actual media content using the provided
492
- * Langfuse client and replaces the reference string with a base64 data URI.
493
- *
494
- * If fetching media content fails for a reference string, a warning is logged and the reference string is left unchanged.
495
- *
496
- * @param params - Configuration object
497
- * @param params.obj - The object to process. Can be a primitive value, array, or nested object
498
- * @param params.langfuseClient - Langfuse client instance used to fetch media content
499
- * @param params.resolveWith - The representation of the media content to replace the media reference string with. Currently only "base64DataUri" is supported.
500
- * @param params.maxDepth - Optional. Default is 10. The maximum depth to traverse the object.
501
- *
502
- * @returns A deep copy of the input object with all media references replaced with base64 data URIs where possible
503
- *
504
- * @example
505
- * ```typescript
506
- * const obj = {
507
- * image: "@@@langfuseMedia:type=image/jpeg|id=123|source=bytes@@@",
508
- * nested: {
509
- * pdf: "@@@langfuseMedia:type=application/pdf|id=456|source=bytes@@@"
510
- * }
511
- * };
512
- *
513
- * const result = await LangfuseMedia.resolveMediaReferences({
514
- * obj,
515
- * langfuseClient
516
- * });
517
- *
518
- * // Result:
519
- * // {
520
- * // image: "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
521
- * // nested: {
522
- * // pdf: "data:application/pdf;base64,JVBERi0xLjcK..."
523
- * // }
524
- * // }
525
- * ```
526
- */
527
- static async resolveMediaReferences(params) {
528
- const { obj, langfuseClient, maxDepth = 10 } = params;
529
- async function traverse(obj, depth) {
530
- if (depth > maxDepth) return obj;
531
- if (typeof obj === "string") {
532
- const referenceStringMatches = obj.match(/@@@langfuseMedia:.+?@@@/g);
533
- if (!referenceStringMatches) return obj;
534
- let result = obj;
535
- const referenceStringToMediaContentMap = /* @__PURE__ */ new Map();
536
- await Promise.all(referenceStringMatches.map(async (referenceString) => {
537
- try {
538
- const parsedMediaReference = LangfuseMedia.parseReferenceString(referenceString);
539
- const mediaData = await langfuseClient.fetchMedia(parsedMediaReference.mediaId);
540
- const mediaContent = await langfuseClient.fetch(mediaData.url, {
541
- method: "GET",
542
- headers: {}
543
- });
544
- if (mediaContent.status !== 200) throw new Error("Failed to fetch media content");
545
- const base64MediaContent = Buffer.from(await mediaContent.arrayBuffer()).toString("base64");
546
- const base64DataUri = `data:${mediaData.contentType};base64,${base64MediaContent}`;
547
- referenceStringToMediaContentMap.set(referenceString, base64DataUri);
548
- } catch (error) {
549
- console.warn("Error fetching media content for reference string", referenceString, error);
550
- }
551
- }));
552
- for (const [referenceString, base64MediaContent] of referenceStringToMediaContentMap.entries()) result = result.replaceAll(referenceString, base64MediaContent);
553
- return result;
554
- }
555
- if (Array.isArray(obj)) return Promise.all(obj.map(async (item) => await traverse(item, depth + 1)));
556
- if (typeof obj === "object" && obj !== null) return Object.fromEntries(await Promise.all(Object.entries(obj).map(async ([key, value]) => [key, await traverse(value, depth + 1)])));
557
- return obj;
558
- }
559
- return traverse(obj, 0);
560
- }
561
- };
562
- /**
563
- * A consistent sampling function that works for arbitrary strings across all JavaScript runtimes.
564
- */
565
- function isInSample(input, sampleRate) {
566
- if (sampleRate === void 0) return true;
567
- else if (sampleRate === 0) return false;
568
- if (sampleRate < 0 || sampleRate > 1 || isNaN(sampleRate)) {
569
- console.warn("Sample rate must be between 0 and 1. Ignoring setting.");
570
- return true;
571
- }
572
- return simpleHash(input) < sampleRate;
573
- }
574
- /**
575
- * Simple and consistent string hashing function.
576
- * Uses character codes and prime numbers for good distribution.
577
- */
578
- function simpleHash(str) {
579
- let hash = 0;
580
- const prime = 31;
581
- for (let i = 0; i < str.length; i++) hash = hash * prime + str.charCodeAt(i) >>> 0;
582
- hash = (hash >>> 16 ^ hash) * 73244475;
583
- hash = (hash >>> 16 ^ hash) * 73244475;
584
- hash = hash >>> 16 ^ hash;
585
- return Math.abs(hash) / 2147483647;
586
- }
587
- const MAX_EVENT_SIZE_BYTES = getEnv("LANGFUSE_MAX_EVENT_SIZE_BYTES") ? Number(getEnv("LANGFUSE_MAX_EVENT_SIZE_BYTES")) : 1e6;
588
- const MAX_BATCH_SIZE_BYTES = getEnv("LANGFUSE_MAX_BATCH_SIZE_BYTES") ? Number(getEnv("LANGFUSE_MAX_BATCH_SIZE_BYTES")) : 25e5;
589
- const ENVIRONMENT_PATTERN = /^(?!langfuse)[a-z0-9_-]+$/;
590
- const WHITELISTED_LANGFUSE_INTERNAL_ENVIRONMENTS = ["langfuse-prompt-experiment"];
591
- var LangfuseFetchHttpError = class extends Error {
592
- constructor(response, body) {
593
- super("HTTP error while fetching Langfuse: " + response.status + " and body: " + body);
594
- this.response = response;
595
- this.name = "LangfuseFetchHttpError";
596
- }
597
- };
598
- var LangfuseFetchNetworkError = class extends Error {
599
- constructor(error) {
600
- super("Network error while fetching Langfuse", error instanceof Error ? { cause: error } : {});
601
- this.error = error;
602
- this.name = "LangfuseFetchNetworkError";
603
- }
604
- };
605
- function isLangfuseFetchHttpError(error) {
606
- return typeof error === "object" && error.name === "LangfuseFetchHttpError";
607
- }
608
- function isLangfuseFetchNetworkError(error) {
609
- return typeof error === "object" && error.name === "LangfuseFetchNetworkError";
610
- }
611
- function isLangfuseFetchError(err) {
612
- return isLangfuseFetchHttpError(err) || isLangfuseFetchNetworkError(err);
613
- }
614
- const SUPPORT_URL = "https://langfuse.com/support";
615
- const API_DOCS_URL = "https://api.reference.langfuse.com";
616
- const RBAC_DOCS_URL = "https://langfuse.com/docs/rbac";
617
- const INSTALLATION_DOCS_URL = "https://langfuse.com/docs/sdk/typescript/guide";
618
- const RATE_LIMITS_URL = "https://langfuse.com/faq/all/api-limits";
619
- const updatePromptResponse = `Make sure to keep your SDK updated, refer to https://www.npmjs.com/package/langfuse for details.`;
620
- const defaultServerErrorPrompt = `This is an unusual occurrence and we are monitoring it closely. For help, please contact support: ${SUPPORT_URL}.`;
621
- const defaultErrorResponse = `Unexpected error occurred. Please check your request and contact support: ${SUPPORT_URL}.`;
622
- const errorResponseByCode = new Map([
623
- [500, `Internal server error occurred. For help, please contact support: ${SUPPORT_URL}`],
624
- [501, `Not implemented. Please check your request and contact support for help: ${SUPPORT_URL}.`],
625
- [502, `Bad gateway. ${defaultServerErrorPrompt}`],
626
- [503, `Service unavailable. ${defaultServerErrorPrompt}`],
627
- [504, `Gateway timeout. ${defaultServerErrorPrompt}`],
628
- [404, `Internal error occurred. ${defaultServerErrorPrompt}`],
629
- [400, `Bad request. Please check your request for any missing or incorrect parameters. Refer to our API docs: ${API_DOCS_URL} for details.`],
630
- [401, `Unauthorized. Please check your public/private host settings. Refer to our installation and setup guide: ${INSTALLATION_DOCS_URL} for details on SDK configuration.`],
631
- [403, `Forbidden. Please check your access control settings. Refer to our RBAC docs: ${RBAC_DOCS_URL} for details.`],
632
- [429, `Rate limit exceeded. For more information on rate limits please see: ${RATE_LIMITS_URL}`]
633
- ]);
634
- function getErrorResponseByCode(code) {
635
- if (!code) return `${defaultErrorResponse} ${updatePromptResponse}`;
636
- return `${code}: ${errorResponseByCode.get(code) || defaultErrorResponse} ${updatePromptResponse}`;
637
- }
638
- function logIngestionError(error) {
639
- if (isLangfuseFetchHttpError(error)) {
640
- const code = error.response.status;
641
- const errorResponse = getErrorResponseByCode(code);
642
- console.error("[Langfuse SDK]", errorResponse, `Error details: ${error}`);
643
- } else if (isLangfuseFetchNetworkError(error)) console.error("[Langfuse SDK] Network error: ", error);
644
- else console.error("[Langfuse SDK] Unknown error:", error);
645
- }
646
- var LangfuseCoreStateless = class {
647
- constructor(params) {
648
- this.additionalHeaders = {};
649
- this.debugMode = false;
650
- this.pendingEventProcessingPromises = {};
651
- this.pendingIngestionPromises = {};
652
- this.localEventExportMap = /* @__PURE__ */ new Map();
653
- this._events = new SimpleEventEmitter();
654
- const { publicKey, secretKey, enabled, _projectId, _isLocalEventExportEnabled, ...options } = params;
655
- this._events.on("error", (payload) => {
656
- console.error(`[Langfuse SDK] ${typeof payload === "string" ? payload : JSON.stringify(payload)}`);
657
- });
658
- this.enabled = enabled === false ? false : true;
659
- this.publicKey = publicKey ?? "";
660
- this.secretKey = secretKey;
661
- this.baseUrl = removeTrailingSlash(options?.baseUrl || "https://cloud.langfuse.com");
662
- this.additionalHeaders = options?.additionalHeaders || {};
663
- this.flushAt = options?.flushAt ? Math.max(options?.flushAt, 1) : 15;
664
- this.flushInterval = options?.flushInterval ?? 1e4;
665
- this.release = options?.release ?? getEnv("LANGFUSE_RELEASE") ?? getCommonReleaseEnvs() ?? void 0;
666
- this.mask = options?.mask;
667
- this.sampleRate = options?.sampleRate ?? (getEnv("LANGFUSE_SAMPLE_RATE") ? Number(getEnv("LANGFUSE_SAMPLE_RATE")) : void 0);
668
- if (this.sampleRate) this._events.emit("debug", `Langfuse trace sampling enabled with sampleRate ${this.sampleRate}.`);
669
- this.environment = options?.environment ?? getEnv("LANGFUSE_TRACING_ENVIRONMENT");
670
- if (this.environment && !(ENVIRONMENT_PATTERN.test(this.environment) || WHITELISTED_LANGFUSE_INTERNAL_ENVIRONMENTS.includes(this.environment)) && !_isLocalEventExportEnabled) this._events.emit("error", `Invalid tracing environment set: ${this.environment} . Environment must match regex ${ENVIRONMENT_PATTERN}. Events will be rejected by Langfuse server.`);
671
- this._retryOptions = {
672
- retryCount: options?.fetchRetryCount ?? 3,
673
- retryDelay: options?.fetchRetryDelay ?? 3e3,
674
- retryCheck: isLangfuseFetchError
675
- };
676
- this.requestTimeout = options?.requestTimeout ?? 5e3;
677
- this.sdkIntegration = options?.sdkIntegration ?? "DEFAULT";
678
- this.isLocalEventExportEnabled = _isLocalEventExportEnabled ?? false;
679
- if (this.isLocalEventExportEnabled && !_projectId) {
680
- this._events.emit("error", "Local event export is enabled, but no project ID was provided. Disabling local export.");
681
- this.isLocalEventExportEnabled = false;
682
- return;
683
- } else if (!this.isLocalEventExportEnabled && _projectId) {
684
- this._events.emit("error", "Local event export is disabled, but a project ID was provided. Disabling local export.");
685
- this.isLocalEventExportEnabled = false;
686
- return;
687
- } else this.projectId = _projectId;
688
- }
689
- getSdkIntegration() {
690
- return this.sdkIntegration;
691
- }
692
- getCommonEventProperties() {
693
- return {
694
- $lib: this.getLibraryId(),
695
- $lib_version: this.getLibraryVersion()
696
- };
697
- }
698
- on(event, cb) {
699
- return this._events.on(event, cb);
700
- }
701
- debug(enabled = true) {
702
- this.removeDebugCallback?.();
703
- this.debugMode = enabled;
704
- if (enabled) this.removeDebugCallback = this.on("*", (event, payload) => {
705
- if (event === "error") return;
706
- console.log("[Langfuse Debug]", event, JSON.stringify(payload));
707
- });
708
- }
709
- /***
710
- *** Handlers for each object type
711
- ***/
712
- traceStateless(body) {
713
- const { id: bodyId, timestamp: bodyTimestamp, release: bodyRelease, ...rest } = body;
714
- const id = bodyId ?? generateUUID();
715
- const parsedBody = {
716
- id,
717
- release: bodyRelease ?? this.release,
718
- timestamp: bodyTimestamp ?? /* @__PURE__ */ new Date(),
719
- environment: this.environment,
720
- ...rest
721
- };
722
- this.enqueue("trace-create", parsedBody);
723
- return id;
724
- }
725
- eventStateless(body) {
726
- const { id: bodyId, startTime: bodyStartTime, ...rest } = body;
727
- const id = bodyId ?? generateUUID();
728
- const parsedBody = {
729
- id,
730
- startTime: bodyStartTime ?? /* @__PURE__ */ new Date(),
731
- environment: this.environment,
732
- ...rest
733
- };
734
- this.enqueue("event-create", parsedBody);
735
- return id;
736
- }
737
- spanStateless(body) {
738
- const { id: bodyId, startTime: bodyStartTime, ...rest } = body;
739
- const id = bodyId || generateUUID();
740
- const parsedBody = {
741
- id,
742
- startTime: bodyStartTime ?? /* @__PURE__ */ new Date(),
743
- environment: this.environment,
744
- ...rest
745
- };
746
- this.enqueue("span-create", parsedBody);
747
- return id;
748
- }
749
- generationStateless(body) {
750
- const { id: bodyId, startTime: bodyStartTime, prompt, ...rest } = body;
751
- const promptDetails = prompt && !prompt.isFallback ? {
752
- promptName: prompt.name,
753
- promptVersion: prompt.version
754
- } : {};
755
- const id = bodyId || generateUUID();
756
- const parsedBody = {
757
- id,
758
- startTime: bodyStartTime ?? /* @__PURE__ */ new Date(),
759
- environment: this.environment,
760
- ...promptDetails,
761
- ...rest
762
- };
763
- this.enqueue("generation-create", parsedBody);
764
- return id;
765
- }
766
- scoreStateless(body) {
767
- const { id: bodyId, ...rest } = body;
768
- const id = bodyId || generateUUID();
769
- const parsedBody = {
770
- id,
771
- environment: this.environment,
772
- ...rest
773
- };
774
- this.enqueue("score-create", parsedBody);
775
- return id;
776
- }
777
- updateSpanStateless(body) {
778
- this.enqueue("span-update", body);
779
- return body.id;
780
- }
781
- updateGenerationStateless(body) {
782
- const { prompt, ...rest } = body;
783
- const parsedBody = {
784
- ...prompt && !prompt.isFallback ? {
785
- promptName: prompt.name,
786
- promptVersion: prompt.version
787
- } : {},
788
- ...rest
789
- };
790
- this.enqueue("generation-update", parsedBody);
791
- return body.id;
792
- }
793
- async _getDataset(name) {
794
- const encodedName = encodeURIComponent(name);
795
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/datasets/${encodedName}`, this._getFetchOptions({ method: "GET" }));
796
- }
797
- async _getDatasetItems(query) {
798
- const params = new URLSearchParams();
799
- Object.entries(query ?? {}).forEach(([key, value]) => {
800
- if (value !== void 0 && value !== null) params.append(key, value.toString());
801
- });
802
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items?${params}`, this._getFetchOptions({ method: "GET" }));
803
- }
804
- async _fetchMedia(id) {
805
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/media/${id}`, this._getFetchOptions({ method: "GET" }));
806
- }
807
- async fetchTraces(query) {
808
- const { data, meta } = await this.fetchAndLogErrors(`${this.baseUrl}/api/public/traces?${encodeQueryParams(query)}`, this._getFetchOptions({ method: "GET" }));
809
- return {
810
- data,
811
- meta
812
- };
813
- }
814
- async fetchTrace(traceId) {
815
- return { data: await this.fetchAndLogErrors(`${this.baseUrl}/api/public/traces/${traceId}`, this._getFetchOptions({ method: "GET" })) };
816
- }
817
- async fetchObservations(query) {
818
- const { data, meta } = await this.fetchAndLogErrors(`${this.baseUrl}/api/public/observations?${encodeQueryParams(query)}`, this._getFetchOptions({ method: "GET" }));
819
- return {
820
- data,
821
- meta
822
- };
823
- }
824
- async fetchObservation(observationId) {
825
- return { data: await this.fetchAndLogErrors(`${this.baseUrl}/api/public/observations/${observationId}`, this._getFetchOptions({ method: "GET" })) };
826
- }
827
- async fetchSessions(query) {
828
- const { data, meta } = await this.fetchAndLogErrors(`${this.baseUrl}/api/public/sessions?${encodeQueryParams(query)}`, this._getFetchOptions({ method: "GET" }));
829
- return {
830
- data,
831
- meta
832
- };
833
- }
834
- async getDatasetRun(params) {
835
- const encodedDatasetName = encodeURIComponent(params.datasetName);
836
- const encodedRunName = encodeURIComponent(params.runName);
837
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets/${encodedDatasetName}/runs/${encodedRunName}`, this._getFetchOptions({ method: "GET" }));
838
- }
839
- async getDatasetRuns(datasetName, query) {
840
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets/${encodeURIComponent(datasetName)}/runs?${encodeQueryParams(query)}`, this._getFetchOptions({ method: "GET" }));
841
- }
842
- async createDatasetRunItem(body) {
843
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-run-items`, this._getFetchOptions({
844
- method: "POST",
845
- body: JSON.stringify(body)
846
- }));
847
- }
848
- /**
849
- * Creates a dataset. Upserts the dataset if it already exists.
850
- *
851
- * @param dataset Can be either a string (name) or an object with name, description and metadata
852
- * @returns A promise that resolves to the response of the create operation.
853
- */
854
- async createDataset(dataset) {
855
- const body = typeof dataset === "string" ? { name: dataset } : dataset;
856
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/datasets`, this._getFetchOptions({
857
- method: "POST",
858
- body: JSON.stringify(body)
859
- }));
860
- }
861
- /**
862
- * Creates a dataset item. Upserts the item if it already exists.
863
- * @param body The body of the dataset item to be created.
864
- * @returns A promise that resolves to the response of the create operation.
865
- */
866
- async createDatasetItem(body) {
867
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items`, this._getFetchOptions({
868
- method: "POST",
869
- body: JSON.stringify(body)
870
- }));
871
- }
872
- async getDatasetItem(id) {
873
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/dataset-items/${id}`, this._getFetchOptions({ method: "GET" }));
874
- }
875
- _parsePayload(response) {
876
- try {
877
- return JSON.parse(response);
878
- } catch {
879
- return response;
880
- }
881
- }
882
- async createPromptStateless(body) {
883
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/prompts`, this._getFetchOptions({
884
- method: "POST",
885
- body: JSON.stringify(body)
886
- }));
887
- }
888
- async updatePromptStateless(body) {
889
- return this.fetchAndLogErrors(`${this.baseUrl}/api/public/v2/prompts/${encodeURIComponent(body.name)}/versions/${encodeURIComponent(body.version)}`, this._getFetchOptions({
890
- method: "PATCH",
891
- body: JSON.stringify(body)
892
- }));
893
- }
894
- async getPromptStateless(name, version, label, maxRetries, requestTimeout) {
895
- const encodedName = encodeURIComponent(name);
896
- const params = new URLSearchParams();
897
- if (version && label) throw new Error("Provide either version or label, not both.");
898
- if (version) params.append("version", version.toString());
899
- if (label) params.append("label", label);
900
- const url = `${this.baseUrl}/api/public/v2/prompts/${encodedName}${params.size ? "?" + params : ""}`;
901
- const boundedMaxRetries = this._getBoundedMaxRetries({
902
- maxRetries,
903
- defaultMaxRetries: 2,
904
- maxRetriesUpperBound: 4
905
- });
906
- const retryOptions = {
907
- ...this._retryOptions,
908
- retryCount: boundedMaxRetries,
909
- retryDelay: 500
910
- };
911
- const retryLogger = (string) => this._events.emit("retry", string + ", " + url + ", " + JSON.stringify(retryOptions));
912
- return retriable(async () => {
913
- const res = await this.fetch(url, this._getFetchOptions({
914
- method: "GET",
915
- fetchTimeout: requestTimeout ?? this.requestTimeout
916
- })).catch((e) => {
917
- if (e.name === "AbortError") throw new LangfuseFetchNetworkError("Fetch request timed out");
918
- throw new LangfuseFetchNetworkError(e);
919
- });
920
- if (res.status >= 500) throw new LangfuseFetchHttpError(res, await res.text());
921
- const data = await res.json();
922
- return {
923
- fetchResult: res.status === 200 ? "success" : "failure",
924
- data
925
- };
926
- }, retryOptions, retryLogger);
927
- }
928
- _getBoundedMaxRetries(params) {
929
- const defaultMaxRetries = Math.max(params.defaultMaxRetries ?? 2, 0);
930
- const maxRetriesUpperBound = Math.max(params.maxRetriesUpperBound ?? 4, 0);
931
- if (params.maxRetries === void 0) return defaultMaxRetries;
932
- return Math.min(Math.max(params.maxRetries, 0), maxRetriesUpperBound);
933
- }
934
- /***
935
- *** QUEUEING AND FLUSHING
936
- ***/
937
- enqueue(type, body) {
938
- if (!this.enabled) return;
939
- const traceId = this.parseTraceId(type, body);
940
- if (!traceId) this._events.emit("warning", "Failed to parse traceID for sampling. Please open a Github issue in https://github.com/langfuse/langfuse/issues/new/choose");
941
- else if (!isInSample(traceId, this.sampleRate)) {
942
- this._events.emit("debug", `Event with trace ID ${traceId} is out of sample. Skipping.`);
943
- return;
944
- }
945
- const promise = this.processEnqueueEvent(type, body);
946
- const promiseId = generateUUID();
947
- this.pendingEventProcessingPromises[promiseId] = promise;
948
- promise.catch((e) => {
949
- this._events.emit("error", e);
950
- }).finally(() => {
951
- delete this.pendingEventProcessingPromises[promiseId];
952
- });
953
- }
954
- async processEnqueueEvent(type, body) {
955
- this.maskEventBodyInPlace(body);
956
- await this.processMediaInEvent(type, body);
957
- const finalEventBody = this.truncateEventBody(body, MAX_EVENT_SIZE_BYTES);
958
- try {
959
- JSON.stringify(finalEventBody);
960
- } catch (e) {
961
- this._events.emit("error", `Event Body for ${type} is not JSON-serializable: ${e}`);
962
- return;
963
- }
964
- const queue = this.getPersistedProperty(LangfusePersistedProperty.Queue) || [];
965
- queue.push({
966
- id: generateUUID(),
967
- type,
968
- timestamp: currentISOTime(),
969
- body: finalEventBody,
970
- metadata: void 0
971
- });
972
- this.setPersistedProperty(LangfusePersistedProperty.Queue, queue);
973
- this._events.emit(type, finalEventBody);
974
- if (queue.length >= this.flushAt) this.flush();
975
- if (this.flushInterval && !this._flushTimer) this._flushTimer = safeSetTimeout(() => this.flush(), this.flushInterval);
976
- }
977
- maskEventBodyInPlace(body) {
978
- if (!this.mask) return;
979
- for (const key of ["input", "output"]) if (key in body) try {
980
- body[key] = this.mask({ data: body[key] });
981
- } catch (e) {
982
- this._events.emit("error", `Error masking ${key}: ${e}`);
983
- body[key] = "<fully masked due to failed mask function>";
984
- }
985
- }
986
- /**
987
- * Truncates the event body if its byte size exceeds the specified maximum byte size.
988
- * Emits a warning event if truncation occurs.
989
- * The fields that may be truncated are: "input", "output", and "metadata".
990
- * The fields are truncated in the order of their size, from largest to smallest until the total byte size is within the limit.
991
- */
992
- truncateEventBody(body, maxByteSize) {
993
- const bodySize = this.getByteSize(body);
994
- if (bodySize <= maxByteSize) return body;
995
- this._events.emit("warning", `Event Body is too large (${bodySize} bytes) and will be truncated`);
996
- const keySizes = [
997
- "input",
998
- "output",
999
- "metadata"
1000
- ].map((key) => ({
1001
- key,
1002
- size: key in body ? this.getByteSize(body[key]) : 0
1003
- })).sort((a, b) => b.size - a.size);
1004
- let result = { ...body };
1005
- let currentSize = bodySize;
1006
- for (const { key, size } of keySizes) if (currentSize > maxByteSize && Object.prototype.hasOwnProperty.call(result, key)) {
1007
- result = {
1008
- ...result,
1009
- [key]: "<truncated due to size exceeding limit>"
1010
- };
1011
- this._events.emit("warning", `Truncated ${key} due to total size exceeding limit`);
1012
- currentSize -= size;
1013
- }
1014
- return result;
1015
- }
1016
- getByteSize(obj) {
1017
- const serialized = JSON.stringify(obj);
1018
- if (typeof TextEncoder !== "undefined") return new TextEncoder().encode(serialized).length;
1019
- else return encodeURIComponent(serialized).replace(/%[A-F\d]{2}/g, "U").length;
1020
- }
1021
- async processMediaInEvent(type, body) {
1022
- if (!body) return;
1023
- const traceId = this.parseTraceId(type, body);
1024
- if (!traceId) {
1025
- this._events.emit("warning", "traceId is required for media upload");
1026
- return;
1027
- }
1028
- const observationId = (type.includes("generation") || type.includes("span")) && body.id ? body.id : void 0;
1029
- await Promise.all([
1030
- "input",
1031
- "output",
1032
- "metadata"
1033
- ].map(async (field) => {
1034
- if (body[field]) body[field] = await this.findAndProcessMedia({
1035
- data: body[field],
1036
- traceId,
1037
- observationId,
1038
- field
1039
- }).catch((e) => {
1040
- this._events.emit("error", `Error processing multimodal event: ${e}`);
1041
- }) ?? body[field];
1042
- }));
1043
- }
1044
- parseTraceId(type, body) {
1045
- return "traceId" in body ? body.traceId : type.includes("trace") ? body.id : void 0;
1046
- }
1047
- async findAndProcessMedia({ data, traceId, observationId, field }) {
1048
- const seenObjects = /* @__PURE__ */ new WeakMap();
1049
- const maxLevels = 10;
1050
- const processRecursively = async (data, level) => {
1051
- if (typeof data === "string" && data.startsWith("data:")) {
1052
- const media = new LangfuseMedia({ base64DataUri: data });
1053
- await this.processMediaItem({
1054
- media,
1055
- traceId,
1056
- observationId,
1057
- field
1058
- });
1059
- return media;
1060
- }
1061
- if (typeof data !== "object" || data === null) return data;
1062
- if (seenObjects.has(data) || level > maxLevels) return data;
1063
- seenObjects.set(data, true);
1064
- if (data instanceof LangfuseMedia || Object.prototype.toString.call(data) === "[object LangfuseMedia]") {
1065
- await this.processMediaItem({
1066
- media: data,
1067
- traceId,
1068
- observationId,
1069
- field
1070
- });
1071
- return data;
1072
- }
1073
- if (Array.isArray(data)) return await Promise.all(data.map((item) => processRecursively(item, level + 1)));
1074
- if (typeof data === "object" && data !== null) {
1075
- if ("input_audio" in data && typeof data["input_audio"] === "object" && "data" in data.input_audio) {
1076
- const media = new LangfuseMedia({ base64DataUri: `data:audio/${data.input_audio["format"] || "wav"};base64,${data.input_audio.data}` });
1077
- await this.processMediaItem({
1078
- media,
1079
- traceId,
1080
- observationId,
1081
- field
1082
- });
1083
- return {
1084
- ...data,
1085
- input_audio: {
1086
- ...data.input_audio,
1087
- data: media
1088
- }
1089
- };
1090
- }
1091
- if ("audio" in data && typeof data["audio"] === "object" && "data" in data.audio) {
1092
- const media = new LangfuseMedia({ base64DataUri: `data:audio/${data.audio["format"] || "wav"};base64,${data.audio.data}` });
1093
- await this.processMediaItem({
1094
- media,
1095
- traceId,
1096
- observationId,
1097
- field
1098
- });
1099
- return {
1100
- ...data,
1101
- audio: {
1102
- ...data.audio,
1103
- data: media
1104
- }
1105
- };
1106
- }
1107
- return Object.fromEntries(await Promise.all(Object.entries(data).map(async ([key, value]) => [key, await processRecursively(value, level + 1)])));
1108
- }
1109
- return data;
1110
- };
1111
- return await processRecursively(data, 1);
1112
- }
1113
- async processMediaItem({ media, traceId, observationId, field }) {
1114
- try {
1115
- if (!media.contentLength || !media._contentType || !media.contentSha256Hash || !media._contentBytes) return;
1116
- const getUploadUrlBody = {
1117
- contentLength: media.contentLength,
1118
- traceId,
1119
- observationId,
1120
- field,
1121
- contentType: media._contentType,
1122
- sha256Hash: media.contentSha256Hash
1123
- };
1124
- const { uploadUrl, mediaId } = await (await this.fetch(`${this.baseUrl}/api/public/media`, this._getFetchOptions({
1125
- method: "POST",
1126
- body: JSON.stringify(getUploadUrlBody)
1127
- }))).json();
1128
- media._mediaId = mediaId;
1129
- if (uploadUrl) {
1130
- this._events.emit("debug", `Uploading media ${mediaId}`);
1131
- const startTime = Date.now();
1132
- const uploadResponse = await this.uploadMediaWithBackoff({
1133
- uploadUrl,
1134
- contentBytes: media._contentBytes,
1135
- contentType: media._contentType,
1136
- contentSha256Hash: media.contentSha256Hash,
1137
- maxRetries: 3,
1138
- baseDelay: 1e3
1139
- });
1140
- if (!uploadResponse) throw Error("Media upload process failed");
1141
- const patchMediaBody = {
1142
- uploadedAt: (/* @__PURE__ */ new Date()).toISOString(),
1143
- uploadHttpStatus: uploadResponse.status,
1144
- uploadHttpError: await uploadResponse.text(),
1145
- uploadTimeMs: Date.now() - startTime
1146
- };
1147
- await this.fetch(`${this.baseUrl}/api/public/media/${mediaId}`, this._getFetchOptions({
1148
- method: "PATCH",
1149
- body: JSON.stringify(patchMediaBody)
1150
- }));
1151
- this._events.emit("debug", `Media upload status reported for ${mediaId}`);
1152
- } else this._events.emit("debug", `Media ${mediaId} already uploaded`);
1153
- } catch (err) {
1154
- this._events.emit("error", `Error processing media item: ${err}`);
1155
- }
1156
- }
1157
- async uploadMediaWithBackoff(params) {
1158
- const { uploadUrl, contentType, contentSha256Hash, contentBytes, maxRetries, baseDelay } = params;
1159
- for (let attempt = 0; attempt <= maxRetries; attempt++) try {
1160
- const uploadResponse = await this.fetch(uploadUrl, {
1161
- method: "PUT",
1162
- body: contentBytes,
1163
- headers: {
1164
- "Content-Type": contentType,
1165
- "x-amz-checksum-sha256": contentSha256Hash,
1166
- "x-ms-blob-type": "BlockBlob"
1167
- }
1168
- });
1169
- if (attempt < maxRetries && uploadResponse.status !== 200 && uploadResponse.status !== 201) throw new Error(`Upload failed with status ${uploadResponse.status}`);
1170
- return uploadResponse;
1171
- } catch (e) {
1172
- if (attempt === maxRetries) throw e;
1173
- const delay = baseDelay * Math.pow(2, attempt);
1174
- const jitter = Math.random() * 1e3;
1175
- await new Promise((resolve) => setTimeout(resolve, delay + jitter));
1176
- }
1177
- }
1178
- /**
1179
- * Asynchronously flushes all events that are not yet sent to the server.
1180
- * This function always resolves, even if there were errors when flushing.
1181
- * Errors are emitted as "error" events and the promise resolves.
1182
- *
1183
- * @returns {Promise<void>} A promise that resolves when the flushing is completed.
1184
- */
1185
- async flushAsync() {
1186
- await Promise.all(Object.values(this.pendingEventProcessingPromises)).catch((e) => {
1187
- logIngestionError(e);
1188
- });
1189
- return new Promise((resolve, _reject) => {
1190
- try {
1191
- this.flush((err, data) => {
1192
- if (err) {
1193
- logIngestionError(err);
1194
- resolve();
1195
- } else resolve(data);
1196
- });
1197
- } catch (e) {
1198
- console.error("[Langfuse SDK] Error while flushing Langfuse", e);
1199
- }
1200
- });
1201
- }
1202
- flush(callback) {
1203
- if (this._flushTimer) {
1204
- clearTimeout(this._flushTimer);
1205
- this._flushTimer = null;
1206
- }
1207
- const queue = this.getPersistedProperty(LangfusePersistedProperty.Queue) || [];
1208
- if (!queue.length) return callback?.();
1209
- const items = queue.splice(0, this.flushAt);
1210
- const { processedItems, remainingItems } = this.processQueueItems(items, MAX_EVENT_SIZE_BYTES, MAX_BATCH_SIZE_BYTES);
1211
- this.setPersistedProperty(LangfusePersistedProperty.Queue, [...remainingItems, ...queue]);
1212
- const promiseUUID = generateUUID();
1213
- const done = (err) => {
1214
- if (err) this._events.emit("warning", err);
1215
- callback?.(err, items);
1216
- this._events.emit("flush", items);
1217
- };
1218
- if (this.isLocalEventExportEnabled && this.projectId) {
1219
- if (!this.localEventExportMap.has(this.projectId)) this.localEventExportMap.set(this.projectId, [...items]);
1220
- else this.localEventExportMap.get(this.projectId)?.push(...items);
1221
- done();
1222
- return;
1223
- }
1224
- const payload = JSON.stringify({
1225
- batch: processedItems,
1226
- metadata: {
1227
- batch_size: processedItems.length,
1228
- sdk_integration: this.sdkIntegration,
1229
- sdk_version: this.getLibraryVersion(),
1230
- sdk_variant: this.getLibraryId(),
1231
- public_key: this.publicKey,
1232
- sdk_name: "langfuse-js"
1233
- }
1234
- });
1235
- const url = `${this.baseUrl}/api/public/ingestion`;
1236
- const fetchOptions = this._getFetchOptions({
1237
- method: "POST",
1238
- body: payload
1239
- });
1240
- const requestPromise = this.fetchWithRetry(url, fetchOptions).then(() => done()).catch((err) => {
1241
- done(err);
1242
- });
1243
- this.pendingIngestionPromises[promiseUUID] = requestPromise;
1244
- requestPromise.finally(() => {
1245
- delete this.pendingIngestionPromises[promiseUUID];
1246
- });
1247
- }
1248
- processQueueItems(queue, MAX_MSG_SIZE, BATCH_SIZE_LIMIT) {
1249
- let totalSize = 0;
1250
- const processedItems = [];
1251
- const remainingItems = [];
1252
- for (let i = 0; i < queue.length; i++) try {
1253
- const itemSize = new Blob([JSON.stringify(queue[i])]).size;
1254
- if (itemSize > MAX_MSG_SIZE) {
1255
- console.warn(`Item exceeds size limit (size: ${itemSize}), dropping item.`);
1256
- continue;
1257
- }
1258
- if (totalSize + itemSize >= BATCH_SIZE_LIMIT) {
1259
- console.debug(`hit batch size limit (size: ${totalSize + itemSize})`);
1260
- remainingItems.push(...queue.slice(i));
1261
- console.log(`Remaining items: ${remainingItems.length}`);
1262
- console.log(`processes items: ${processedItems.length}`);
1263
- break;
1264
- }
1265
- totalSize += itemSize;
1266
- processedItems.push(queue[i]);
1267
- } catch (error) {
1268
- this._events.emit("error", error);
1269
- remainingItems.push(...queue.slice(i));
1270
- break;
1271
- }
1272
- return {
1273
- processedItems,
1274
- remainingItems
1275
- };
1276
- }
1277
- _getFetchOptions(p) {
1278
- return {
1279
- method: p.method,
1280
- headers: {
1281
- "Content-Type": "application/json",
1282
- "X-Langfuse-Sdk-Name": "langfuse-js",
1283
- "X-Langfuse-Sdk-Version": this.getLibraryVersion(),
1284
- "X-Langfuse-Sdk-Variant": this.getLibraryId(),
1285
- "X-Langfuse-Sdk-Integration": this.sdkIntegration,
1286
- "X-Langfuse-Public-Key": this.publicKey,
1287
- ...this.additionalHeaders,
1288
- ...this.constructAuthorizationHeader(this.publicKey, this.secretKey)
1289
- },
1290
- body: p.body,
1291
- ...p.fetchTimeout !== void 0 ? { signal: AbortSignal.timeout(p.fetchTimeout) } : {}
1292
- };
1293
- }
1294
- constructAuthorizationHeader(publicKey, secretKey) {
1295
- if (secretKey === void 0) return { Authorization: "Bearer " + publicKey };
1296
- else return { Authorization: "Basic " + (typeof btoa === "function" ? btoa(publicKey + ":" + secretKey) : Buffer.from(publicKey + ":" + secretKey).toString("base64")) };
1297
- }
1298
- async fetchWithRetry(url, options, retryOptions) {
1299
- AbortSignal.timeout ??= function timeout(ms) {
1300
- const ctrl = new AbortController();
1301
- setTimeout(() => ctrl.abort(), ms);
1302
- return ctrl.signal;
1303
- };
1304
- return await retriable(async () => {
1305
- let res = null;
1306
- try {
1307
- res = await this.fetch(url, {
1308
- signal: AbortSignal.timeout(this.requestTimeout),
1309
- ...options
1310
- });
1311
- } catch (e) {
1312
- throw new LangfuseFetchNetworkError(e);
1313
- }
1314
- if (res.status < 200 || res.status >= 400) {
1315
- const body = await res.json();
1316
- throw new LangfuseFetchHttpError(res, JSON.stringify(body));
1317
- }
1318
- const returnBody = await res.json();
1319
- if (res.status === 207 && returnBody.errors.length > 0) throw new LangfuseFetchHttpError(res, JSON.stringify(returnBody.errors));
1320
- return res;
1321
- }, {
1322
- ...this._retryOptions,
1323
- ...retryOptions
1324
- }, (string) => this._events.emit("retry", string + ", " + url + ", " + JSON.stringify(options)));
1325
- }
1326
- async fetchAndLogErrors(url, options) {
1327
- const res = await this.fetch(url, options);
1328
- const data = res.status === 429 ? await res.text() : await res.json();
1329
- if (res.status < 200 || res.status >= 400) logIngestionError(new LangfuseFetchHttpError(res, JSON.stringify(data)));
1330
- return data;
1331
- }
1332
- async shutdownAsync() {
1333
- clearTimeout(this._flushTimer);
1334
- try {
1335
- await this.flushAsync();
1336
- await Promise.all(Object.values(this.pendingIngestionPromises).map((x) => x.catch(() => {})));
1337
- await this.flushAsync();
1338
- } catch (e) {
1339
- console.error("[Langfuse SDK] Error while shutting down Langfuse", e);
1340
- }
1341
- }
1342
- async _exportLocalEvents(projectId) {
1343
- if (this.isLocalEventExportEnabled) {
1344
- clearTimeout(this._flushTimer);
1345
- await this.flushAsync();
1346
- const events = this.localEventExportMap.get(projectId) ?? [];
1347
- this.localEventExportMap.delete(projectId);
1348
- return events;
1349
- } else {
1350
- this._events.emit("error", "Local event exports are disabled, but _exportLocalEvents() was called.");
1351
- return [];
1352
- }
1353
- }
1354
- shutdown() {
1355
- console.warn("shutdown() is deprecated. It does not wait for all events to be processed. Please use shutdownAsync() instead.");
1356
- this.shutdownAsync();
1357
- }
1358
- async awaitAllQueuedAndPendingRequests() {
1359
- clearTimeout(this._flushTimer);
1360
- await this.flushAsync();
1361
- await Promise.all(Object.values(this.pendingIngestionPromises));
1362
- }
1363
- };
1364
- var LangfuseWebStateless = class extends LangfuseCoreStateless {
1365
- constructor(params) {
1366
- const { flushAt, flushInterval, publicKey, enabled, ...rest } = params;
1367
- let isObservabilityEnabled = enabled === false ? false : true;
1368
- if (isObservabilityEnabled && !publicKey) {
1369
- isObservabilityEnabled = false;
1370
- console.warn("Langfuse public key not passed to constructor and not set as 'LANGFUSE_PUBLIC_KEY' environment variable. No observability data will be sent to Langfuse.");
1371
- }
1372
- super({
1373
- ...rest,
1374
- publicKey,
1375
- flushAt: flushAt ?? 1,
1376
- flushInterval: flushInterval ?? 0,
1377
- enabled: isObservabilityEnabled
1378
- });
1379
- }
1380
- async score(body) {
1381
- this.scoreStateless(body);
1382
- await this.awaitAllQueuedAndPendingRequests();
1383
- return this;
1384
- }
1385
- };
1386
- var LangfuseCore = class extends LangfuseCoreStateless {
1387
- constructor(params) {
1388
- const { publicKey, secretKey, enabled, _isLocalEventExportEnabled } = params;
1389
- let isObservabilityEnabled = enabled === false ? false : true;
1390
- if (_isLocalEventExportEnabled) isObservabilityEnabled = true;
1391
- else if (!secretKey) {
1392
- isObservabilityEnabled = false;
1393
- if (enabled !== false) console.warn("Langfuse secret key was not passed to constructor or not set as 'LANGFUSE_SECRET_KEY' environment variable. No observability data will be sent to Langfuse.");
1394
- } else if (!publicKey) {
1395
- isObservabilityEnabled = false;
1396
- if (enabled !== false) console.warn("Langfuse public key was not passed to constructor or not set as 'LANGFUSE_PUBLIC_KEY' environment variable. No observability data will be sent to Langfuse.");
1397
- }
1398
- super({
1399
- ...params,
1400
- enabled: isObservabilityEnabled
1401
- });
1402
- this._promptCache = new LangfusePromptCache();
1403
- }
1404
- trace(body) {
1405
- const id = this.traceStateless(body ?? {});
1406
- const t = new LangfuseTraceClient(this, id);
1407
- if (getEnv("DEFER") && body) try {
1408
- const deferRuntime = getEnv("__deferRuntime");
1409
- if (deferRuntime) deferRuntime.langfuseTraces([{
1410
- id,
1411
- name: body.name || "",
1412
- url: t.getTraceUrl()
1413
- }]);
1414
- } catch {}
1415
- return t;
1416
- }
1417
- span(body) {
1418
- const traceId = body.traceId || this.traceStateless({ name: body.name });
1419
- const id = this.spanStateless({
1420
- ...body,
1421
- traceId
1422
- });
1423
- return new LangfuseSpanClient(this, id, traceId);
1424
- }
1425
- generation(body) {
1426
- const traceId = body.traceId || this.traceStateless({ name: body.name });
1427
- const id = this.generationStateless({
1428
- ...body,
1429
- traceId
1430
- });
1431
- return new LangfuseGenerationClient(this, id, traceId);
1432
- }
1433
- event(body) {
1434
- const traceId = body.traceId || this.traceStateless({ name: body.name });
1435
- const id = this.eventStateless({
1436
- ...body,
1437
- traceId
1438
- });
1439
- return new LangfuseEventClient(this, id, traceId);
1440
- }
1441
- score(body) {
1442
- this.scoreStateless(body);
1443
- return this;
1444
- }
1445
- async getDataset(name, options) {
1446
- const dataset = await this._getDataset(name);
1447
- const items = [];
1448
- let page = 1;
1449
- while (true) {
1450
- const itemsResponse = await this._getDatasetItems({
1451
- datasetName: name,
1452
- limit: options?.fetchItemsPageSize ?? 50,
1453
- page
1454
- });
1455
- items.push(...itemsResponse.data);
1456
- if (itemsResponse.meta.totalPages <= page) break;
1457
- page++;
1458
- }
1459
- return {
1460
- ...dataset,
1461
- description: dataset.description ?? void 0,
1462
- metadata: dataset.metadata ?? void 0,
1463
- items: items.map((item) => ({
1464
- ...item,
1465
- link: async (obj, runName, runArgs) => {
1466
- await this.awaitAllQueuedAndPendingRequests();
1467
- return await this.createDatasetRunItem({
1468
- runName,
1469
- datasetItemId: item.id,
1470
- observationId: obj.observationId,
1471
- traceId: obj.traceId,
1472
- runDescription: runArgs?.description,
1473
- metadata: runArgs?.metadata
1474
- });
1475
- }
1476
- }))
1477
- };
1478
- }
1479
- async createPrompt(body) {
1480
- const labels = body.labels ?? [];
1481
- const promptResponse = body.type === "chat" ? await this.createPromptStateless({
1482
- ...body,
1483
- prompt: body.prompt.map((item) => {
1484
- if ("type" in item && item.type === ChatMessageType.Placeholder) return {
1485
- type: ChatMessageType.Placeholder,
1486
- name: item.name
1487
- };
1488
- else return {
1489
- type: ChatMessageType.ChatMessage,
1490
- ...item
1491
- };
1492
- }),
1493
- labels: body.isActive ? [...new Set([...labels, "production"])] : labels
1494
- }) : await this.createPromptStateless({
1495
- ...body,
1496
- type: body.type ?? "text",
1497
- labels: body.isActive ? [...new Set([...labels, "production"])] : labels
1498
- });
1499
- if (promptResponse.type === "chat") return new ChatPromptClient(promptResponse);
1500
- return new TextPromptClient(promptResponse);
1501
- }
1502
- async updatePrompt(body) {
1503
- const newPrompt = await this.updatePromptStateless(body);
1504
- this._promptCache.invalidate(body.name);
1505
- return newPrompt;
1506
- }
1507
- async getPrompt(name, version, options) {
1508
- const cacheKey = this._getPromptCacheKey({
1509
- name,
1510
- version,
1511
- label: options?.label
1512
- });
1513
- const cachedPrompt = this._promptCache.getIncludingExpired(cacheKey);
1514
- if (!cachedPrompt || options?.cacheTtlSeconds === 0) try {
1515
- return await this._fetchPromptAndUpdateCache({
1516
- name,
1517
- version,
1518
- label: options?.label,
1519
- cacheTtlSeconds: options?.cacheTtlSeconds,
1520
- maxRetries: options?.maxRetries,
1521
- fetchTimeout: options?.fetchTimeoutMs
1522
- });
1523
- } catch (err) {
1524
- if (options?.fallback) {
1525
- const sharedFallbackParams = {
1526
- name,
1527
- version: version ?? 0,
1528
- labels: options.label ? [options.label] : [],
1529
- cacheTtlSeconds: options?.cacheTtlSeconds,
1530
- config: {},
1531
- tags: []
1532
- };
1533
- if (options.type === "chat") return new ChatPromptClient({
1534
- ...sharedFallbackParams,
1535
- type: "chat",
1536
- prompt: options.fallback.map((msg) => ({
1537
- type: ChatMessageType.ChatMessage,
1538
- ...msg
1539
- }))
1540
- }, true);
1541
- else return new TextPromptClient({
1542
- ...sharedFallbackParams,
1543
- type: "text",
1544
- prompt: options.fallback
1545
- }, true);
1546
- }
1547
- throw err;
1548
- }
1549
- if (cachedPrompt.isExpired) {
1550
- if (!this._promptCache.isRefreshing(cacheKey)) {
1551
- const refreshPromptPromise = this._fetchPromptAndUpdateCache({
1552
- name,
1553
- version,
1554
- label: options?.label,
1555
- cacheTtlSeconds: options?.cacheTtlSeconds,
1556
- maxRetries: options?.maxRetries,
1557
- fetchTimeout: options?.fetchTimeoutMs
1558
- }).catch(() => {
1559
- console.warn(`Failed to refresh prompt cache '${cacheKey}', stale cache will be used until next refresh succeeds.`);
1560
- });
1561
- this._promptCache.addRefreshingPromise(cacheKey, refreshPromptPromise);
1562
- }
1563
- return cachedPrompt.value;
1564
- }
1565
- return cachedPrompt.value;
1566
- }
1567
- _getPromptCacheKey(params) {
1568
- const { name, version, label } = params;
1569
- const parts = [name];
1570
- if (version !== void 0) parts.push("version:" + version.toString());
1571
- else if (label !== void 0) parts.push("label:" + label);
1572
- else parts.push("label:production");
1573
- return parts.join("-");
1574
- }
1575
- async _fetchPromptAndUpdateCache(params) {
1576
- const cacheKey = this._getPromptCacheKey(params);
1577
- try {
1578
- const { name, version, cacheTtlSeconds, label, maxRetries, fetchTimeout } = params;
1579
- const { data, fetchResult } = await this.getPromptStateless(name, version, label, maxRetries, fetchTimeout);
1580
- if (fetchResult === "failure") throw Error(data.message ?? "Internal error while fetching prompt");
1581
- let prompt;
1582
- if (data.type === "chat") prompt = new ChatPromptClient(data);
1583
- else prompt = new TextPromptClient(data);
1584
- this._promptCache.set(cacheKey, prompt, cacheTtlSeconds);
1585
- return prompt;
1586
- } catch (error) {
1587
- console.error(`[Langfuse SDK] Error while fetching prompt '${cacheKey}':`, error);
1588
- throw error;
1589
- }
1590
- }
1591
- async fetchMedia(id) {
1592
- return await this._fetchMedia(id);
1593
- }
1594
- /**
1595
- * Replaces the media reference strings in an object with base64 data URIs for the media content.
1596
- *
1597
- * This method recursively traverses an object (up to a maximum depth of 10) looking for media reference strings
1598
- * in the format "@@@langfuseMedia:...@@@". When found, it fetches the actual media content using the provided
1599
- * Langfuse client and replaces the reference string with a base64 data URI.
1600
- *
1601
- * If fetching media content fails for a reference string, a warning is logged and the reference string is left unchanged.
1602
- *
1603
- * @param params - Configuration object
1604
- * @param params.obj - The object to process. Can be a primitive value, array, or nested object
1605
- * @param params.langfuseClient - Langfuse client instance used to fetch media content
1606
- * @param params.resolveWith - The representation of the media content to replace the media reference string with. Currently only "base64DataUri" is supported.
1607
- * @param params.maxDepth - Optional. Default is 10. The maximum depth to traverse the object.
1608
- *
1609
- * @returns A deep copy of the input object with all media references replaced with base64 data URIs where possible
1610
- *
1611
- * @example
1612
- * ```typescript
1613
- * const obj = {
1614
- * image: "@@@langfuseMedia:type=image/jpeg|id=123|source=bytes@@@",
1615
- * nested: {
1616
- * pdf: "@@@langfuseMedia:type=application/pdf|id=456|source=bytes@@@"
1617
- * }
1618
- * };
1619
- *
1620
- * const result = await LangfuseMedia.resolveMediaReferences({
1621
- * obj,
1622
- * langfuseClient
1623
- * });
1624
- *
1625
- * // Result:
1626
- * // {
1627
- * // image: "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
1628
- * // nested: {
1629
- * // pdf: "data:application/pdf;base64,JVBERi0xLjcK..."
1630
- * // }
1631
- * // }
1632
- * ```
1633
- */
1634
- async resolveMediaReferences(params) {
1635
- const { obj, ...rest } = params;
1636
- return LangfuseMedia.resolveMediaReferences({
1637
- ...rest,
1638
- langfuseClient: this,
1639
- obj
1640
- });
1641
- }
1642
- _updateSpan(body) {
1643
- this.updateSpanStateless(body);
1644
- return this;
1645
- }
1646
- _updateGeneration(body) {
1647
- this.updateGenerationStateless(body);
1648
- return this;
1649
- }
1650
- };
1651
- var LangfuseObjectClient = class {
1652
- constructor({ client, id, traceId, observationId }) {
1653
- this.client = client;
1654
- this.id = id;
1655
- this.traceId = traceId;
1656
- this.observationId = observationId;
1657
- }
1658
- event(body) {
1659
- return this.client.event({
1660
- ...body,
1661
- traceId: this.traceId,
1662
- parentObservationId: this.observationId
1663
- });
1664
- }
1665
- span(body) {
1666
- return this.client.span({
1667
- ...body,
1668
- traceId: this.traceId,
1669
- parentObservationId: this.observationId
1670
- });
1671
- }
1672
- generation(body) {
1673
- return this.client.generation({
1674
- ...body,
1675
- traceId: this.traceId,
1676
- parentObservationId: this.observationId
1677
- });
1678
- }
1679
- score(body) {
1680
- this.client.score({
1681
- ...body,
1682
- traceId: this.traceId,
1683
- observationId: this.observationId
1684
- });
1685
- return this;
1686
- }
1687
- getTraceUrl() {
1688
- return `${this.client.baseUrl}/trace/${this.traceId}`;
1689
- }
1690
- };
1691
- var LangfuseTraceClient = class extends LangfuseObjectClient {
1692
- constructor(client, traceId) {
1693
- super({
1694
- client,
1695
- id: traceId,
1696
- traceId,
1697
- observationId: null
1698
- });
1699
- }
1700
- update(body) {
1701
- this.client.trace({
1702
- ...body,
1703
- id: this.id
1704
- });
1705
- return this;
1706
- }
1707
- };
1708
- var LangfuseObservationClient = class extends LangfuseObjectClient {
1709
- constructor(client, id, traceId) {
1710
- super({
1711
- client,
1712
- id,
1713
- traceId,
1714
- observationId: id
1715
- });
1716
- }
1717
- };
1718
- var LangfuseSpanClient = class extends LangfuseObservationClient {
1719
- constructor(client, id, traceId) {
1720
- super(client, id, traceId);
1721
- }
1722
- update(body) {
1723
- this.client._updateSpan({
1724
- ...body,
1725
- id: this.id,
1726
- traceId: this.traceId
1727
- });
1728
- return this;
1729
- }
1730
- end(body) {
1731
- this.client._updateSpan({
1732
- ...body,
1733
- id: this.id,
1734
- traceId: this.traceId,
1735
- endTime: /* @__PURE__ */ new Date()
1736
- });
1737
- return this;
1738
- }
1739
- };
1740
- var LangfuseGenerationClient = class extends LangfuseObservationClient {
1741
- constructor(client, id, traceId) {
1742
- super(client, id, traceId);
1743
- }
1744
- update(body) {
1745
- this.client._updateGeneration({
1746
- ...body,
1747
- id: this.id,
1748
- traceId: this.traceId
1749
- });
1750
- return this;
1751
- }
1752
- end(body) {
1753
- this.client._updateGeneration({
1754
- ...body,
1755
- id: this.id,
1756
- traceId: this.traceId,
1757
- endTime: /* @__PURE__ */ new Date()
1758
- });
1759
- return this;
1760
- }
1761
- };
1762
- var LangfuseEventClient = class extends LangfuseObservationClient {
1763
- constructor(client, id, traceId) {
1764
- super(client, id, traceId);
1765
- }
1766
- };
1767
-
1768
- //#endregion
1769
- export { LangfuseCore, LangfuseMedia, LangfuseWebStateless, utils };
1770
- //# sourceMappingURL=index.mjs.map