langgraph-ui-components 0.0.4 → 0.0.6

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 (525) hide show
  1. package/dist/index.es10.js +31 -16
  2. package/dist/index.es10.js.map +1 -1
  3. package/dist/index.es100.js +36 -3156
  4. package/dist/index.es100.js.map +1 -1
  5. package/dist/index.es101.js +162 -33
  6. package/dist/index.es101.js.map +1 -1
  7. package/dist/index.es102.js +203 -5
  8. package/dist/index.es102.js.map +1 -1
  9. package/dist/index.es103.js +13 -72
  10. package/dist/index.es103.js.map +1 -1
  11. package/dist/index.es104.js +27 -34
  12. package/dist/index.es104.js.map +1 -1
  13. package/dist/index.es105.js +34 -5
  14. package/dist/index.es105.js.map +1 -1
  15. package/dist/index.es106.js +3159 -2
  16. package/dist/index.es106.js.map +1 -1
  17. package/dist/index.es107.js +5 -11
  18. package/dist/index.es107.js.map +1 -1
  19. package/dist/index.es108.js +2 -503
  20. package/dist/index.es108.js.map +1 -1
  21. package/dist/index.es109.js +16 -5
  22. package/dist/index.es109.js.map +1 -1
  23. package/dist/index.es11.js +146 -120
  24. package/dist/index.es11.js.map +1 -1
  25. package/dist/index.es110.js +13 -2
  26. package/dist/index.es110.js.map +1 -1
  27. package/dist/index.es111.js +484 -129
  28. package/dist/index.es111.js.map +1 -1
  29. package/dist/index.es112.js +5 -906
  30. package/dist/index.es112.js.map +1 -1
  31. package/dist/index.es113.js +2 -282
  32. package/dist/index.es113.js.map +1 -1
  33. package/dist/index.es114.js +148 -4
  34. package/dist/index.es114.js.map +1 -1
  35. package/dist/index.es115.js +869 -407
  36. package/dist/index.es115.js.map +1 -1
  37. package/dist/index.es116.js +274 -40
  38. package/dist/index.es116.js.map +1 -1
  39. package/dist/index.es117.js +4 -24
  40. package/dist/index.es117.js.map +1 -1
  41. package/dist/index.es118.js +437 -72
  42. package/dist/index.es118.js.map +1 -1
  43. package/dist/index.es119.js +42 -125
  44. package/dist/index.es119.js.map +1 -1
  45. package/dist/index.es12.js +13 -103
  46. package/dist/index.es12.js.map +1 -1
  47. package/dist/index.es120.js +21 -48
  48. package/dist/index.es120.js.map +1 -1
  49. package/dist/index.es121.js +77 -8
  50. package/dist/index.es121.js.map +1 -1
  51. package/dist/index.es122.js +127 -43
  52. package/dist/index.es122.js.map +1 -1
  53. package/dist/index.es123.js +41 -91
  54. package/dist/index.es123.js.map +1 -1
  55. package/dist/index.es124.js +9 -52
  56. package/dist/index.es124.js.map +1 -1
  57. package/dist/index.es125.js +44 -15
  58. package/dist/index.es125.js.map +1 -1
  59. package/dist/index.es126.js +97 -13
  60. package/dist/index.es126.js.map +1 -1
  61. package/dist/index.es127.js +52 -88
  62. package/dist/index.es127.js.map +1 -1
  63. package/dist/index.es128.js +15 -2
  64. package/dist/index.es128.js.map +1 -1
  65. package/dist/index.es129.js +87 -54
  66. package/dist/index.es129.js.map +1 -1
  67. package/dist/index.es13.js +126 -32
  68. package/dist/index.es13.js.map +1 -1
  69. package/dist/index.es130.js +2 -100
  70. package/dist/index.es130.js.map +1 -1
  71. package/dist/index.es131.js +163 -190
  72. package/dist/index.es131.js.map +1 -1
  73. package/dist/index.es132.js +2 -110
  74. package/dist/index.es132.js.map +1 -1
  75. package/dist/index.es133.js +53 -32
  76. package/dist/index.es133.js.map +1 -1
  77. package/dist/index.es134.js +99 -9
  78. package/dist/index.es134.js.map +1 -1
  79. package/dist/index.es135.js +190 -10
  80. package/dist/index.es135.js.map +1 -1
  81. package/dist/index.es136.js +108 -10
  82. package/dist/index.es136.js.map +1 -1
  83. package/dist/index.es137.js +30 -86
  84. package/dist/index.es137.js.map +1 -1
  85. package/dist/index.es138.js +10 -275
  86. package/dist/index.es138.js.map +1 -1
  87. package/dist/index.es139.js +11 -2
  88. package/dist/index.es139.js.map +1 -1
  89. package/dist/index.es140.js +11 -163
  90. package/dist/index.es140.js.map +1 -1
  91. package/dist/index.es141.js +87 -47
  92. package/dist/index.es141.js.map +1 -1
  93. package/dist/index.es142.js +266 -31
  94. package/dist/index.es142.js.map +1 -1
  95. package/dist/index.es143.js +2 -35
  96. package/dist/index.es143.js.map +1 -1
  97. package/dist/index.es144.js +155 -31
  98. package/dist/index.es144.js.map +1 -1
  99. package/dist/index.es145.js +48 -21
  100. package/dist/index.es145.js.map +1 -1
  101. package/dist/index.es146.js +33 -584
  102. package/dist/index.es146.js.map +1 -1
  103. package/dist/index.es147.js +34 -124
  104. package/dist/index.es147.js.map +1 -1
  105. package/dist/index.es148.js +31 -155
  106. package/dist/index.es148.js.map +1 -1
  107. package/dist/index.es149.js +24 -2
  108. package/dist/index.es149.js.map +1 -1
  109. package/dist/index.es15.js +15 -15
  110. package/dist/index.es150.js +591 -2
  111. package/dist/index.es150.js.map +1 -1
  112. package/dist/index.es151.js +125 -2
  113. package/dist/index.es151.js.map +1 -1
  114. package/dist/index.es152.js +3 -21
  115. package/dist/index.es152.js.map +1 -1
  116. package/dist/index.es153.js +2 -2
  117. package/dist/index.es154.js +2 -25
  118. package/dist/index.es154.js.map +1 -1
  119. package/dist/index.es155.js +22 -8
  120. package/dist/index.es155.js.map +1 -1
  121. package/dist/index.es156.js +2 -5
  122. package/dist/index.es156.js.map +1 -1
  123. package/dist/index.es157.js +24 -12
  124. package/dist/index.es157.js.map +1 -1
  125. package/dist/index.es158.js +5 -6
  126. package/dist/index.es158.js.map +1 -1
  127. package/dist/index.es159.js +12 -63
  128. package/dist/index.es159.js.map +1 -1
  129. package/dist/index.es160.js +5 -21
  130. package/dist/index.es160.js.map +1 -1
  131. package/dist/index.es161.js +8 -6
  132. package/dist/index.es161.js.map +1 -1
  133. package/dist/index.es162.js +22 -346
  134. package/dist/index.es162.js.map +1 -1
  135. package/dist/index.es163.js +12 -25
  136. package/dist/index.es163.js.map +1 -1
  137. package/dist/index.es164.js +53 -11
  138. package/dist/index.es164.js.map +1 -1
  139. package/dist/index.es165.js +59 -49
  140. package/dist/index.es165.js.map +1 -1
  141. package/dist/index.es166.js +22 -7
  142. package/dist/index.es166.js.map +1 -1
  143. package/dist/index.es167.js +5 -102
  144. package/dist/index.es167.js.map +1 -1
  145. package/dist/index.es168.js +339 -109
  146. package/dist/index.es168.js.map +1 -1
  147. package/dist/index.es169.js +7 -136
  148. package/dist/index.es169.js.map +1 -1
  149. package/dist/index.es17.js +2 -2
  150. package/dist/index.es170.js +97 -109
  151. package/dist/index.es170.js.map +1 -1
  152. package/dist/index.es171.js +119 -6
  153. package/dist/index.es171.js.map +1 -1
  154. package/dist/index.es172.js +136 -4
  155. package/dist/index.es172.js.map +1 -1
  156. package/dist/index.es173.js +115 -2
  157. package/dist/index.es173.js.map +1 -1
  158. package/dist/index.es174.js +6 -3737
  159. package/dist/index.es174.js.map +1 -1
  160. package/dist/index.es175.js +2 -342
  161. package/dist/index.es175.js.map +1 -1
  162. package/dist/index.es176.js +138 -105
  163. package/dist/index.es176.js.map +1 -1
  164. package/dist/index.es177.js +2 -133
  165. package/dist/index.es177.js.map +1 -1
  166. package/dist/index.es178.js +3734 -12
  167. package/dist/index.es178.js.map +1 -1
  168. package/dist/index.es179.js +326 -136
  169. package/dist/index.es179.js.map +1 -1
  170. package/dist/index.es180.js +107 -13
  171. package/dist/index.es180.js.map +1 -1
  172. package/dist/index.es181.js +131 -6
  173. package/dist/index.es181.js.map +1 -1
  174. package/dist/index.es182.js +13 -19
  175. package/dist/index.es182.js.map +1 -1
  176. package/dist/index.es183.js +139 -77
  177. package/dist/index.es183.js.map +1 -1
  178. package/dist/index.es184.js +13 -241
  179. package/dist/index.es184.js.map +1 -1
  180. package/dist/index.es185.js +8 -24
  181. package/dist/index.es185.js.map +1 -1
  182. package/dist/index.es186.js +21 -6
  183. package/dist/index.es186.js.map +1 -1
  184. package/dist/index.es187.js +90 -4
  185. package/dist/index.es187.js.map +1 -1
  186. package/dist/index.es188.js +240 -15
  187. package/dist/index.es188.js.map +1 -1
  188. package/dist/index.es189.js +24 -8
  189. package/dist/index.es189.js.map +1 -1
  190. package/dist/index.es190.js +6 -142
  191. package/dist/index.es190.js.map +1 -1
  192. package/dist/index.es191.js +4 -2
  193. package/dist/index.es191.js.map +1 -1
  194. package/dist/index.es192.js +18 -32
  195. package/dist/index.es192.js.map +1 -1
  196. package/dist/index.es193.js +8 -6
  197. package/dist/index.es193.js.map +1 -1
  198. package/dist/index.es194.js +31 -105
  199. package/dist/index.es194.js.map +1 -1
  200. package/dist/index.es195.js +6 -13
  201. package/dist/index.es195.js.map +1 -1
  202. package/dist/index.es196.js +105 -17
  203. package/dist/index.es196.js.map +1 -1
  204. package/dist/index.es197.js +11 -29
  205. package/dist/index.es197.js.map +1 -1
  206. package/dist/index.es198.js +17 -3
  207. package/dist/index.es198.js.map +1 -1
  208. package/dist/index.es199.js +30 -4
  209. package/dist/index.es199.js.map +1 -1
  210. package/dist/index.es2.js +24 -15
  211. package/dist/index.es2.js.map +1 -1
  212. package/dist/index.es20.js +35 -66
  213. package/dist/index.es20.js.map +1 -1
  214. package/dist/index.es200.js +4 -5
  215. package/dist/index.es200.js.map +1 -1
  216. package/dist/index.es201.js +4 -36
  217. package/dist/index.es201.js.map +1 -1
  218. package/dist/index.es202.js +5 -8
  219. package/dist/index.es202.js.map +1 -1
  220. package/dist/index.es203.js +36 -5
  221. package/dist/index.es203.js.map +1 -1
  222. package/dist/index.es204.js +5 -4
  223. package/dist/index.es204.js.map +1 -1
  224. package/dist/index.es205.js +5 -41
  225. package/dist/index.es205.js.map +1 -1
  226. package/dist/index.es206.js +4 -10
  227. package/dist/index.es206.js.map +1 -1
  228. package/dist/index.es207.js +39 -239
  229. package/dist/index.es207.js.map +1 -1
  230. package/dist/index.es208.js +10 -48
  231. package/dist/index.es208.js.map +1 -1
  232. package/dist/index.es209.js +239 -32
  233. package/dist/index.es209.js.map +1 -1
  234. package/dist/index.es21.js +25 -34
  235. package/dist/index.es21.js.map +1 -1
  236. package/dist/index.es210.js +49 -11
  237. package/dist/index.es210.js.map +1 -1
  238. package/dist/index.es211.js +33 -6
  239. package/dist/index.es211.js.map +1 -1
  240. package/dist/index.es212.js +12 -6
  241. package/dist/index.es212.js.map +1 -1
  242. package/dist/index.es213.js +7 -64
  243. package/dist/index.es213.js.map +1 -1
  244. package/dist/index.es214.js +6 -40
  245. package/dist/index.es214.js.map +1 -1
  246. package/dist/index.es215.js +63 -30
  247. package/dist/index.es215.js.map +1 -1
  248. package/dist/index.es216.js +35 -56
  249. package/dist/index.es216.js.map +1 -1
  250. package/dist/index.es217.js +32 -15
  251. package/dist/index.es217.js.map +1 -1
  252. package/dist/index.es218.js +60 -21
  253. package/dist/index.es218.js.map +1 -1
  254. package/dist/index.es219.js +15 -5
  255. package/dist/index.es219.js.map +1 -1
  256. package/dist/index.es22.js +146 -27
  257. package/dist/index.es22.js.map +1 -1
  258. package/dist/index.es220.js +21 -15
  259. package/dist/index.es220.js.map +1 -1
  260. package/dist/index.es221.js +4 -32
  261. package/dist/index.es221.js.map +1 -1
  262. package/dist/index.es222.js +16 -4
  263. package/dist/index.es222.js.map +1 -1
  264. package/dist/index.es223.js +32 -4
  265. package/dist/index.es223.js.map +1 -1
  266. package/dist/index.es224.js +5 -5
  267. package/dist/index.es224.js.map +1 -1
  268. package/dist/index.es225.js +4 -7
  269. package/dist/index.es225.js.map +1 -1
  270. package/dist/index.es226.js +4 -91
  271. package/dist/index.es226.js.map +1 -1
  272. package/dist/index.es227.js +7 -17
  273. package/dist/index.es227.js.map +1 -1
  274. package/dist/index.es228.js +90 -760
  275. package/dist/index.es228.js.map +1 -1
  276. package/dist/index.es229.js +18 -66
  277. package/dist/index.es229.js.map +1 -1
  278. package/dist/index.es23.js +16 -146
  279. package/dist/index.es23.js.map +1 -1
  280. package/dist/index.es230.js +749 -161
  281. package/dist/index.es230.js.map +1 -1
  282. package/dist/index.es231.js +66 -38
  283. package/dist/index.es231.js.map +1 -1
  284. package/dist/index.es232.js +172 -135
  285. package/dist/index.es232.js.map +1 -1
  286. package/dist/index.es233.js +136 -92
  287. package/dist/index.es233.js.map +1 -1
  288. package/dist/index.es234.js +92 -32
  289. package/dist/index.es234.js.map +1 -1
  290. package/dist/index.es235.js +32 -284
  291. package/dist/index.es235.js.map +1 -1
  292. package/dist/index.es236.js +284 -25
  293. package/dist/index.es236.js.map +1 -1
  294. package/dist/index.es237.js +22 -20
  295. package/dist/index.es237.js.map +1 -1
  296. package/dist/index.es238.js +22 -13
  297. package/dist/index.es238.js.map +1 -1
  298. package/dist/index.es239.js +12 -12
  299. package/dist/index.es239.js.map +1 -1
  300. package/dist/index.es24.js +58 -295
  301. package/dist/index.es24.js.map +1 -1
  302. package/dist/index.es240.js +13 -24
  303. package/dist/index.es240.js.map +1 -1
  304. package/dist/index.es241.js +22 -42
  305. package/dist/index.es241.js.map +1 -1
  306. package/dist/index.es242.js +45 -11
  307. package/dist/index.es242.js.map +1 -1
  308. package/dist/index.es243.js +10 -10
  309. package/dist/index.es243.js.map +1 -1
  310. package/dist/index.es244.js +10 -10
  311. package/dist/index.es244.js.map +1 -1
  312. package/dist/index.es245.js +11 -14
  313. package/dist/index.es245.js.map +1 -1
  314. package/dist/index.es246.js +14 -11
  315. package/dist/index.es246.js.map +1 -1
  316. package/dist/index.es247.js +11 -11
  317. package/dist/index.es247.js.map +1 -1
  318. package/dist/index.es248.js +10 -10
  319. package/dist/index.es248.js.map +1 -1
  320. package/dist/index.es249.js +11 -15
  321. package/dist/index.es249.js.map +1 -1
  322. package/dist/index.es25.js +298 -114
  323. package/dist/index.es25.js.map +1 -1
  324. package/dist/index.es250.js +15 -11
  325. package/dist/index.es250.js.map +1 -1
  326. package/dist/index.es251.js +10 -10
  327. package/dist/index.es251.js.map +1 -1
  328. package/dist/index.es252.js +11 -11
  329. package/dist/index.es252.js.map +1 -1
  330. package/dist/index.es253.js +10 -10
  331. package/dist/index.es253.js.map +1 -1
  332. package/dist/index.es254.js +10 -10
  333. package/dist/index.es254.js.map +1 -1
  334. package/dist/index.es255.js +10 -10
  335. package/dist/index.es255.js.map +1 -1
  336. package/dist/index.es256.js +10 -10
  337. package/dist/index.es256.js.map +1 -1
  338. package/dist/index.es257.js +10 -10
  339. package/dist/index.es257.js.map +1 -1
  340. package/dist/index.es258.js +11 -56
  341. package/dist/index.es258.js.map +1 -1
  342. package/dist/index.es259.js +53 -46
  343. package/dist/index.es259.js.map +1 -1
  344. package/dist/index.es26.js +121 -5
  345. package/dist/index.es26.js.map +1 -1
  346. package/dist/index.es260.js +42 -112
  347. package/dist/index.es260.js.map +1 -1
  348. package/dist/index.es261.js +87 -352
  349. package/dist/index.es261.js.map +1 -1
  350. package/dist/index.es262.js +381 -15
  351. package/dist/index.es262.js.map +1 -1
  352. package/dist/index.es263.js +17 -10
  353. package/dist/index.es263.js.map +1 -1
  354. package/dist/index.es264.js +10 -30
  355. package/dist/index.es264.js.map +1 -1
  356. package/dist/index.es265.js +17 -17
  357. package/dist/index.es265.js.map +1 -1
  358. package/dist/index.es266.js +25 -56
  359. package/dist/index.es266.js.map +1 -1
  360. package/dist/index.es267.js +59 -14
  361. package/dist/index.es267.js.map +1 -1
  362. package/dist/index.es268.js +14 -74
  363. package/dist/index.es268.js.map +1 -1
  364. package/dist/index.es269.js +77 -11
  365. package/dist/index.es269.js.map +1 -1
  366. package/dist/index.es270.js +10 -10
  367. package/dist/index.es270.js.map +1 -1
  368. package/dist/index.es271.js +11 -15
  369. package/dist/index.es271.js.map +1 -1
  370. package/dist/index.es272.js +14 -51
  371. package/dist/index.es272.js.map +1 -1
  372. package/dist/index.es273.js +44 -158
  373. package/dist/index.es273.js.map +1 -1
  374. package/dist/index.es274.js +167 -2
  375. package/dist/index.es274.js.map +1 -1
  376. package/dist/index.es275.js +37 -10
  377. package/dist/index.es275.js.map +1 -1
  378. package/dist/index.es276.js +2 -20
  379. package/dist/index.es276.js.map +1 -1
  380. package/dist/index.es277.js +10 -38
  381. package/dist/index.es277.js.map +1 -1
  382. package/dist/index.es278.js +23 -0
  383. package/dist/index.es278.js.map +1 -0
  384. package/dist/index.es279.js +42 -0
  385. package/dist/index.es279.js.map +1 -0
  386. package/dist/index.es28.js +7 -7
  387. package/dist/index.es29.js +1 -1
  388. package/dist/index.es32.js +4 -4
  389. package/dist/index.es33.js +117 -13
  390. package/dist/index.es33.js.map +1 -1
  391. package/dist/index.es34.js +65 -112
  392. package/dist/index.es34.js.map +1 -1
  393. package/dist/index.es35.js +18 -71
  394. package/dist/index.es35.js.map +1 -1
  395. package/dist/index.es36.js +260 -17
  396. package/dist/index.es36.js.map +1 -1
  397. package/dist/index.es37.js +31 -249
  398. package/dist/index.es37.js.map +1 -1
  399. package/dist/index.es38.js +199 -27
  400. package/dist/index.es38.js.map +1 -1
  401. package/dist/index.es39.js +50 -198
  402. package/dist/index.es39.js.map +1 -1
  403. package/dist/index.es40.js +120 -45
  404. package/dist/index.es40.js.map +1 -1
  405. package/dist/index.es41.js +14 -132
  406. package/dist/index.es41.js.map +1 -1
  407. package/dist/index.es42.js +225 -19
  408. package/dist/index.es42.js.map +1 -1
  409. package/dist/index.es43.js +8 -229
  410. package/dist/index.es43.js.map +1 -1
  411. package/dist/index.es44.js +1190 -7
  412. package/dist/index.es44.js.map +1 -1
  413. package/dist/index.es45.js +6 -1191
  414. package/dist/index.es45.js.map +1 -1
  415. package/dist/index.es46.js +146 -6
  416. package/dist/index.es46.js.map +1 -1
  417. package/dist/index.es47.js +15 -146
  418. package/dist/index.es47.js.map +1 -1
  419. package/dist/index.es49.js +5 -93
  420. package/dist/index.es49.js.map +1 -1
  421. package/dist/index.es50.js +8 -4
  422. package/dist/index.es50.js.map +1 -1
  423. package/dist/index.es51.js +91 -33
  424. package/dist/index.es51.js.map +1 -1
  425. package/dist/index.es52.js +3 -71
  426. package/dist/index.es52.js.map +1 -1
  427. package/dist/index.es53.js +34 -36
  428. package/dist/index.es53.js.map +1 -1
  429. package/dist/index.es54.js +61 -295
  430. package/dist/index.es54.js.map +1 -1
  431. package/dist/index.es55.js +38 -9
  432. package/dist/index.es55.js.map +1 -1
  433. package/dist/index.es56.js +296 -81
  434. package/dist/index.es56.js.map +1 -1
  435. package/dist/index.es57.js +9 -8
  436. package/dist/index.es57.js.map +1 -1
  437. package/dist/index.es58.js +89 -13
  438. package/dist/index.es58.js.map +1 -1
  439. package/dist/index.es59.js +6 -141
  440. package/dist/index.es59.js.map +1 -1
  441. package/dist/index.es60.js +12 -297
  442. package/dist/index.es60.js.map +1 -1
  443. package/dist/index.es61.js +137 -60
  444. package/dist/index.es61.js.map +1 -1
  445. package/dist/index.es62.js +247 -160
  446. package/dist/index.es62.js.map +1 -1
  447. package/dist/index.es63.js +63 -31
  448. package/dist/index.es63.js.map +1 -1
  449. package/dist/index.es64.js +212 -8
  450. package/dist/index.es64.js.map +1 -1
  451. package/dist/index.es65.js +32 -10
  452. package/dist/index.es65.js.map +1 -1
  453. package/dist/index.es66.js +8 -186
  454. package/dist/index.es66.js.map +1 -1
  455. package/dist/index.es67.js +11 -23
  456. package/dist/index.es67.js.map +1 -1
  457. package/dist/index.es68.js +183 -1396
  458. package/dist/index.es68.js.map +1 -1
  459. package/dist/index.es69.js +24 -9
  460. package/dist/index.es69.js.map +1 -1
  461. package/dist/index.es70.js +1400 -8
  462. package/dist/index.es70.js.map +1 -1
  463. package/dist/index.es71.js +9 -6
  464. package/dist/index.es71.js.map +1 -1
  465. package/dist/index.es72.js +8 -163
  466. package/dist/index.es72.js.map +1 -1
  467. package/dist/index.es73.js +6 -672
  468. package/dist/index.es73.js.map +1 -1
  469. package/dist/index.es74.js +161 -10
  470. package/dist/index.es74.js.map +1 -1
  471. package/dist/index.es75.js +671 -39
  472. package/dist/index.es75.js.map +1 -1
  473. package/dist/index.es76.js +10 -32
  474. package/dist/index.es76.js.map +1 -1
  475. package/dist/index.es77.js +31 -223
  476. package/dist/index.es77.js.map +1 -1
  477. package/dist/index.es78.js +33 -29
  478. package/dist/index.es78.js.map +1 -1
  479. package/dist/index.es79.js +193 -36
  480. package/dist/index.es79.js.map +1 -1
  481. package/dist/index.es80.js +26 -72
  482. package/dist/index.es80.js.map +1 -1
  483. package/dist/index.es81.js +70 -47
  484. package/dist/index.es81.js.map +1 -1
  485. package/dist/index.es82.js +72 -26
  486. package/dist/index.es82.js.map +1 -1
  487. package/dist/index.es83.js +37 -28
  488. package/dist/index.es83.js.map +1 -1
  489. package/dist/index.es84.js +28 -55
  490. package/dist/index.es84.js.map +1 -1
  491. package/dist/index.es85.js +43 -13
  492. package/dist/index.es85.js.map +1 -1
  493. package/dist/index.es86.js +32 -132
  494. package/dist/index.es86.js.map +1 -1
  495. package/dist/index.es87.js +5 -21
  496. package/dist/index.es87.js.map +1 -1
  497. package/dist/index.es88.js +61 -170
  498. package/dist/index.es88.js.map +1 -1
  499. package/dist/index.es89.js +31 -235
  500. package/dist/index.es89.js.map +1 -1
  501. package/dist/index.es90.js +50 -348
  502. package/dist/index.es90.js.map +1 -1
  503. package/dist/index.es91.js +13 -137
  504. package/dist/index.es91.js.map +1 -1
  505. package/dist/index.es92.js +132 -65
  506. package/dist/index.es92.js.map +1 -1
  507. package/dist/index.es93.js +21 -37
  508. package/dist/index.es93.js.map +1 -1
  509. package/dist/index.es94.js +179 -34
  510. package/dist/index.es94.js.map +1 -1
  511. package/dist/index.es95.js +230 -155
  512. package/dist/index.es95.js.map +1 -1
  513. package/dist/index.es96.js +341 -189
  514. package/dist/index.es96.js.map +1 -1
  515. package/dist/index.es97.js +136 -13
  516. package/dist/index.es97.js.map +1 -1
  517. package/dist/index.es98.js +68 -28
  518. package/dist/index.es98.js.map +1 -1
  519. package/dist/index.es99.js +33 -30
  520. package/dist/index.es99.js.map +1 -1
  521. package/dist/langgraph-ui-components.css +107 -0
  522. package/dist/styles.css +1 -1
  523. package/package.json +8 -11
  524. package/dist/index.es48.js +0 -11
  525. package/dist/index.es48.js.map +0 -1
@@ -1,3740 +1,9 @@
1
- import * as uuid from "uuid";
2
- import { LangSmithToOTELTranslator } from "./index.es175.js";
3
- import { getOTELTrace, getOTELContext, getDefaultOTLPTracerComponents } from "./index.es176.js";
4
- import { AsyncCaller } from "./index.es177.js";
5
- import { isLangChainMessage, convertLangChainMessageToExample } from "./index.es178.js";
6
- import { getEnvironmentVariable, getLangSmithEnvironmentVariable, getOtelEnabled, getLangSmithEnvVarsMetadata, getEnv, getRuntimeEnvironment } from "./index.es179.js";
7
- import { __version__ } from "./index.es155.js";
8
- import { assertUuid } from "./index.es180.js";
9
- import { warnOnce } from "./index.es181.js";
10
- import { parsePromptIdentifier } from "./index.es182.js";
11
- import { raiseForStatus, isLangSmithNotFoundError } from "./index.es183.js";
12
- import { Cache } from "./index.es184.js";
13
- import { _getFetchImplementation, _globalFetchImplementationIsNodeFetch } from "./index.es185.js";
14
- import { serialize } from "./index.es111.js";
15
- function mergeRuntimeEnvIntoRun(run, cachedEnvVars, omitTracedRuntimeInfo) {
16
- if (omitTracedRuntimeInfo) {
17
- return run;
18
- }
19
- const runtimeEnv = getRuntimeEnvironment();
20
- const envVars = cachedEnvVars ?? getLangSmithEnvVarsMetadata();
21
- const extra = run.extra ?? {};
22
- const metadata = extra.metadata;
23
- run.extra = {
24
- ...extra,
25
- runtime: {
26
- ...runtimeEnv,
27
- ...extra?.runtime
28
- },
29
- metadata: {
30
- ...envVars,
31
- ...envVars.revision_id || "revision_id" in run && run.revision_id ? {
32
- revision_id: ("revision_id" in run ? run.revision_id : void 0) ?? envVars.revision_id
33
- } : {},
34
- ...metadata
35
- }
36
- };
37
- return run;
38
- }
39
- const getTracingSamplingRate = (configRate) => {
40
- const samplingRateStr = configRate?.toString() ?? getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE");
41
- if (samplingRateStr === void 0) {
42
- return void 0;
43
- }
44
- const samplingRate = parseFloat(samplingRateStr);
45
- if (samplingRate < 0 || samplingRate > 1) {
46
- throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`);
47
- }
48
- return samplingRate;
49
- };
50
- const isLocalhost = (url) => {
51
- const strippedUrl = url.replace("http://", "").replace("https://", "");
52
- const hostname = strippedUrl.split("/")[0].split(":")[0];
53
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1";
54
- };
55
- async function toArray(iterable) {
56
- const result = [];
57
- for await (const item of iterable) {
58
- result.push(item);
59
- }
60
- return result;
61
- }
62
- function trimQuotes(str) {
63
- if (str === void 0) {
64
- return void 0;
65
- }
66
- return str.trim().replace(/^"(.*)"$/, "$1").replace(/^'(.*)'$/, "$1");
67
- }
68
- const handle429 = async (response) => {
69
- if (response?.status === 429) {
70
- const retryAfter = parseInt(response.headers.get("retry-after") ?? "10", 10) * 1e3;
71
- if (retryAfter > 0) {
72
- await new Promise((resolve) => setTimeout(resolve, retryAfter));
73
- return true;
74
- }
75
- }
76
- return false;
77
- };
78
- function _formatFeedbackScore(score) {
79
- if (typeof score === "number") {
80
- return Number(score.toFixed(4));
81
- }
82
- return score;
83
- }
84
- const DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES = 24 * 1024 * 1024;
85
- const DEFAULT_MAX_SIZE_BYTES = 1024 * 1024 * 1024;
86
- const SERVER_INFO_REQUEST_TIMEOUT_MS = 1e4;
87
- const DEFAULT_BATCH_SIZE_LIMIT = 100;
88
- const DEFAULT_API_URL = "https://api.smith.langchain.com";
89
- class AutoBatchQueue {
90
- constructor(maxSizeBytes) {
91
- Object.defineProperty(this, "items", {
92
- enumerable: true,
93
- configurable: true,
94
- writable: true,
95
- value: []
96
- });
97
- Object.defineProperty(this, "sizeBytes", {
98
- enumerable: true,
99
- configurable: true,
100
- writable: true,
101
- value: 0
102
- });
103
- Object.defineProperty(this, "maxSizeBytes", {
104
- enumerable: true,
105
- configurable: true,
106
- writable: true,
107
- value: void 0
108
- });
109
- this.maxSizeBytes = maxSizeBytes ?? DEFAULT_MAX_SIZE_BYTES;
110
- }
111
- peek() {
112
- return this.items[0];
113
- }
114
- push(item) {
115
- let itemPromiseResolve;
116
- const itemPromise = new Promise((resolve) => {
117
- itemPromiseResolve = resolve;
118
- });
119
- const size = serialize(item.item, `Serializing run with id: ${item.item.id}`).length;
120
- if (this.sizeBytes + size > this.maxSizeBytes && this.items.length > 0) {
121
- console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${item.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${size} bytes.`);
122
- itemPromiseResolve();
123
- return itemPromise;
124
- }
125
- this.items.push({
126
- action: item.action,
127
- payload: item.item,
128
- otelContext: item.otelContext,
129
- apiKey: item.apiKey,
130
- apiUrl: item.apiUrl,
131
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
132
- itemPromiseResolve,
133
- itemPromise,
134
- size
135
- });
136
- this.sizeBytes += size;
137
- return itemPromise;
138
- }
139
- pop({ upToSizeBytes, upToSize }) {
140
- if (upToSizeBytes < 1) {
141
- throw new Error("Number of bytes to pop off may not be less than 1.");
142
- }
143
- const popped = [];
144
- let poppedSizeBytes = 0;
145
- while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && this.items.length > 0 && popped.length < upToSize) {
146
- const item = this.items.shift();
147
- if (item) {
148
- popped.push(item);
149
- poppedSizeBytes += item.size;
150
- this.sizeBytes -= item.size;
151
- }
152
- }
153
- if (popped.length === 0 && this.items.length > 0) {
154
- const item = this.items.shift();
155
- popped.push(item);
156
- poppedSizeBytes += item.size;
157
- this.sizeBytes -= item.size;
158
- }
159
- return [
160
- popped.map((it) => ({
161
- action: it.action,
162
- item: it.payload,
163
- otelContext: it.otelContext,
164
- apiKey: it.apiKey,
165
- apiUrl: it.apiUrl,
166
- size: it.size
167
- })),
168
- () => popped.forEach((it) => it.itemPromiseResolve())
169
- ];
170
- }
171
- }
172
- class Client {
173
- get _fetch() {
174
- return this.fetchImplementation || _getFetchImplementation(this.debug);
175
- }
176
- constructor(config = {}) {
177
- Object.defineProperty(this, "apiKey", {
178
- enumerable: true,
179
- configurable: true,
180
- writable: true,
181
- value: void 0
182
- });
183
- Object.defineProperty(this, "apiUrl", {
184
- enumerable: true,
185
- configurable: true,
186
- writable: true,
187
- value: void 0
188
- });
189
- Object.defineProperty(this, "webUrl", {
190
- enumerable: true,
191
- configurable: true,
192
- writable: true,
193
- value: void 0
194
- });
195
- Object.defineProperty(this, "workspaceId", {
196
- enumerable: true,
197
- configurable: true,
198
- writable: true,
199
- value: void 0
200
- });
201
- Object.defineProperty(this, "caller", {
202
- enumerable: true,
203
- configurable: true,
204
- writable: true,
205
- value: void 0
206
- });
207
- Object.defineProperty(this, "batchIngestCaller", {
208
- enumerable: true,
209
- configurable: true,
210
- writable: true,
211
- value: void 0
212
- });
213
- Object.defineProperty(this, "timeout_ms", {
214
- enumerable: true,
215
- configurable: true,
216
- writable: true,
217
- value: void 0
218
- });
219
- Object.defineProperty(this, "_tenantId", {
220
- enumerable: true,
221
- configurable: true,
222
- writable: true,
223
- value: null
224
- });
225
- Object.defineProperty(this, "hideInputs", {
226
- enumerable: true,
227
- configurable: true,
228
- writable: true,
229
- value: void 0
230
- });
231
- Object.defineProperty(this, "hideOutputs", {
232
- enumerable: true,
233
- configurable: true,
234
- writable: true,
235
- value: void 0
236
- });
237
- Object.defineProperty(this, "omitTracedRuntimeInfo", {
238
- enumerable: true,
239
- configurable: true,
240
- writable: true,
241
- value: void 0
242
- });
243
- Object.defineProperty(this, "tracingSampleRate", {
244
- enumerable: true,
245
- configurable: true,
246
- writable: true,
247
- value: void 0
248
- });
249
- Object.defineProperty(this, "filteredPostUuids", {
250
- enumerable: true,
251
- configurable: true,
252
- writable: true,
253
- value: /* @__PURE__ */ new Set()
254
- });
255
- Object.defineProperty(this, "autoBatchTracing", {
256
- enumerable: true,
257
- configurable: true,
258
- writable: true,
259
- value: true
260
- });
261
- Object.defineProperty(this, "autoBatchQueue", {
262
- enumerable: true,
263
- configurable: true,
264
- writable: true,
265
- value: void 0
266
- });
267
- Object.defineProperty(this, "autoBatchTimeout", {
268
- enumerable: true,
269
- configurable: true,
270
- writable: true,
271
- value: void 0
272
- });
273
- Object.defineProperty(this, "autoBatchAggregationDelayMs", {
274
- enumerable: true,
275
- configurable: true,
276
- writable: true,
277
- value: 250
278
- });
279
- Object.defineProperty(this, "batchSizeBytesLimit", {
280
- enumerable: true,
281
- configurable: true,
282
- writable: true,
283
- value: void 0
284
- });
285
- Object.defineProperty(this, "batchSizeLimit", {
286
- enumerable: true,
287
- configurable: true,
288
- writable: true,
289
- value: void 0
290
- });
291
- Object.defineProperty(this, "fetchOptions", {
292
- enumerable: true,
293
- configurable: true,
294
- writable: true,
295
- value: void 0
296
- });
297
- Object.defineProperty(this, "settings", {
298
- enumerable: true,
299
- configurable: true,
300
- writable: true,
301
- value: void 0
302
- });
303
- Object.defineProperty(this, "blockOnRootRunFinalization", {
304
- enumerable: true,
305
- configurable: true,
306
- writable: true,
307
- value: getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false"
308
- });
309
- Object.defineProperty(this, "traceBatchConcurrency", {
310
- enumerable: true,
311
- configurable: true,
312
- writable: true,
313
- value: 5
314
- });
315
- Object.defineProperty(this, "_serverInfo", {
316
- enumerable: true,
317
- configurable: true,
318
- writable: true,
319
- value: void 0
320
- });
321
- Object.defineProperty(this, "_getServerInfoPromise", {
322
- enumerable: true,
323
- configurable: true,
324
- writable: true,
325
- value: void 0
326
- });
327
- Object.defineProperty(this, "manualFlushMode", {
328
- enumerable: true,
329
- configurable: true,
330
- writable: true,
331
- value: false
332
- });
333
- Object.defineProperty(this, "langSmithToOTELTranslator", {
334
- enumerable: true,
335
- configurable: true,
336
- writable: true,
337
- value: void 0
338
- });
339
- Object.defineProperty(this, "fetchImplementation", {
340
- enumerable: true,
341
- configurable: true,
342
- writable: true,
343
- value: void 0
344
- });
345
- Object.defineProperty(this, "cachedLSEnvVarsForMetadata", {
346
- enumerable: true,
347
- configurable: true,
348
- writable: true,
349
- value: void 0
350
- });
351
- Object.defineProperty(this, "_cache", {
352
- enumerable: true,
353
- configurable: true,
354
- writable: true,
355
- value: void 0
356
- });
357
- Object.defineProperty(this, "multipartStreamingDisabled", {
358
- enumerable: true,
359
- configurable: true,
360
- writable: true,
361
- value: false
362
- });
363
- Object.defineProperty(this, "_multipartDisabled", {
364
- enumerable: true,
365
- configurable: true,
366
- writable: true,
367
- value: false
368
- });
369
- Object.defineProperty(this, "debug", {
370
- enumerable: true,
371
- configurable: true,
372
- writable: true,
373
- value: getEnvironmentVariable("LANGSMITH_DEBUG") === "true"
374
- });
375
- const defaultConfig = Client.getDefaultClientConfig();
376
- this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate);
377
- this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? "";
378
- if (this.apiUrl.endsWith("/")) {
379
- this.apiUrl = this.apiUrl.slice(0, -1);
380
- }
381
- this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey);
382
- this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl);
383
- if (this.webUrl?.endsWith("/")) {
384
- this.webUrl = this.webUrl.slice(0, -1);
385
- }
386
- this.workspaceId = trimQuotes(config.workspaceId ?? getLangSmithEnvironmentVariable("WORKSPACE_ID"));
387
- this.timeout_ms = config.timeout_ms ?? 9e4;
388
- this.caller = new AsyncCaller({
389
- ...config.callerOptions ?? {},
390
- maxRetries: 4,
391
- debug: config.debug ?? this.debug
392
- });
393
- this.traceBatchConcurrency = config.traceBatchConcurrency ?? this.traceBatchConcurrency;
394
- if (this.traceBatchConcurrency < 1) {
395
- throw new Error("Trace batch concurrency must be positive.");
396
- }
397
- this.debug = config.debug ?? this.debug;
398
- this.fetchImplementation = config.fetchImplementation;
399
- const maxMemory = config.maxIngestMemoryBytes ?? DEFAULT_MAX_SIZE_BYTES;
400
- this.batchIngestCaller = new AsyncCaller({
401
- maxRetries: 4,
402
- maxConcurrency: this.traceBatchConcurrency,
403
- maxQueueSizeBytes: maxMemory,
404
- ...config.callerOptions ?? {},
405
- onFailedResponseHook: handle429,
406
- debug: config.debug ?? this.debug
407
- });
408
- this.hideInputs = config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs;
409
- this.hideOutputs = config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs;
410
- this.omitTracedRuntimeInfo = config.omitTracedRuntimeInfo ?? false;
411
- this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing;
412
- this.autoBatchQueue = new AutoBatchQueue(maxMemory);
413
- this.blockOnRootRunFinalization = config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization;
414
- this.batchSizeBytesLimit = config.batchSizeBytesLimit;
415
- this.batchSizeLimit = config.batchSizeLimit;
416
- this.fetchOptions = config.fetchOptions || {};
417
- this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode;
418
- if (getOtelEnabled()) {
419
- this.langSmithToOTELTranslator = new LangSmithToOTELTranslator();
420
- }
421
- this.cachedLSEnvVarsForMetadata = getLangSmithEnvVarsMetadata();
422
- if (config.cache === true) {
423
- this._cache = new Cache();
424
- } else if (config.cache && typeof config.cache === "object") {
425
- this._cache = config.cache;
426
- } else {
427
- this._cache = void 0;
428
- }
429
- }
430
- static getDefaultClientConfig() {
431
- const apiKey = getLangSmithEnvironmentVariable("API_KEY");
432
- const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? DEFAULT_API_URL;
433
- const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true";
434
- const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true";
435
- return {
436
- apiUrl,
437
- apiKey,
438
- webUrl: void 0,
439
- hideInputs,
440
- hideOutputs
441
- };
442
- }
443
- getHostUrl() {
444
- if (this.webUrl) {
445
- return this.webUrl;
446
- } else if (isLocalhost(this.apiUrl)) {
447
- this.webUrl = "http://localhost:3000";
448
- return this.webUrl;
449
- } else if (this.apiUrl.endsWith("/api/v1")) {
450
- this.webUrl = this.apiUrl.replace("/api/v1", "");
451
- return this.webUrl;
452
- } else if (this.apiUrl.includes("/api") && !this.apiUrl.split(".", 1)[0].endsWith("api")) {
453
- this.webUrl = this.apiUrl.replace("/api", "");
454
- return this.webUrl;
455
- } else if (this.apiUrl.split(".", 1)[0].includes("dev")) {
456
- this.webUrl = "https://dev.smith.langchain.com";
457
- return this.webUrl;
458
- } else if (this.apiUrl.split(".", 1)[0].includes("eu")) {
459
- this.webUrl = "https://eu.smith.langchain.com";
460
- return this.webUrl;
461
- } else if (this.apiUrl.split(".", 1)[0].includes("beta")) {
462
- this.webUrl = "https://beta.smith.langchain.com";
463
- return this.webUrl;
464
- } else {
465
- this.webUrl = "https://smith.langchain.com";
466
- return this.webUrl;
467
- }
468
- }
469
- get headers() {
470
- const headers = {
471
- "User-Agent": `langsmith-js/${__version__}`
472
- };
473
- if (this.apiKey) {
474
- headers["x-api-key"] = `${this.apiKey}`;
475
- }
476
- if (this.workspaceId) {
477
- headers["x-tenant-id"] = this.workspaceId;
478
- }
479
- return headers;
480
- }
481
- _getPlatformEndpointPath(path) {
482
- const needsV1Prefix = this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/";
483
- return needsV1Prefix ? `/v1/platform/${path}` : `/platform/${path}`;
484
- }
485
- async processInputs(inputs) {
486
- if (this.hideInputs === false) {
487
- return inputs;
488
- }
489
- if (this.hideInputs === true) {
490
- return {};
491
- }
492
- if (typeof this.hideInputs === "function") {
493
- return this.hideInputs(inputs);
494
- }
495
- return inputs;
496
- }
497
- async processOutputs(outputs) {
498
- if (this.hideOutputs === false) {
499
- return outputs;
500
- }
501
- if (this.hideOutputs === true) {
502
- return {};
503
- }
504
- if (typeof this.hideOutputs === "function") {
505
- return this.hideOutputs(outputs);
506
- }
507
- return outputs;
508
- }
509
- async prepareRunCreateOrUpdateInputs(run) {
510
- const runParams = { ...run };
511
- if (runParams.inputs !== void 0) {
512
- runParams.inputs = await this.processInputs(runParams.inputs);
513
- }
514
- if (runParams.outputs !== void 0) {
515
- runParams.outputs = await this.processOutputs(runParams.outputs);
516
- }
517
- return runParams;
518
- }
519
- async _getResponse(path, queryParams) {
520
- const paramsString = queryParams?.toString() ?? "";
521
- const url = `${this.apiUrl}${path}?${paramsString}`;
522
- const response = await this.caller.call(async () => {
523
- const res = await this._fetch(url, {
524
- method: "GET",
525
- headers: this.headers,
526
- signal: AbortSignal.timeout(this.timeout_ms),
527
- ...this.fetchOptions
528
- });
529
- await raiseForStatus(res, `fetch ${path}`);
530
- return res;
531
- });
532
- return response;
533
- }
534
- async _get(path, queryParams) {
535
- const response = await this._getResponse(path, queryParams);
536
- return response.json();
537
- }
538
- async *_getPaginated(path, queryParams = new URLSearchParams(), transform) {
539
- let offset = Number(queryParams.get("offset")) || 0;
540
- const limit = Number(queryParams.get("limit")) || 100;
541
- while (true) {
542
- queryParams.set("offset", String(offset));
543
- queryParams.set("limit", String(limit));
544
- const url = `${this.apiUrl}${path}?${queryParams}`;
545
- const response = await this.caller.call(async () => {
546
- const res = await this._fetch(url, {
547
- method: "GET",
548
- headers: this.headers,
549
- signal: AbortSignal.timeout(this.timeout_ms),
550
- ...this.fetchOptions
551
- });
552
- await raiseForStatus(res, `fetch ${path}`);
553
- return res;
554
- });
555
- const items = transform ? transform(await response.json()) : await response.json();
556
- if (items.length === 0) {
557
- break;
558
- }
559
- yield items;
560
- if (items.length < limit) {
561
- break;
562
- }
563
- offset += items.length;
564
- }
565
- }
566
- async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") {
567
- const bodyParams = body ? { ...body } : {};
568
- while (true) {
569
- const body2 = JSON.stringify(bodyParams);
570
- const response = await this.caller.call(async () => {
571
- const res = await this._fetch(`${this.apiUrl}${path}`, {
572
- method: requestMethod,
573
- headers: { ...this.headers, "Content-Type": "application/json" },
574
- signal: AbortSignal.timeout(this.timeout_ms),
575
- ...this.fetchOptions,
576
- body: body2
577
- });
578
- await raiseForStatus(res, `fetch ${path}`);
579
- return res;
580
- });
581
- const responseBody = await response.json();
582
- if (!responseBody) {
583
- break;
584
- }
585
- if (!responseBody[dataKey]) {
586
- break;
587
- }
588
- yield responseBody[dataKey];
589
- const cursors = responseBody.cursors;
590
- if (!cursors) {
591
- break;
592
- }
593
- if (!cursors.next) {
594
- break;
595
- }
596
- bodyParams.cursor = cursors.next;
597
- }
598
- }
599
- // Allows mocking for tests
600
- _shouldSample() {
601
- if (this.tracingSampleRate === void 0) {
602
- return true;
603
- }
604
- return Math.random() < this.tracingSampleRate;
605
- }
606
- _filterForSampling(runs, patch = false) {
607
- if (this.tracingSampleRate === void 0) {
608
- return runs;
609
- }
610
- if (patch) {
611
- const sampled = [];
612
- for (const run of runs) {
613
- if (!this.filteredPostUuids.has(run.trace_id)) {
614
- sampled.push(run);
615
- } else if (run.id === run.trace_id) {
616
- this.filteredPostUuids.delete(run.trace_id);
617
- }
618
- }
619
- return sampled;
620
- } else {
621
- const sampled = [];
622
- for (const run of runs) {
623
- const traceId = run.trace_id ?? run.id;
624
- if (this.filteredPostUuids.has(traceId)) {
625
- continue;
626
- }
627
- if (run.id === traceId) {
628
- if (this._shouldSample()) {
629
- sampled.push(run);
630
- } else {
631
- this.filteredPostUuids.add(traceId);
632
- }
633
- } else {
634
- sampled.push(run);
635
- }
636
- }
637
- return sampled;
638
- }
639
- }
640
- async _getBatchSizeLimitBytes() {
641
- const serverInfo = await this._ensureServerInfo();
642
- return this.batchSizeBytesLimit ?? serverInfo?.batch_ingest_config?.size_limit_bytes ?? DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES;
643
- }
644
- /**
645
- * Get the maximum number of operations to batch in a single request.
646
- */
647
- async _getBatchSizeLimit() {
648
- const serverInfo = await this._ensureServerInfo();
649
- return this.batchSizeLimit ?? serverInfo?.batch_ingest_config?.size_limit ?? DEFAULT_BATCH_SIZE_LIMIT;
650
- }
651
- async _getDatasetExamplesMultiPartSupport() {
652
- const serverInfo = await this._ensureServerInfo();
653
- return serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false;
654
- }
655
- drainAutoBatchQueue({ batchSizeLimitBytes, batchSizeLimit }) {
656
- const promises = [];
657
- while (this.autoBatchQueue.items.length > 0) {
658
- const [batch, done] = this.autoBatchQueue.pop({
659
- upToSizeBytes: batchSizeLimitBytes,
660
- upToSize: batchSizeLimit
661
- });
662
- if (!batch.length) {
663
- done();
664
- break;
665
- }
666
- const batchesByDestination = batch.reduce((acc, item) => {
667
- const apiUrl = item.apiUrl ?? this.apiUrl;
668
- const apiKey = item.apiKey ?? this.apiKey;
669
- const isDefault = item.apiKey === this.apiKey && item.apiUrl === this.apiUrl;
670
- const batchKey = isDefault ? "default" : `${apiUrl}|${apiKey}`;
671
- if (!acc[batchKey]) {
672
- acc[batchKey] = [];
673
- }
674
- acc[batchKey].push(item);
675
- return acc;
676
- }, {});
677
- const batchPromises = [];
678
- for (const [batchKey, batch2] of Object.entries(batchesByDestination)) {
679
- const batchPromise = this._processBatch(batch2, {
680
- apiUrl: batchKey === "default" ? void 0 : batchKey.split("|")[0],
681
- apiKey: batchKey === "default" ? void 0 : batchKey.split("|")[1]
682
- });
683
- batchPromises.push(batchPromise);
684
- }
685
- const allBatchesPromise = Promise.all(batchPromises).finally(done);
686
- promises.push(allBatchesPromise);
687
- }
688
- return Promise.all(promises);
689
- }
690
- async _processBatch(batch, options) {
691
- if (!batch.length) {
692
- return;
693
- }
694
- const batchSizeBytes = batch.reduce((sum, item) => sum + (item.size ?? 0), 0);
695
- try {
696
- if (this.langSmithToOTELTranslator !== void 0) {
697
- this._sendBatchToOTELTranslator(batch);
698
- } else {
699
- const ingestParams = {
700
- runCreates: batch.filter((item) => item.action === "create").map((item) => item.item),
701
- runUpdates: batch.filter((item) => item.action === "update").map((item) => item.item)
702
- };
703
- const serverInfo = await this._ensureServerInfo();
704
- const useMultipart = !this._multipartDisabled && (serverInfo?.batch_ingest_config?.use_multipart_endpoint ?? true);
705
- if (useMultipart) {
706
- const useGzip = serverInfo?.instance_flags?.gzip_body_enabled;
707
- try {
708
- await this.multipartIngestRuns(ingestParams, {
709
- ...options,
710
- useGzip,
711
- sizeBytes: batchSizeBytes
712
- });
713
- } catch (e) {
714
- if (isLangSmithNotFoundError(e)) {
715
- this._multipartDisabled = true;
716
- await this.batchIngestRuns(ingestParams, {
717
- ...options,
718
- sizeBytes: batchSizeBytes
719
- });
720
- } else {
721
- throw e;
722
- }
723
- }
724
- } else {
725
- await this.batchIngestRuns(ingestParams, {
726
- ...options,
727
- sizeBytes: batchSizeBytes
728
- });
729
- }
730
- }
731
- } catch (e) {
732
- console.error("Error exporting batch:", e);
733
- }
734
- }
735
- _sendBatchToOTELTranslator(batch) {
736
- if (this.langSmithToOTELTranslator !== void 0) {
737
- const otelContextMap = /* @__PURE__ */ new Map();
738
- const operations = [];
739
- for (const item of batch) {
740
- if (item.item.id && item.otelContext) {
741
- otelContextMap.set(item.item.id, item.otelContext);
742
- if (item.action === "create") {
743
- operations.push({
744
- operation: "post",
745
- id: item.item.id,
746
- trace_id: item.item.trace_id ?? item.item.id,
747
- run: item.item
748
- });
749
- } else {
750
- operations.push({
751
- operation: "patch",
752
- id: item.item.id,
753
- trace_id: item.item.trace_id ?? item.item.id,
754
- run: item.item
755
- });
756
- }
757
- }
758
- }
759
- this.langSmithToOTELTranslator.exportBatch(operations, otelContextMap);
760
- }
761
- }
762
- async processRunOperation(item) {
763
- clearTimeout(this.autoBatchTimeout);
764
- this.autoBatchTimeout = void 0;
765
- item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo);
766
- const itemPromise = this.autoBatchQueue.push(item);
767
- if (this.manualFlushMode) {
768
- return itemPromise;
769
- }
770
- const sizeLimitBytes = await this._getBatchSizeLimitBytes();
771
- const sizeLimit = await this._getBatchSizeLimit();
772
- if (this.autoBatchQueue.sizeBytes > sizeLimitBytes || this.autoBatchQueue.items.length > sizeLimit) {
773
- void this.drainAutoBatchQueue({
774
- batchSizeLimitBytes: sizeLimitBytes,
775
- batchSizeLimit: sizeLimit
776
- });
777
- }
778
- if (this.autoBatchQueue.items.length > 0) {
779
- this.autoBatchTimeout = setTimeout(() => {
780
- this.autoBatchTimeout = void 0;
781
- void this.drainAutoBatchQueue({
782
- batchSizeLimitBytes: sizeLimitBytes,
783
- batchSizeLimit: sizeLimit
784
- });
785
- }, this.autoBatchAggregationDelayMs);
786
- }
787
- return itemPromise;
788
- }
789
- async _getServerInfo() {
790
- const response = await this.caller.call(async () => {
791
- const res = await this._fetch(`${this.apiUrl}/info`, {
792
- method: "GET",
793
- headers: { Accept: "application/json" },
794
- signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT_MS),
795
- ...this.fetchOptions
796
- });
797
- await raiseForStatus(res, "get server info");
798
- return res;
799
- });
800
- const json = await response.json();
801
- if (this.debug) {
802
- console.log("\n=== LangSmith Server Configuration ===\n" + JSON.stringify(json, null, 2) + "\n");
803
- }
804
- return json;
805
- }
806
- async _ensureServerInfo() {
807
- if (this._getServerInfoPromise === void 0) {
808
- this._getServerInfoPromise = (async () => {
809
- if (this._serverInfo === void 0) {
810
- try {
811
- this._serverInfo = await this._getServerInfo();
812
- } catch (e) {
813
- console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status ?? "Unspecified status code"} ${e.message}`);
814
- }
815
- }
816
- return this._serverInfo ?? {};
817
- })();
818
- }
819
- return this._getServerInfoPromise.then((serverInfo) => {
820
- if (this._serverInfo === void 0) {
821
- this._getServerInfoPromise = void 0;
822
- }
823
- return serverInfo;
824
- });
825
- }
826
- async _getSettings() {
827
- if (!this.settings) {
828
- this.settings = this._get("/settings");
829
- }
830
- return await this.settings;
831
- }
832
- /**
833
- * Flushes current queued traces.
834
- */
835
- async flush() {
836
- const sizeLimitBytes = await this._getBatchSizeLimitBytes();
837
- const sizeLimit = await this._getBatchSizeLimit();
838
- await this.drainAutoBatchQueue({
839
- batchSizeLimitBytes: sizeLimitBytes,
840
- batchSizeLimit: sizeLimit
841
- });
842
- }
843
- _cloneCurrentOTELContext() {
844
- const otel_trace = getOTELTrace();
845
- const otel_context = getOTELContext();
846
- if (this.langSmithToOTELTranslator !== void 0) {
847
- const currentSpan = otel_trace.getActiveSpan();
848
- if (currentSpan) {
849
- return otel_trace.setSpan(otel_context.active(), currentSpan);
850
- }
851
- }
852
- return void 0;
853
- }
854
- async createRun(run, options) {
855
- if (!this._filterForSampling([run]).length) {
856
- return;
857
- }
858
- const headers = {
859
- ...this.headers,
860
- "Content-Type": "application/json"
861
- };
862
- const session_name = run.project_name;
863
- delete run.project_name;
864
- const runCreate = await this.prepareRunCreateOrUpdateInputs({
865
- session_name,
866
- ...run,
867
- start_time: run.start_time ?? Date.now()
868
- });
869
- if (this.autoBatchTracing && runCreate.trace_id !== void 0 && runCreate.dotted_order !== void 0) {
870
- const otelContext = this._cloneCurrentOTELContext();
871
- void this.processRunOperation({
872
- action: "create",
873
- item: runCreate,
874
- otelContext,
875
- apiKey: options?.apiKey,
876
- apiUrl: options?.apiUrl
877
- }).catch(console.error);
878
- return;
879
- }
880
- const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo);
881
- if (options?.apiKey !== void 0) {
882
- headers["x-api-key"] = options.apiKey;
883
- }
884
- if (options?.workspaceId !== void 0) {
885
- headers["x-tenant-id"] = options.workspaceId;
886
- }
887
- const body = serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`);
888
- await this.caller.call(async () => {
889
- const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs`, {
890
- method: "POST",
891
- headers,
892
- signal: AbortSignal.timeout(this.timeout_ms),
893
- ...this.fetchOptions,
894
- body
895
- });
896
- await raiseForStatus(res, "create run", true);
897
- return res;
898
- });
899
- }
900
- /**
901
- * Batch ingest/upsert multiple runs in the Langsmith system.
902
- * @param runs
903
- */
904
- async batchIngestRuns({ runCreates, runUpdates }, options) {
905
- if (runCreates === void 0 && runUpdates === void 0) {
906
- return;
907
- }
908
- let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []);
909
- let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []);
910
- if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) {
911
- const createById = preparedCreateParams.reduce((params, run) => {
912
- if (!run.id) {
913
- return params;
914
- }
915
- params[run.id] = run;
916
- return params;
917
- }, {});
918
- const standaloneUpdates = [];
919
- for (const updateParam of preparedUpdateParams) {
920
- if (updateParam.id !== void 0 && createById[updateParam.id]) {
921
- createById[updateParam.id] = {
922
- ...createById[updateParam.id],
923
- ...updateParam
924
- };
925
- } else {
926
- standaloneUpdates.push(updateParam);
927
- }
928
- }
929
- preparedCreateParams = Object.values(createById);
930
- preparedUpdateParams = standaloneUpdates;
931
- }
932
- const rawBatch = {
933
- post: preparedCreateParams,
934
- patch: preparedUpdateParams
935
- };
936
- if (!rawBatch.post.length && !rawBatch.patch.length) {
937
- return;
938
- }
939
- const batchChunks = {
940
- post: [],
941
- patch: []
942
- };
943
- for (const k of ["post", "patch"]) {
944
- const key = k;
945
- const batchItems = rawBatch[key].reverse();
946
- let batchItem = batchItems.pop();
947
- while (batchItem !== void 0) {
948
- batchChunks[key].push(batchItem);
949
- batchItem = batchItems.pop();
950
- }
951
- }
952
- if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) {
953
- const runIds = batchChunks.post.map((item) => item.id).concat(batchChunks.patch.map((item) => item.id)).join(",");
954
- await this._postBatchIngestRuns(serialize(batchChunks, `Ingesting runs with ids: ${runIds}`), options);
955
- }
956
- }
957
- async _postBatchIngestRuns(body, options) {
958
- const headers = {
959
- ...this.headers,
960
- "Content-Type": "application/json",
961
- Accept: "application/json"
962
- };
963
- if (options?.apiKey !== void 0) {
964
- headers["x-api-key"] = options.apiKey;
965
- }
966
- await this.batchIngestCaller.callWithOptions({ sizeBytes: options?.sizeBytes }, async () => {
967
- const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/batch`, {
968
- method: "POST",
969
- headers,
970
- signal: AbortSignal.timeout(this.timeout_ms),
971
- ...this.fetchOptions,
972
- body
973
- });
974
- await raiseForStatus(res, "batch create run", true);
975
- return res;
976
- });
977
- }
978
- /**
979
- * Batch ingest/upsert multiple runs in the Langsmith system.
980
- * @param runs
981
- */
982
- async multipartIngestRuns({ runCreates, runUpdates }, options) {
983
- if (runCreates === void 0 && runUpdates === void 0) {
984
- return;
985
- }
986
- const allAttachments = {};
987
- let preparedCreateParams = [];
988
- for (const create of runCreates ?? []) {
989
- const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create);
990
- if (preparedCreate.id !== void 0 && preparedCreate.attachments !== void 0) {
991
- allAttachments[preparedCreate.id] = preparedCreate.attachments;
992
- }
993
- delete preparedCreate.attachments;
994
- preparedCreateParams.push(preparedCreate);
995
- }
996
- let preparedUpdateParams = [];
997
- for (const update of runUpdates ?? []) {
998
- preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update));
999
- }
1000
- const invalidRunCreate = preparedCreateParams.find((runCreate) => {
1001
- return runCreate.trace_id === void 0 || runCreate.dotted_order === void 0;
1002
- });
1003
- if (invalidRunCreate !== void 0) {
1004
- throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`);
1005
- }
1006
- const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => {
1007
- return runUpdate.trace_id === void 0 || runUpdate.dotted_order === void 0;
1008
- });
1009
- if (invalidRunUpdate !== void 0) {
1010
- throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`);
1011
- }
1012
- if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) {
1013
- const createById = preparedCreateParams.reduce((params, run) => {
1014
- if (!run.id) {
1015
- return params;
1016
- }
1017
- params[run.id] = run;
1018
- return params;
1019
- }, {});
1020
- const standaloneUpdates = [];
1021
- for (const updateParam of preparedUpdateParams) {
1022
- if (updateParam.id !== void 0 && createById[updateParam.id]) {
1023
- createById[updateParam.id] = {
1024
- ...createById[updateParam.id],
1025
- ...updateParam
1026
- };
1027
- } else {
1028
- standaloneUpdates.push(updateParam);
1029
- }
1030
- }
1031
- preparedCreateParams = Object.values(createById);
1032
- preparedUpdateParams = standaloneUpdates;
1033
- }
1034
- if (preparedCreateParams.length === 0 && preparedUpdateParams.length === 0) {
1035
- return;
1036
- }
1037
- const accumulatedContext = [];
1038
- const accumulatedParts = [];
1039
- for (const [method, payloads] of [
1040
- ["post", preparedCreateParams],
1041
- ["patch", preparedUpdateParams]
1042
- ]) {
1043
- for (const originalPayload of payloads) {
1044
- const { inputs, outputs, events, extra, error, serialized, attachments, ...payload } = originalPayload;
1045
- const fields = { inputs, outputs, events, extra, error, serialized };
1046
- const stringifiedPayload = serialize(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`);
1047
- accumulatedParts.push({
1048
- name: `${method}.${payload.id}`,
1049
- payload: new Blob([stringifiedPayload], {
1050
- type: `application/json; length=${stringifiedPayload.length}`
1051
- // encoding=gzip
1052
- })
1053
- });
1054
- for (const [key, value] of Object.entries(fields)) {
1055
- if (value === void 0) {
1056
- continue;
1057
- }
1058
- const stringifiedValue = serialize(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`);
1059
- accumulatedParts.push({
1060
- name: `${method}.${payload.id}.${key}`,
1061
- payload: new Blob([stringifiedValue], {
1062
- type: `application/json; length=${stringifiedValue.length}`
1063
- })
1064
- });
1065
- }
1066
- if (payload.id !== void 0) {
1067
- const attachments2 = allAttachments[payload.id];
1068
- if (attachments2) {
1069
- delete allAttachments[payload.id];
1070
- for (const [name, attachment] of Object.entries(attachments2)) {
1071
- let contentType;
1072
- let content;
1073
- if (Array.isArray(attachment)) {
1074
- [contentType, content] = attachment;
1075
- } else {
1076
- contentType = attachment.mimeType;
1077
- content = attachment.data;
1078
- }
1079
- if (name.includes(".")) {
1080
- console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);
1081
- continue;
1082
- }
1083
- accumulatedParts.push({
1084
- name: `attachment.${payload.id}.${name}`,
1085
- payload: new Blob([content], {
1086
- type: `${contentType}; length=${content.byteLength}`
1087
- })
1088
- });
1089
- }
1090
- }
1091
- }
1092
- accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`);
1093
- }
1094
- }
1095
- await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; "), options);
1096
- }
1097
- async _createNodeFetchBody(parts, boundary) {
1098
- const chunks = [];
1099
- for (const part of parts) {
1100
- chunks.push(new Blob([`--${boundary}\r
1101
- `]));
1102
- chunks.push(new Blob([
1103
- `Content-Disposition: form-data; name="${part.name}"\r
1104
- `,
1105
- `Content-Type: ${part.payload.type}\r
1106
- \r
1107
- `
1108
- ]));
1109
- chunks.push(part.payload);
1110
- chunks.push(new Blob(["\r\n"]));
1111
- }
1112
- chunks.push(new Blob([`--${boundary}--\r
1113
- `]));
1114
- const body = new Blob(chunks);
1115
- const arrayBuffer = await body.arrayBuffer();
1116
- return arrayBuffer;
1117
- }
1118
- async _createMultipartStream(parts, boundary) {
1119
- const encoder = new TextEncoder();
1120
- const stream = new ReadableStream({
1121
- async start(controller) {
1122
- const writeChunk = async (chunk) => {
1123
- if (typeof chunk === "string") {
1124
- controller.enqueue(encoder.encode(chunk));
1125
- } else {
1126
- controller.enqueue(chunk);
1127
- }
1128
- };
1129
- for (const part of parts) {
1130
- await writeChunk(`--${boundary}\r
1131
- `);
1132
- await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r
1133
- `);
1134
- await writeChunk(`Content-Type: ${part.payload.type}\r
1135
- \r
1136
- `);
1137
- const payloadStream = part.payload.stream();
1138
- const reader = payloadStream.getReader();
1139
- try {
1140
- let result;
1141
- while (!(result = await reader.read()).done) {
1142
- controller.enqueue(result.value);
1143
- }
1144
- } finally {
1145
- reader.releaseLock();
1146
- }
1147
- await writeChunk("\r\n");
1148
- }
1149
- await writeChunk(`--${boundary}--\r
1150
- `);
1151
- controller.close();
1152
- }
1153
- });
1154
- return stream;
1155
- }
1156
- async _sendMultipartRequest(parts, context, options) {
1157
- const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2);
1158
- const isNodeFetch = _globalFetchImplementationIsNodeFetch();
1159
- const buildBuffered = () => this._createNodeFetchBody(parts, boundary);
1160
- const buildStream = () => this._createMultipartStream(parts, boundary);
1161
- const sendWithRetry = async (bodyFactory) => {
1162
- return this.batchIngestCaller.callWithOptions({ sizeBytes: options?.sizeBytes }, async () => {
1163
- const body = await bodyFactory();
1164
- const headers = {
1165
- ...this.headers,
1166
- "Content-Type": `multipart/form-data; boundary=${boundary}`
1167
- };
1168
- if (options?.apiKey !== void 0) {
1169
- headers["x-api-key"] = options.apiKey;
1170
- }
1171
- let transformedBody = body;
1172
- if (options?.useGzip && typeof body === "object" && "pipeThrough" in body) {
1173
- transformedBody = body.pipeThrough(new CompressionStream("gzip"));
1174
- headers["Content-Encoding"] = "gzip";
1175
- }
1176
- const response = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/multipart`, {
1177
- method: "POST",
1178
- headers,
1179
- body: transformedBody,
1180
- duplex: "half",
1181
- signal: AbortSignal.timeout(this.timeout_ms),
1182
- ...this.fetchOptions
1183
- });
1184
- await raiseForStatus(response, `Failed to send multipart request`, true);
1185
- return response;
1186
- });
1187
- };
1188
- try {
1189
- let res;
1190
- let streamedAttempt = false;
1191
- if (!isNodeFetch && !this.multipartStreamingDisabled && getEnv() !== "bun") {
1192
- streamedAttempt = true;
1193
- res = await sendWithRetry(buildStream);
1194
- } else {
1195
- res = await sendWithRetry(buildBuffered);
1196
- }
1197
- if ((!this.multipartStreamingDisabled || streamedAttempt) && res.status === 422 && (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) {
1198
- console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${context}".`);
1199
- this.multipartStreamingDisabled = true;
1200
- res = await sendWithRetry(buildBuffered);
1201
- }
1202
- } catch (e) {
1203
- if (isLangSmithNotFoundError(e)) {
1204
- throw e;
1205
- }
1206
- console.warn(`${e.message.trim()}
1207
-
1208
- Context: ${context}`);
1209
- }
1210
- }
1211
- async updateRun(runId, run, options) {
1212
- assertUuid(runId);
1213
- if (run.inputs) {
1214
- run.inputs = await this.processInputs(run.inputs);
1215
- }
1216
- if (run.outputs) {
1217
- run.outputs = await this.processOutputs(run.outputs);
1218
- }
1219
- const data = { ...run, id: runId };
1220
- if (!this._filterForSampling([data], true).length) {
1221
- return;
1222
- }
1223
- if (this.autoBatchTracing && data.trace_id !== void 0 && data.dotted_order !== void 0) {
1224
- const otelContext = this._cloneCurrentOTELContext();
1225
- if (run.end_time !== void 0 && data.parent_run_id === void 0 && this.blockOnRootRunFinalization && !this.manualFlushMode) {
1226
- await this.processRunOperation({
1227
- action: "update",
1228
- item: data,
1229
- otelContext,
1230
- apiKey: options?.apiKey,
1231
- apiUrl: options?.apiUrl
1232
- }).catch(console.error);
1233
- return;
1234
- } else {
1235
- void this.processRunOperation({
1236
- action: "update",
1237
- item: data,
1238
- otelContext,
1239
- apiKey: options?.apiKey,
1240
- apiUrl: options?.apiUrl
1241
- }).catch(console.error);
1242
- }
1243
- return;
1244
- }
1245
- const headers = {
1246
- ...this.headers,
1247
- "Content-Type": "application/json"
1248
- };
1249
- if (options?.apiKey !== void 0) {
1250
- headers["x-api-key"] = options.apiKey;
1251
- }
1252
- if (options?.workspaceId !== void 0) {
1253
- headers["x-tenant-id"] = options.workspaceId;
1254
- }
1255
- const body = serialize(run, `Serializing payload to update run with id: ${runId}`);
1256
- await this.caller.call(async () => {
1257
- const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/${runId}`, {
1258
- method: "PATCH",
1259
- headers,
1260
- signal: AbortSignal.timeout(this.timeout_ms),
1261
- ...this.fetchOptions,
1262
- body
1263
- });
1264
- await raiseForStatus(res, "update run", true);
1265
- return res;
1266
- });
1267
- }
1268
- async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) {
1269
- assertUuid(runId);
1270
- let run = await this._get(`/runs/${runId}`);
1271
- if (loadChildRuns) {
1272
- run = await this._loadChildRuns(run);
1273
- }
1274
- return run;
1275
- }
1276
- async getRunUrl({ runId, run, projectOpts }) {
1277
- if (run !== void 0) {
1278
- let sessionId;
1279
- if (run.session_id) {
1280
- sessionId = run.session_id;
1281
- } else if (projectOpts?.projectName) {
1282
- sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id;
1283
- } else if (projectOpts?.projectId) {
1284
- sessionId = projectOpts?.projectId;
1285
- } else {
1286
- const project = await this.readProject({
1287
- projectName: getLangSmithEnvironmentVariable("PROJECT") || "default"
1288
- });
1289
- sessionId = project.id;
1290
- }
1291
- const tenantId = await this._getTenantId();
1292
- return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`;
1293
- } else if (runId !== void 0) {
1294
- const run_ = await this.readRun(runId);
1295
- if (!run_.app_path) {
1296
- throw new Error(`Run ${runId} has no app_path`);
1297
- }
1298
- const baseUrl = this.getHostUrl();
1299
- return `${baseUrl}${run_.app_path}`;
1300
- } else {
1301
- throw new Error("Must provide either runId or run");
1302
- }
1303
- }
1304
- async _loadChildRuns(run) {
1305
- const childRuns = await toArray(this.listRuns({
1306
- isRoot: false,
1307
- projectId: run.session_id,
1308
- traceId: run.trace_id
1309
- }));
1310
- const treemap = {};
1311
- const runs = {};
1312
- childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? ""));
1313
- for (const childRun of childRuns) {
1314
- if (childRun.parent_run_id === null || childRun.parent_run_id === void 0) {
1315
- throw new Error(`Child run ${childRun.id} has no parent`);
1316
- }
1317
- if (childRun.dotted_order?.startsWith(run.dotted_order ?? "") && childRun.id !== run.id) {
1318
- if (!(childRun.parent_run_id in treemap)) {
1319
- treemap[childRun.parent_run_id] = [];
1320
- }
1321
- treemap[childRun.parent_run_id].push(childRun);
1322
- runs[childRun.id] = childRun;
1323
- }
1324
- }
1325
- run.child_runs = treemap[run.id] || [];
1326
- for (const runId in treemap) {
1327
- if (runId !== run.id) {
1328
- runs[runId].child_runs = treemap[runId];
1329
- }
1330
- }
1331
- return run;
1332
- }
1333
- /**
1334
- * List runs from the LangSmith server.
1335
- * @param projectId - The ID of the project to filter by.
1336
- * @param projectName - The name of the project to filter by.
1337
- * @param parentRunId - The ID of the parent run to filter by.
1338
- * @param traceId - The ID of the trace to filter by.
1339
- * @param referenceExampleId - The ID of the reference example to filter by.
1340
- * @param startTime - The start time to filter by.
1341
- * @param isRoot - Indicates whether to only return root runs.
1342
- * @param runType - The run type to filter by.
1343
- * @param error - Indicates whether to filter by error runs.
1344
- * @param id - The ID of the run to filter by.
1345
- * @param query - The query string to filter by.
1346
- * @param filter - The filter string to apply to the run spans.
1347
- * @param traceFilter - The filter string to apply on the root run of the trace.
1348
- * @param treeFilter - The filter string to apply on other runs in the trace.
1349
- * @param limit - The maximum number of runs to retrieve.
1350
- * @returns {AsyncIterable<Run>} - The runs.
1351
- *
1352
- * @example
1353
- * // List all runs in a project
1354
- * const projectRuns = client.listRuns({ projectName: "<your_project>" });
1355
- *
1356
- * @example
1357
- * // List LLM and Chat runs in the last 24 hours
1358
- * const todaysLLMRuns = client.listRuns({
1359
- * projectName: "<your_project>",
1360
- * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000),
1361
- * run_type: "llm",
1362
- * });
1363
- *
1364
- * @example
1365
- * // List traces in a project
1366
- * const rootRuns = client.listRuns({
1367
- * projectName: "<your_project>",
1368
- * execution_order: 1,
1369
- * });
1370
- *
1371
- * @example
1372
- * // List runs without errors
1373
- * const correctRuns = client.listRuns({
1374
- * projectName: "<your_project>",
1375
- * error: false,
1376
- * });
1377
- *
1378
- * @example
1379
- * // List runs by run ID
1380
- * const runIds = [
1381
- * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836",
1382
- * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074",
1383
- * ];
1384
- * const selectedRuns = client.listRuns({ run_ids: runIds });
1385
- *
1386
- * @example
1387
- * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000
1388
- * const chainRuns = client.listRuns({
1389
- * projectName: "<your_project>",
1390
- * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))',
1391
- * });
1392
- *
1393
- * @example
1394
- * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1
1395
- * const goodExtractorRuns = client.listRuns({
1396
- * projectName: "<your_project>",
1397
- * filter: 'eq(name, "extractor")',
1398
- * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))',
1399
- * });
1400
- *
1401
- * @example
1402
- * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0
1403
- * const complexRuns = client.listRuns({
1404
- * projectName: "<your_project>",
1405
- * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))',
1406
- * });
1407
- *
1408
- * @example
1409
- * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds
1410
- * const taggedRuns = client.listRuns({
1411
- * projectName: "<your_project>",
1412
- * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))',
1413
- * });
1414
- */
1415
- async *listRuns(props) {
1416
- const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order } = props;
1417
- let projectIds = [];
1418
- if (projectId) {
1419
- projectIds = Array.isArray(projectId) ? projectId : [projectId];
1420
- }
1421
- if (projectName) {
1422
- const projectNames = Array.isArray(projectName) ? projectName : [projectName];
1423
- const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)));
1424
- projectIds.push(...projectIds_);
1425
- }
1426
- const default_select = [
1427
- "app_path",
1428
- "completion_cost",
1429
- "completion_tokens",
1430
- "dotted_order",
1431
- "end_time",
1432
- "error",
1433
- "events",
1434
- "extra",
1435
- "feedback_stats",
1436
- "first_token_time",
1437
- "id",
1438
- "inputs",
1439
- "name",
1440
- "outputs",
1441
- "parent_run_id",
1442
- "parent_run_ids",
1443
- "prompt_cost",
1444
- "prompt_tokens",
1445
- "reference_example_id",
1446
- "run_type",
1447
- "session_id",
1448
- "start_time",
1449
- "status",
1450
- "tags",
1451
- "total_cost",
1452
- "total_tokens",
1453
- "trace_id"
1454
- ];
1455
- const body = {
1456
- session: projectIds.length ? projectIds : null,
1457
- run_type: runType,
1458
- reference_example: referenceExampleId,
1459
- query,
1460
- filter,
1461
- trace_filter: traceFilter,
1462
- tree_filter: treeFilter,
1463
- execution_order: executionOrder,
1464
- parent_run: parentRunId,
1465
- start_time: startTime ? startTime.toISOString() : null,
1466
- error,
1467
- id,
1468
- limit,
1469
- trace: traceId,
1470
- select: select ? select : default_select,
1471
- is_root: isRoot,
1472
- order
1473
- };
1474
- if (body.select.includes("child_run_ids")) {
1475
- warnOnce("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");
1476
- }
1477
- let runsYielded = 0;
1478
- for await (const runs of this._getCursorPaginatedList("/runs/query", body)) {
1479
- if (limit) {
1480
- if (runsYielded >= limit) {
1481
- break;
1482
- }
1483
- if (runs.length + runsYielded > limit) {
1484
- const newRuns = runs.slice(0, limit - runsYielded);
1485
- yield* newRuns;
1486
- break;
1487
- }
1488
- runsYielded += runs.length;
1489
- yield* runs;
1490
- } else {
1491
- yield* runs;
1492
- }
1493
- }
1494
- }
1495
- async *listGroupRuns(props) {
1496
- const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset } = props;
1497
- const sessionId = projectId || (await this.readProject({ projectName })).id;
1498
- const baseBody = {
1499
- session_id: sessionId,
1500
- group_by: groupBy,
1501
- filter,
1502
- start_time: startTime ? startTime.toISOString() : null,
1503
- end_time: endTime ? endTime.toISOString() : null,
1504
- limit: Number(limit) || 100
1505
- };
1506
- let currentOffset = Number(offset) || 0;
1507
- const path = "/runs/group";
1508
- const url = `${this.apiUrl}${path}`;
1509
- while (true) {
1510
- const currentBody = {
1511
- ...baseBody,
1512
- offset: currentOffset
1513
- };
1514
- const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== void 0));
1515
- const body = JSON.stringify(filteredPayload);
1516
- const response = await this.caller.call(async () => {
1517
- const res = await this._fetch(url, {
1518
- method: "POST",
1519
- headers: { ...this.headers, "Content-Type": "application/json" },
1520
- signal: AbortSignal.timeout(this.timeout_ms),
1521
- ...this.fetchOptions,
1522
- body
1523
- });
1524
- await raiseForStatus(res, `Failed to fetch ${path}`);
1525
- return res;
1526
- });
1527
- const items = await response.json();
1528
- const { groups, total } = items;
1529
- if (groups.length === 0) {
1530
- break;
1531
- }
1532
- for (const thread of groups) {
1533
- yield thread;
1534
- }
1535
- currentOffset += groups.length;
1536
- if (currentOffset >= total) {
1537
- break;
1538
- }
1539
- }
1540
- }
1541
- async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType }) {
1542
- let projectIds_ = projectIds || [];
1543
- if (projectNames) {
1544
- projectIds_ = [
1545
- ...projectIds || [],
1546
- ...await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))
1547
- ];
1548
- }
1549
- const payload = {
1550
- id,
1551
- trace,
1552
- parent_run: parentRun,
1553
- run_type: runType,
1554
- session: projectIds_,
1555
- reference_example: referenceExampleIds,
1556
- start_time: startTime,
1557
- end_time: endTime,
1558
- error,
1559
- query,
1560
- filter,
1561
- trace_filter: traceFilter,
1562
- tree_filter: treeFilter,
1563
- is_root: isRoot,
1564
- data_source_type: dataSourceType
1565
- };
1566
- const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== void 0));
1567
- const body = JSON.stringify(filteredPayload);
1568
- const response = await this.caller.call(async () => {
1569
- const res = await this._fetch(`${this.apiUrl}/runs/stats`, {
1570
- method: "POST",
1571
- headers: { ...this.headers, "Content-Type": "application/json" },
1572
- signal: AbortSignal.timeout(this.timeout_ms),
1573
- ...this.fetchOptions,
1574
- body
1575
- });
1576
- await raiseForStatus(res, "get run stats");
1577
- return res;
1578
- });
1579
- const result = await response.json();
1580
- return result;
1581
- }
1582
- async shareRun(runId, { shareId } = {}) {
1583
- const data = {
1584
- run_id: runId,
1585
- share_token: shareId || uuid.v4()
1586
- };
1587
- assertUuid(runId);
1588
- const body = JSON.stringify(data);
1589
- const response = await this.caller.call(async () => {
1590
- const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, {
1591
- method: "PUT",
1592
- headers: this.headers,
1593
- signal: AbortSignal.timeout(this.timeout_ms),
1594
- ...this.fetchOptions,
1595
- body
1596
- });
1597
- await raiseForStatus(res, "share run");
1598
- return res;
1599
- });
1600
- const result = await response.json();
1601
- if (result === null || !("share_token" in result)) {
1602
- throw new Error("Invalid response from server");
1603
- }
1604
- return `${this.getHostUrl()}/public/${result["share_token"]}/r`;
1605
- }
1606
- async unshareRun(runId) {
1607
- assertUuid(runId);
1608
- await this.caller.call(async () => {
1609
- const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, {
1610
- method: "DELETE",
1611
- headers: this.headers,
1612
- signal: AbortSignal.timeout(this.timeout_ms),
1613
- ...this.fetchOptions
1614
- });
1615
- await raiseForStatus(res, "unshare run", true);
1616
- return res;
1617
- });
1618
- }
1619
- async readRunSharedLink(runId) {
1620
- assertUuid(runId);
1621
- const response = await this.caller.call(async () => {
1622
- const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, {
1623
- method: "GET",
1624
- headers: this.headers,
1625
- signal: AbortSignal.timeout(this.timeout_ms),
1626
- ...this.fetchOptions
1627
- });
1628
- await raiseForStatus(res, "read run shared link");
1629
- return res;
1630
- });
1631
- const result = await response.json();
1632
- if (result === null || !("share_token" in result)) {
1633
- return void 0;
1634
- }
1635
- return `${this.getHostUrl()}/public/${result["share_token"]}/r`;
1636
- }
1637
- async listSharedRuns(shareToken, { runIds } = {}) {
1638
- const queryParams = new URLSearchParams({
1639
- share_token: shareToken
1640
- });
1641
- if (runIds !== void 0) {
1642
- for (const runId of runIds) {
1643
- queryParams.append("id", runId);
1644
- }
1645
- }
1646
- assertUuid(shareToken);
1647
- const response = await this.caller.call(async () => {
1648
- const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/runs${queryParams}`, {
1649
- method: "GET",
1650
- headers: this.headers,
1651
- signal: AbortSignal.timeout(this.timeout_ms),
1652
- ...this.fetchOptions
1653
- });
1654
- await raiseForStatus(res, "list shared runs");
1655
- return res;
1656
- });
1657
- const runs = await response.json();
1658
- return runs;
1659
- }
1660
- async readDatasetSharedSchema(datasetId, datasetName) {
1661
- if (!datasetId && !datasetName) {
1662
- throw new Error("Either datasetId or datasetName must be given");
1663
- }
1664
- if (!datasetId) {
1665
- const dataset = await this.readDataset({ datasetName });
1666
- datasetId = dataset.id;
1667
- }
1668
- assertUuid(datasetId);
1669
- const response = await this.caller.call(async () => {
1670
- const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, {
1671
- method: "GET",
1672
- headers: this.headers,
1673
- signal: AbortSignal.timeout(this.timeout_ms),
1674
- ...this.fetchOptions
1675
- });
1676
- await raiseForStatus(res, "read dataset shared schema");
1677
- return res;
1678
- });
1679
- const shareSchema = await response.json();
1680
- shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;
1681
- return shareSchema;
1682
- }
1683
- async shareDataset(datasetId, datasetName) {
1684
- if (!datasetId && !datasetName) {
1685
- throw new Error("Either datasetId or datasetName must be given");
1686
- }
1687
- if (!datasetId) {
1688
- const dataset = await this.readDataset({ datasetName });
1689
- datasetId = dataset.id;
1690
- }
1691
- const data = {
1692
- dataset_id: datasetId
1693
- };
1694
- assertUuid(datasetId);
1695
- const body = JSON.stringify(data);
1696
- const response = await this.caller.call(async () => {
1697
- const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, {
1698
- method: "PUT",
1699
- headers: this.headers,
1700
- signal: AbortSignal.timeout(this.timeout_ms),
1701
- ...this.fetchOptions,
1702
- body
1703
- });
1704
- await raiseForStatus(res, "share dataset");
1705
- return res;
1706
- });
1707
- const shareSchema = await response.json();
1708
- shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`;
1709
- return shareSchema;
1710
- }
1711
- async unshareDataset(datasetId) {
1712
- assertUuid(datasetId);
1713
- await this.caller.call(async () => {
1714
- const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, {
1715
- method: "DELETE",
1716
- headers: this.headers,
1717
- signal: AbortSignal.timeout(this.timeout_ms),
1718
- ...this.fetchOptions
1719
- });
1720
- await raiseForStatus(res, "unshare dataset", true);
1721
- return res;
1722
- });
1723
- }
1724
- async readSharedDataset(shareToken) {
1725
- assertUuid(shareToken);
1726
- const response = await this.caller.call(async () => {
1727
- const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/datasets`, {
1728
- method: "GET",
1729
- headers: this.headers,
1730
- signal: AbortSignal.timeout(this.timeout_ms),
1731
- ...this.fetchOptions
1732
- });
1733
- await raiseForStatus(res, "read shared dataset");
1734
- return res;
1735
- });
1736
- const dataset = await response.json();
1737
- return dataset;
1738
- }
1739
- /**
1740
- * Get shared examples.
1741
- *
1742
- * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public.
1743
- * @param {Object} [options] Additional options for listing the examples.
1744
- * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by.
1745
- * @returns {Promise<Example[]>} The shared examples.
1746
- */
1747
- async listSharedExamples(shareToken, options) {
1748
- const params = {};
1749
- if (options?.exampleIds) {
1750
- params.id = options.exampleIds;
1751
- }
1752
- const urlParams = new URLSearchParams();
1753
- Object.entries(params).forEach(([key, value]) => {
1754
- if (Array.isArray(value)) {
1755
- value.forEach((v) => urlParams.append(key, v));
1756
- } else {
1757
- urlParams.append(key, value);
1758
- }
1759
- });
1760
- const response = await this.caller.call(async () => {
1761
- const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, {
1762
- method: "GET",
1763
- headers: this.headers,
1764
- signal: AbortSignal.timeout(this.timeout_ms),
1765
- ...this.fetchOptions
1766
- });
1767
- await raiseForStatus(res, "list shared examples");
1768
- return res;
1769
- });
1770
- const result = await response.json();
1771
- if (!response.ok) {
1772
- if ("detail" in result) {
1773
- throw new Error(`Failed to list shared examples.
1774
- Status: ${response.status}
1775
- Message: ${Array.isArray(result.detail) ? result.detail.join("\n") : "Unspecified error"}`);
1776
- }
1777
- throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`);
1778
- }
1779
- return result.map((example) => ({
1780
- ...example,
1781
- _hostUrl: this.getHostUrl()
1782
- }));
1783
- }
1784
- async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null }) {
1785
- const upsert_ = upsert ? `?upsert=true` : "";
1786
- const endpoint = `${this.apiUrl}/sessions${upsert_}`;
1787
- const extra = projectExtra || {};
1788
- if (metadata) {
1789
- extra["metadata"] = metadata;
1790
- }
1791
- const body = {
1792
- name: projectName,
1793
- extra,
1794
- description
1795
- };
1796
- if (referenceDatasetId !== null) {
1797
- body["reference_dataset_id"] = referenceDatasetId;
1798
- }
1799
- const serializedBody = JSON.stringify(body);
1800
- const response = await this.caller.call(async () => {
1801
- const res = await this._fetch(endpoint, {
1802
- method: "POST",
1803
- headers: { ...this.headers, "Content-Type": "application/json" },
1804
- signal: AbortSignal.timeout(this.timeout_ms),
1805
- ...this.fetchOptions,
1806
- body: serializedBody
1807
- });
1808
- await raiseForStatus(res, "create project");
1809
- return res;
1810
- });
1811
- const result = await response.json();
1812
- return result;
1813
- }
1814
- async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null }) {
1815
- const endpoint = `${this.apiUrl}/sessions/${projectId}`;
1816
- let extra = projectExtra;
1817
- if (metadata) {
1818
- extra = { ...extra || {}, metadata };
1819
- }
1820
- const body = JSON.stringify({
1821
- name,
1822
- extra,
1823
- description,
1824
- end_time: endTime ? new Date(endTime).toISOString() : null
1825
- });
1826
- const response = await this.caller.call(async () => {
1827
- const res = await this._fetch(endpoint, {
1828
- method: "PATCH",
1829
- headers: { ...this.headers, "Content-Type": "application/json" },
1830
- signal: AbortSignal.timeout(this.timeout_ms),
1831
- ...this.fetchOptions,
1832
- body
1833
- });
1834
- await raiseForStatus(res, "update project");
1835
- return res;
1836
- });
1837
- const result = await response.json();
1838
- return result;
1839
- }
1840
- async hasProject({ projectId, projectName }) {
1841
- let path = "/sessions";
1842
- const params = new URLSearchParams();
1843
- if (projectId !== void 0 && projectName !== void 0) {
1844
- throw new Error("Must provide either projectName or projectId, not both");
1845
- } else if (projectId !== void 0) {
1846
- assertUuid(projectId);
1847
- path += `/${projectId}`;
1848
- } else if (projectName !== void 0) {
1849
- params.append("name", projectName);
1850
- } else {
1851
- throw new Error("Must provide projectName or projectId");
1852
- }
1853
- const response = await this.caller.call(async () => {
1854
- const res = await this._fetch(`${this.apiUrl}${path}?${params}`, {
1855
- method: "GET",
1856
- headers: this.headers,
1857
- signal: AbortSignal.timeout(this.timeout_ms),
1858
- ...this.fetchOptions
1859
- });
1860
- await raiseForStatus(res, "has project");
1861
- return res;
1862
- });
1863
- try {
1864
- const result = await response.json();
1865
- if (!response.ok) {
1866
- return false;
1867
- }
1868
- if (Array.isArray(result)) {
1869
- return result.length > 0;
1870
- }
1871
- return true;
1872
- } catch (e) {
1873
- return false;
1874
- }
1875
- }
1876
- async readProject({ projectId, projectName, includeStats }) {
1877
- let path = "/sessions";
1878
- const params = new URLSearchParams();
1879
- if (projectId !== void 0 && projectName !== void 0) {
1880
- throw new Error("Must provide either projectName or projectId, not both");
1881
- } else if (projectId !== void 0) {
1882
- assertUuid(projectId);
1883
- path += `/${projectId}`;
1884
- } else if (projectName !== void 0) {
1885
- params.append("name", projectName);
1886
- } else {
1887
- throw new Error("Must provide projectName or projectId");
1888
- }
1889
- if (includeStats !== void 0) {
1890
- params.append("include_stats", includeStats.toString());
1891
- }
1892
- const response = await this._get(path, params);
1893
- let result;
1894
- if (Array.isArray(response)) {
1895
- if (response.length === 0) {
1896
- throw new Error(`Project[id=${projectId}, name=${projectName}] not found`);
1897
- }
1898
- result = response[0];
1899
- } else {
1900
- result = response;
1901
- }
1902
- return result;
1903
- }
1904
- async getProjectUrl({ projectId, projectName }) {
1905
- if (projectId === void 0 && projectName === void 0) {
1906
- throw new Error("Must provide either projectName or projectId");
1907
- }
1908
- const project = await this.readProject({ projectId, projectName });
1909
- const tenantId = await this._getTenantId();
1910
- return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`;
1911
- }
1912
- async getDatasetUrl({ datasetId, datasetName }) {
1913
- if (datasetId === void 0 && datasetName === void 0) {
1914
- throw new Error("Must provide either datasetName or datasetId");
1915
- }
1916
- const dataset = await this.readDataset({ datasetId, datasetName });
1917
- const tenantId = await this._getTenantId();
1918
- return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`;
1919
- }
1920
- async _getTenantId() {
1921
- if (this._tenantId !== null) {
1922
- return this._tenantId;
1923
- }
1924
- const queryParams = new URLSearchParams({ limit: "1" });
1925
- for await (const projects of this._getPaginated("/sessions", queryParams)) {
1926
- this._tenantId = projects[0].tenant_id;
1927
- return projects[0].tenant_id;
1928
- }
1929
- throw new Error("No projects found to resolve tenant.");
1930
- }
1931
- async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, includeStats, datasetVersion, referenceFree, metadata } = {}) {
1932
- const params = new URLSearchParams();
1933
- if (projectIds !== void 0) {
1934
- for (const projectId of projectIds) {
1935
- params.append("id", projectId);
1936
- }
1937
- }
1938
- if (name !== void 0) {
1939
- params.append("name", name);
1940
- }
1941
- if (nameContains !== void 0) {
1942
- params.append("name_contains", nameContains);
1943
- }
1944
- if (referenceDatasetId !== void 0) {
1945
- params.append("reference_dataset", referenceDatasetId);
1946
- } else if (referenceDatasetName !== void 0) {
1947
- const dataset = await this.readDataset({
1948
- datasetName: referenceDatasetName
1949
- });
1950
- params.append("reference_dataset", dataset.id);
1951
- }
1952
- if (includeStats !== void 0) {
1953
- params.append("include_stats", includeStats.toString());
1954
- }
1955
- if (datasetVersion !== void 0) {
1956
- params.append("dataset_version", datasetVersion);
1957
- }
1958
- if (referenceFree !== void 0) {
1959
- params.append("reference_free", referenceFree.toString());
1960
- }
1961
- if (metadata !== void 0) {
1962
- params.append("metadata", JSON.stringify(metadata));
1963
- }
1964
- for await (const projects of this._getPaginated("/sessions", params)) {
1965
- yield* projects;
1966
- }
1967
- }
1968
- async deleteProject({ projectId, projectName }) {
1969
- let projectId_;
1970
- if (projectId === void 0 && projectName === void 0) {
1971
- throw new Error("Must provide projectName or projectId");
1972
- } else if (projectId !== void 0 && projectName !== void 0) {
1973
- throw new Error("Must provide either projectName or projectId, not both");
1974
- } else if (projectId === void 0) {
1975
- projectId_ = (await this.readProject({ projectName })).id;
1976
- } else {
1977
- projectId_ = projectId;
1978
- }
1979
- assertUuid(projectId_);
1980
- await this.caller.call(async () => {
1981
- const res = await this._fetch(`${this.apiUrl}/sessions/${projectId_}`, {
1982
- method: "DELETE",
1983
- headers: this.headers,
1984
- signal: AbortSignal.timeout(this.timeout_ms),
1985
- ...this.fetchOptions
1986
- });
1987
- await raiseForStatus(res, `delete session ${projectId_} (${projectName})`, true);
1988
- return res;
1989
- });
1990
- }
1991
- async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name }) {
1992
- const url = `${this.apiUrl}/datasets/upload`;
1993
- const formData = new FormData();
1994
- formData.append("file", csvFile, fileName);
1995
- inputKeys.forEach((key) => {
1996
- formData.append("input_keys", key);
1997
- });
1998
- outputKeys.forEach((key) => {
1999
- formData.append("output_keys", key);
2000
- });
2001
- if (description) {
2002
- formData.append("description", description);
2003
- }
2004
- if (dataType) {
2005
- formData.append("data_type", dataType);
2006
- }
2007
- if (name) {
2008
- formData.append("name", name);
2009
- }
2010
- const response = await this.caller.call(async () => {
2011
- const res = await this._fetch(url, {
2012
- method: "POST",
2013
- headers: this.headers,
2014
- signal: AbortSignal.timeout(this.timeout_ms),
2015
- ...this.fetchOptions,
2016
- body: formData
2017
- });
2018
- await raiseForStatus(res, "upload CSV");
2019
- return res;
2020
- });
2021
- const result = await response.json();
2022
- return result;
2023
- }
2024
- async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata } = {}) {
2025
- const body = {
2026
- name,
2027
- description,
2028
- extra: metadata ? { metadata } : void 0
2029
- };
2030
- if (dataType) {
2031
- body.data_type = dataType;
2032
- }
2033
- if (inputsSchema) {
2034
- body.inputs_schema_definition = inputsSchema;
2035
- }
2036
- if (outputsSchema) {
2037
- body.outputs_schema_definition = outputsSchema;
2038
- }
2039
- const serializedBody = JSON.stringify(body);
2040
- const response = await this.caller.call(async () => {
2041
- const res = await this._fetch(`${this.apiUrl}/datasets`, {
2042
- method: "POST",
2043
- headers: { ...this.headers, "Content-Type": "application/json" },
2044
- signal: AbortSignal.timeout(this.timeout_ms),
2045
- ...this.fetchOptions,
2046
- body: serializedBody
2047
- });
2048
- await raiseForStatus(res, "create dataset");
2049
- return res;
2050
- });
2051
- const result = await response.json();
2052
- return result;
2053
- }
2054
- async readDataset({ datasetId, datasetName }) {
2055
- let path = "/datasets";
2056
- const params = new URLSearchParams({ limit: "1" });
2057
- if (datasetId && datasetName) {
2058
- throw new Error("Must provide either datasetName or datasetId, not both");
2059
- } else if (datasetId) {
2060
- assertUuid(datasetId);
2061
- path += `/${datasetId}`;
2062
- } else if (datasetName) {
2063
- params.append("name", datasetName);
2064
- } else {
2065
- throw new Error("Must provide datasetName or datasetId");
2066
- }
2067
- const response = await this._get(path, params);
2068
- let result;
2069
- if (Array.isArray(response)) {
2070
- if (response.length === 0) {
2071
- throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`);
2072
- }
2073
- result = response[0];
2074
- } else {
2075
- result = response;
2076
- }
2077
- return result;
2078
- }
2079
- async hasDataset({ datasetId, datasetName }) {
2080
- try {
2081
- await this.readDataset({ datasetId, datasetName });
2082
- return true;
2083
- } catch (e) {
2084
- if (
2085
- // eslint-disable-next-line no-instanceof/no-instanceof
2086
- e instanceof Error && e.message.toLocaleLowerCase().includes("not found")
2087
- ) {
2088
- return false;
2089
- }
2090
- throw e;
2091
- }
2092
- }
2093
- async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion }) {
2094
- let datasetId_ = datasetId;
2095
- if (datasetId_ === void 0 && datasetName === void 0) {
2096
- throw new Error("Must provide either datasetName or datasetId");
2097
- } else if (datasetId_ !== void 0 && datasetName !== void 0) {
2098
- throw new Error("Must provide either datasetName or datasetId, not both");
2099
- } else if (datasetId_ === void 0) {
2100
- const dataset = await this.readDataset({ datasetName });
2101
- datasetId_ = dataset.id;
2102
- }
2103
- const urlParams = new URLSearchParams({
2104
- from_version: typeof fromVersion === "string" ? fromVersion : fromVersion.toISOString(),
2105
- to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString()
2106
- });
2107
- const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams);
2108
- return response;
2109
- }
2110
- async readDatasetOpenaiFinetuning({ datasetId, datasetName }) {
2111
- const path = "/datasets";
2112
- if (datasetId !== void 0) ;
2113
- else if (datasetName !== void 0) {
2114
- datasetId = (await this.readDataset({ datasetName })).id;
2115
- } else {
2116
- throw new Error("Must provide either datasetName or datasetId");
2117
- }
2118
- const response = await this._getResponse(`${path}/${datasetId}/openai_ft`);
2119
- const datasetText = await response.text();
2120
- const dataset = datasetText.trim().split("\n").map((line) => JSON.parse(line));
2121
- return dataset;
2122
- }
2123
- async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata } = {}) {
2124
- const path = "/datasets";
2125
- const params = new URLSearchParams({
2126
- limit: limit.toString(),
2127
- offset: offset.toString()
2128
- });
2129
- if (datasetIds !== void 0) {
2130
- for (const id_ of datasetIds) {
2131
- params.append("id", id_);
2132
- }
2133
- }
2134
- if (datasetName !== void 0) {
2135
- params.append("name", datasetName);
2136
- }
2137
- if (datasetNameContains !== void 0) {
2138
- params.append("name_contains", datasetNameContains);
2139
- }
2140
- if (metadata !== void 0) {
2141
- params.append("metadata", JSON.stringify(metadata));
2142
- }
2143
- for await (const datasets of this._getPaginated(path, params)) {
2144
- yield* datasets;
2145
- }
2146
- }
2147
- /**
2148
- * Update a dataset
2149
- * @param props The dataset details to update
2150
- * @returns The updated dataset
2151
- */
2152
- async updateDataset(props) {
2153
- const { datasetId, datasetName, ...update } = props;
2154
- if (!datasetId && !datasetName) {
2155
- throw new Error("Must provide either datasetName or datasetId");
2156
- }
2157
- const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id;
2158
- assertUuid(_datasetId);
2159
- const body = JSON.stringify(update);
2160
- const response = await this.caller.call(async () => {
2161
- const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}`, {
2162
- method: "PATCH",
2163
- headers: { ...this.headers, "Content-Type": "application/json" },
2164
- signal: AbortSignal.timeout(this.timeout_ms),
2165
- ...this.fetchOptions,
2166
- body
2167
- });
2168
- await raiseForStatus(res, "update dataset");
2169
- return res;
2170
- });
2171
- return await response.json();
2172
- }
2173
- /**
2174
- * Updates a tag on a dataset.
2175
- *
2176
- * If the tag is already assigned to a different version of this dataset,
2177
- * the tag will be moved to the new version. The as_of parameter is used to
2178
- * determine which version of the dataset to apply the new tags to.
2179
- *
2180
- * It must be an exact version of the dataset to succeed. You can
2181
- * use the "readDatasetVersion" method to find the exact version
2182
- * to apply the tags to.
2183
- * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided.
2184
- * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided.
2185
- * @param params.asOf The timestamp of the dataset to apply the new tags to.
2186
- * @param params.tag The new tag to apply to the dataset.
2187
- */
2188
- async updateDatasetTag(props) {
2189
- const { datasetId, datasetName, asOf, tag } = props;
2190
- if (!datasetId && !datasetName) {
2191
- throw new Error("Must provide either datasetName or datasetId");
2192
- }
2193
- const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id;
2194
- assertUuid(_datasetId);
2195
- const body = JSON.stringify({
2196
- as_of: typeof asOf === "string" ? asOf : asOf.toISOString(),
2197
- tag
2198
- });
2199
- await this.caller.call(async () => {
2200
- const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}/tags`, {
2201
- method: "PUT",
2202
- headers: { ...this.headers, "Content-Type": "application/json" },
2203
- signal: AbortSignal.timeout(this.timeout_ms),
2204
- ...this.fetchOptions,
2205
- body
2206
- });
2207
- await raiseForStatus(res, "update dataset tags", true);
2208
- return res;
2209
- });
2210
- }
2211
- async deleteDataset({ datasetId, datasetName }) {
2212
- let path = "/datasets";
2213
- let datasetId_ = datasetId;
2214
- if (datasetId !== void 0 && datasetName !== void 0) {
2215
- throw new Error("Must provide either datasetName or datasetId, not both");
2216
- } else if (datasetName !== void 0) {
2217
- const dataset = await this.readDataset({ datasetName });
2218
- datasetId_ = dataset.id;
2219
- }
2220
- if (datasetId_ !== void 0) {
2221
- assertUuid(datasetId_);
2222
- path += `/${datasetId_}`;
2223
- } else {
2224
- throw new Error("Must provide datasetName or datasetId");
2225
- }
2226
- await this.caller.call(async () => {
2227
- const res = await this._fetch(this.apiUrl + path, {
2228
- method: "DELETE",
2229
- headers: this.headers,
2230
- signal: AbortSignal.timeout(this.timeout_ms),
2231
- ...this.fetchOptions
2232
- });
2233
- await raiseForStatus(res, `delete ${path}`, true);
2234
- return res;
2235
- });
2236
- }
2237
- async indexDataset({ datasetId, datasetName, tag }) {
2238
- let datasetId_ = datasetId;
2239
- if (!datasetId_ && !datasetName) {
2240
- throw new Error("Must provide either datasetName or datasetId");
2241
- } else if (datasetId_ && datasetName) {
2242
- throw new Error("Must provide either datasetName or datasetId, not both");
2243
- } else if (!datasetId_) {
2244
- const dataset = await this.readDataset({ datasetName });
2245
- datasetId_ = dataset.id;
2246
- }
2247
- assertUuid(datasetId_);
2248
- const data = {
2249
- tag
2250
- };
2251
- const body = JSON.stringify(data);
2252
- const response = await this.caller.call(async () => {
2253
- const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/index`, {
2254
- method: "POST",
2255
- headers: { ...this.headers, "Content-Type": "application/json" },
2256
- signal: AbortSignal.timeout(this.timeout_ms),
2257
- ...this.fetchOptions,
2258
- body
2259
- });
2260
- await raiseForStatus(res, "index dataset");
2261
- return res;
2262
- });
2263
- await response.json();
2264
- }
2265
- /**
2266
- * Lets you run a similarity search query on a dataset.
2267
- *
2268
- * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing.
2269
- *
2270
- * @param inputs The input on which to run the similarity search. Must have the
2271
- * same schema as the dataset.
2272
- *
2273
- * @param datasetId The dataset to search for similar examples.
2274
- *
2275
- * @param limit The maximum number of examples to return. Will return the top `limit` most
2276
- * similar examples in order of most similar to least similar. If no similar
2277
- * examples are found, random examples will be returned.
2278
- *
2279
- * @param filter A filter string to apply to the search. Only examples will be returned that
2280
- * match the filter string. Some examples of filters
2281
- *
2282
- * - eq(metadata.mykey, "value")
2283
- * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value"))
2284
- * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue"))
2285
- *
2286
- * @returns A list of similar examples.
2287
- *
2288
- *
2289
- * @example
2290
- * dataset_id = "123e4567-e89b-12d3-a456-426614174000"
2291
- * inputs = {"text": "How many people live in Berlin?"}
2292
- * limit = 5
2293
- * examples = await client.similarExamples(inputs, dataset_id, limit)
2294
- */
2295
- async similarExamples(inputs, datasetId, limit, { filter } = {}) {
2296
- const data = {
2297
- limit,
2298
- inputs
2299
- };
2300
- if (filter !== void 0) {
2301
- data["filter"] = filter;
2302
- }
2303
- assertUuid(datasetId);
2304
- const body = JSON.stringify(data);
2305
- const response = await this.caller.call(async () => {
2306
- const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/search`, {
2307
- headers: { ...this.headers, "Content-Type": "application/json" },
2308
- signal: AbortSignal.timeout(this.timeout_ms),
2309
- ...this.fetchOptions,
2310
- method: "POST",
2311
- body
2312
- });
2313
- await raiseForStatus(res, "fetch similar examples");
2314
- return res;
2315
- });
2316
- const result = await response.json();
2317
- return result["examples"];
2318
- }
2319
- async createExample(inputsOrUpdate, outputs, options) {
2320
- if (isExampleCreate(inputsOrUpdate)) {
2321
- if (outputs !== void 0 || options !== void 0) {
2322
- throw new Error("Cannot provide outputs or options when using ExampleCreate object");
2323
- }
2324
- }
2325
- let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id;
2326
- const datasetName_ = outputs ? options?.datasetName : inputsOrUpdate.dataset_name;
2327
- if (datasetId_ === void 0 && datasetName_ === void 0) {
2328
- throw new Error("Must provide either datasetName or datasetId");
2329
- } else if (datasetId_ !== void 0 && datasetName_ !== void 0) {
2330
- throw new Error("Must provide either datasetName or datasetId, not both");
2331
- } else if (datasetId_ === void 0) {
2332
- const dataset = await this.readDataset({ datasetName: datasetName_ });
2333
- datasetId_ = dataset.id;
2334
- }
2335
- const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || /* @__PURE__ */ new Date();
2336
- let data;
2337
- if (!isExampleCreate(inputsOrUpdate)) {
2338
- data = {
2339
- inputs: inputsOrUpdate,
2340
- outputs,
2341
- created_at: createdAt_?.toISOString(),
2342
- id: options?.exampleId,
2343
- metadata: options?.metadata,
2344
- split: options?.split,
2345
- source_run_id: options?.sourceRunId,
2346
- use_source_run_io: options?.useSourceRunIO,
2347
- use_source_run_attachments: options?.useSourceRunAttachments,
2348
- attachments: options?.attachments
2349
- };
2350
- } else {
2351
- data = inputsOrUpdate;
2352
- }
2353
- const response = await this._uploadExamplesMultipart(datasetId_, [data]);
2354
- const example = await this.readExample(response.example_ids?.[0] ?? uuid.v4());
2355
- return example;
2356
- }
2357
- async createExamples(propsOrUploads) {
2358
- if (Array.isArray(propsOrUploads)) {
2359
- if (propsOrUploads.length === 0) {
2360
- return [];
2361
- }
2362
- const uploads = propsOrUploads;
2363
- let datasetId_2 = uploads[0].dataset_id;
2364
- const datasetName_2 = uploads[0].dataset_name;
2365
- if (datasetId_2 === void 0 && datasetName_2 === void 0) {
2366
- throw new Error("Must provide either datasetName or datasetId");
2367
- } else if (datasetId_2 !== void 0 && datasetName_2 !== void 0) {
2368
- throw new Error("Must provide either datasetName or datasetId, not both");
2369
- } else if (datasetId_2 === void 0) {
2370
- const dataset = await this.readDataset({ datasetName: datasetName_2 });
2371
- datasetId_2 = dataset.id;
2372
- }
2373
- const response2 = await this._uploadExamplesMultipart(datasetId_2, uploads);
2374
- const examples2 = await Promise.all(response2.example_ids.map((id) => this.readExample(id)));
2375
- return examples2;
2376
- }
2377
- const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName } = propsOrUploads;
2378
- if (inputs === void 0) {
2379
- throw new Error("Must provide inputs when using legacy parameters");
2380
- }
2381
- let datasetId_ = datasetId;
2382
- const datasetName_ = datasetName;
2383
- if (datasetId_ === void 0 && datasetName_ === void 0) {
2384
- throw new Error("Must provide either datasetName or datasetId");
2385
- } else if (datasetId_ !== void 0 && datasetName_ !== void 0) {
2386
- throw new Error("Must provide either datasetName or datasetId, not both");
2387
- } else if (datasetId_ === void 0) {
2388
- const dataset = await this.readDataset({ datasetName: datasetName_ });
2389
- datasetId_ = dataset.id;
2390
- }
2391
- const formattedExamples = inputs.map((input, idx) => {
2392
- return {
2393
- dataset_id: datasetId_,
2394
- inputs: input,
2395
- outputs: outputs?.[idx],
2396
- metadata: metadata?.[idx],
2397
- split: splits?.[idx],
2398
- id: exampleIds?.[idx],
2399
- attachments: attachments?.[idx],
2400
- source_run_id: sourceRunIds?.[idx],
2401
- use_source_run_io: useSourceRunIOs?.[idx],
2402
- use_source_run_attachments: useSourceRunAttachments?.[idx]
2403
- };
2404
- });
2405
- const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples);
2406
- const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id)));
2407
- return examples;
2408
- }
2409
- async createLLMExample(input, generation, options) {
2410
- return this.createExample({ input }, { output: generation }, options);
2411
- }
2412
- async createChatExample(input, generations, options) {
2413
- const finalInput = input.map((message) => {
2414
- if (isLangChainMessage(message)) {
2415
- return convertLangChainMessageToExample(message);
2416
- }
2417
- return message;
2418
- });
2419
- const finalOutput = isLangChainMessage(generations) ? convertLangChainMessageToExample(generations) : generations;
2420
- return this.createExample({ input: finalInput }, { output: finalOutput }, options);
2421
- }
2422
- async readExample(exampleId) {
2423
- assertUuid(exampleId);
2424
- const path = `/examples/${exampleId}`;
2425
- const rawExample = await this._get(path);
2426
- const { attachment_urls, ...rest } = rawExample;
2427
- const example = rest;
2428
- if (attachment_urls) {
2429
- example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => {
2430
- acc[key.slice("attachment.".length)] = {
2431
- presigned_url: value.presigned_url,
2432
- mime_type: value.mime_type
2433
- };
2434
- return acc;
2435
- }, {});
2436
- }
2437
- return example;
2438
- }
2439
- async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments } = {}) {
2440
- let datasetId_;
2441
- if (datasetId !== void 0 && datasetName !== void 0) {
2442
- throw new Error("Must provide either datasetName or datasetId, not both");
2443
- } else if (datasetId !== void 0) {
2444
- datasetId_ = datasetId;
2445
- } else if (datasetName !== void 0) {
2446
- const dataset = await this.readDataset({ datasetName });
2447
- datasetId_ = dataset.id;
2448
- } else {
2449
- throw new Error("Must provide a datasetName or datasetId");
2450
- }
2451
- const params = new URLSearchParams({ dataset: datasetId_ });
2452
- const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0;
2453
- if (dataset_version) {
2454
- params.append("as_of", dataset_version);
2455
- }
2456
- const inlineS3Urls_ = inlineS3Urls ?? true;
2457
- params.append("inline_s3_urls", inlineS3Urls_.toString());
2458
- if (exampleIds !== void 0) {
2459
- for (const id_ of exampleIds) {
2460
- params.append("id", id_);
2461
- }
2462
- }
2463
- if (splits !== void 0) {
2464
- for (const split of splits) {
2465
- params.append("splits", split);
2466
- }
2467
- }
2468
- if (metadata !== void 0) {
2469
- const serializedMetadata = JSON.stringify(metadata);
2470
- params.append("metadata", serializedMetadata);
2471
- }
2472
- if (limit !== void 0) {
2473
- params.append("limit", limit.toString());
2474
- }
2475
- if (offset !== void 0) {
2476
- params.append("offset", offset.toString());
2477
- }
2478
- if (filter !== void 0) {
2479
- params.append("filter", filter);
2480
- }
2481
- if (includeAttachments === true) {
2482
- ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field));
2483
- }
2484
- let i = 0;
2485
- for await (const rawExamples of this._getPaginated("/examples", params)) {
2486
- for (const rawExample of rawExamples) {
2487
- const { attachment_urls, ...rest } = rawExample;
2488
- const example = rest;
2489
- if (attachment_urls) {
2490
- example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => {
2491
- acc[key.slice("attachment.".length)] = {
2492
- presigned_url: value.presigned_url,
2493
- mime_type: value.mime_type || void 0
2494
- };
2495
- return acc;
2496
- }, {});
2497
- }
2498
- yield example;
2499
- i++;
2500
- }
2501
- if (limit !== void 0 && i >= limit) {
2502
- break;
2503
- }
2504
- }
2505
- }
2506
- async deleteExample(exampleId) {
2507
- assertUuid(exampleId);
2508
- const path = `/examples/${exampleId}`;
2509
- await this.caller.call(async () => {
2510
- const res = await this._fetch(this.apiUrl + path, {
2511
- method: "DELETE",
2512
- headers: this.headers,
2513
- signal: AbortSignal.timeout(this.timeout_ms),
2514
- ...this.fetchOptions
2515
- });
2516
- await raiseForStatus(res, `delete ${path}`, true);
2517
- return res;
2518
- });
2519
- }
2520
- /**
2521
- * Delete multiple examples by ID.
2522
- * @param exampleIds - The IDs of the examples to delete
2523
- * @param options - Optional settings for deletion
2524
- * @param options.hardDelete - If true, permanently delete examples. If false (default), soft delete them.
2525
- */
2526
- async deleteExamples(exampleIds, options) {
2527
- exampleIds.forEach((id) => assertUuid(id));
2528
- if (options?.hardDelete) {
2529
- const path = this._getPlatformEndpointPath("datasets/examples/delete");
2530
- await this.caller.call(async () => {
2531
- const res = await this._fetch(`${this.apiUrl}${path}`, {
2532
- method: "POST",
2533
- headers: { ...this.headers, "Content-Type": "application/json" },
2534
- body: JSON.stringify({
2535
- example_ids: exampleIds,
2536
- hard_delete: true
2537
- }),
2538
- signal: AbortSignal.timeout(this.timeout_ms),
2539
- ...this.fetchOptions
2540
- });
2541
- await raiseForStatus(res, "hard delete examples", true);
2542
- return res;
2543
- });
2544
- } else {
2545
- const params = new URLSearchParams();
2546
- exampleIds.forEach((id) => params.append("example_ids", id));
2547
- await this.caller.call(async () => {
2548
- const res = await this._fetch(`${this.apiUrl}/examples?${params.toString()}`, {
2549
- method: "DELETE",
2550
- headers: this.headers,
2551
- signal: AbortSignal.timeout(this.timeout_ms),
2552
- ...this.fetchOptions
2553
- });
2554
- await raiseForStatus(res, "delete examples", true);
2555
- return res;
2556
- });
2557
- }
2558
- }
2559
- async updateExample(exampleIdOrUpdate, update) {
2560
- let exampleId;
2561
- if (update) {
2562
- exampleId = exampleIdOrUpdate;
2563
- } else {
2564
- exampleId = exampleIdOrUpdate.id;
2565
- }
2566
- assertUuid(exampleId);
2567
- let updateToUse;
2568
- if (update) {
2569
- updateToUse = { id: exampleId, ...update };
2570
- } else {
2571
- updateToUse = exampleIdOrUpdate;
2572
- }
2573
- let datasetId;
2574
- if (updateToUse.dataset_id !== void 0) {
2575
- datasetId = updateToUse.dataset_id;
2576
- } else {
2577
- const example = await this.readExample(exampleId);
2578
- datasetId = example.dataset_id;
2579
- }
2580
- return this._updateExamplesMultipart(datasetId, [updateToUse]);
2581
- }
2582
- async updateExamples(update) {
2583
- let datasetId;
2584
- if (update[0].dataset_id === void 0) {
2585
- const example = await this.readExample(update[0].id);
2586
- datasetId = example.dataset_id;
2587
- } else {
2588
- datasetId = update[0].dataset_id;
2589
- }
2590
- return this._updateExamplesMultipart(datasetId, update);
2591
- }
2592
- /**
2593
- * Get dataset version by closest date or exact tag.
2594
- *
2595
- * Use this to resolve the nearest version to a given timestamp or for a given tag.
2596
- *
2597
- * @param options The options for getting the dataset version
2598
- * @param options.datasetId The ID of the dataset
2599
- * @param options.datasetName The name of the dataset
2600
- * @param options.asOf The timestamp of the dataset to retrieve
2601
- * @param options.tag The tag of the dataset to retrieve
2602
- * @returns The dataset version
2603
- */
2604
- async readDatasetVersion({ datasetId, datasetName, asOf, tag }) {
2605
- let resolvedDatasetId;
2606
- if (!datasetId) {
2607
- const dataset = await this.readDataset({ datasetName });
2608
- resolvedDatasetId = dataset.id;
2609
- } else {
2610
- resolvedDatasetId = datasetId;
2611
- }
2612
- assertUuid(resolvedDatasetId);
2613
- if (asOf && tag || !asOf && !tag) {
2614
- throw new Error("Exactly one of asOf and tag must be specified.");
2615
- }
2616
- const params = new URLSearchParams();
2617
- if (asOf !== void 0) {
2618
- params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString());
2619
- }
2620
- if (tag !== void 0) {
2621
- params.append("tag", tag);
2622
- }
2623
- const response = await this.caller.call(async () => {
2624
- const res = await this._fetch(`${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, {
2625
- method: "GET",
2626
- headers: { ...this.headers },
2627
- signal: AbortSignal.timeout(this.timeout_ms),
2628
- ...this.fetchOptions
2629
- });
2630
- await raiseForStatus(res, "read dataset version");
2631
- return res;
2632
- });
2633
- return await response.json();
2634
- }
2635
- async listDatasetSplits({ datasetId, datasetName, asOf }) {
2636
- let datasetId_;
2637
- if (datasetId === void 0 && datasetName === void 0) {
2638
- throw new Error("Must provide dataset name or ID");
2639
- } else if (datasetId !== void 0 && datasetName !== void 0) {
2640
- throw new Error("Must provide either datasetName or datasetId, not both");
2641
- } else if (datasetId === void 0) {
2642
- const dataset = await this.readDataset({ datasetName });
2643
- datasetId_ = dataset.id;
2644
- } else {
2645
- datasetId_ = datasetId;
2646
- }
2647
- assertUuid(datasetId_);
2648
- const params = new URLSearchParams();
2649
- const dataset_version = asOf ? typeof asOf === "string" ? asOf : asOf?.toISOString() : void 0;
2650
- if (dataset_version) {
2651
- params.append("as_of", dataset_version);
2652
- }
2653
- const response = await this._get(`/datasets/${datasetId_}/splits`, params);
2654
- return response;
2655
- }
2656
- async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false }) {
2657
- let datasetId_;
2658
- if (datasetId === void 0 && datasetName === void 0) {
2659
- throw new Error("Must provide dataset name or ID");
2660
- } else if (datasetId !== void 0 && datasetName !== void 0) {
2661
- throw new Error("Must provide either datasetName or datasetId, not both");
2662
- } else if (datasetId === void 0) {
2663
- const dataset = await this.readDataset({ datasetName });
2664
- datasetId_ = dataset.id;
2665
- } else {
2666
- datasetId_ = datasetId;
2667
- }
2668
- assertUuid(datasetId_);
2669
- const data = {
2670
- split_name: splitName,
2671
- examples: exampleIds.map((id) => {
2672
- assertUuid(id);
2673
- return id;
2674
- }),
2675
- remove
2676
- };
2677
- const body = JSON.stringify(data);
2678
- await this.caller.call(async () => {
2679
- const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/splits`, {
2680
- method: "PUT",
2681
- headers: { ...this.headers, "Content-Type": "application/json" },
2682
- signal: AbortSignal.timeout(this.timeout_ms),
2683
- ...this.fetchOptions,
2684
- body
2685
- });
2686
- await raiseForStatus(res, "update dataset splits", true);
2687
- return res;
2688
- });
2689
- }
2690
- async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId }) {
2691
- if (!runId && !projectId) {
2692
- throw new Error("One of runId or projectId must be provided");
2693
- }
2694
- if (runId && projectId) {
2695
- throw new Error("Only one of runId or projectId can be provided");
2696
- }
2697
- const feedback_source = {
2698
- type: feedbackSourceType ?? "api",
2699
- metadata: sourceInfo ?? {}
2700
- };
2701
- if (sourceRunId !== void 0 && feedback_source?.metadata !== void 0 && !feedback_source.metadata["__run"]) {
2702
- feedback_source.metadata["__run"] = { run_id: sourceRunId };
2703
- }
2704
- if (feedback_source?.metadata !== void 0 && feedback_source.metadata["__run"]?.run_id !== void 0) {
2705
- assertUuid(feedback_source.metadata["__run"].run_id);
2706
- }
2707
- const feedback = {
2708
- id: feedbackId ?? uuid.v4(),
2709
- run_id: runId,
2710
- key,
2711
- score: _formatFeedbackScore(score),
2712
- value,
2713
- correction,
2714
- comment,
2715
- feedback_source,
2716
- comparative_experiment_id: comparativeExperimentId,
2717
- feedbackConfig,
2718
- session_id: projectId
2719
- };
2720
- const body = JSON.stringify(feedback);
2721
- const url = `${this.apiUrl}/feedback`;
2722
- await this.caller.call(async () => {
2723
- const res = await this._fetch(url, {
2724
- method: "POST",
2725
- headers: { ...this.headers, "Content-Type": "application/json" },
2726
- signal: AbortSignal.timeout(this.timeout_ms),
2727
- ...this.fetchOptions,
2728
- body
2729
- });
2730
- await raiseForStatus(res, "create feedback", true);
2731
- return res;
2732
- });
2733
- return feedback;
2734
- }
2735
- async updateFeedback(feedbackId, { score, value, correction, comment }) {
2736
- const feedbackUpdate = {};
2737
- if (score !== void 0 && score !== null) {
2738
- feedbackUpdate["score"] = _formatFeedbackScore(score);
2739
- }
2740
- if (value !== void 0 && value !== null) {
2741
- feedbackUpdate["value"] = value;
2742
- }
2743
- if (correction !== void 0 && correction !== null) {
2744
- feedbackUpdate["correction"] = correction;
2745
- }
2746
- if (comment !== void 0 && comment !== null) {
2747
- feedbackUpdate["comment"] = comment;
2748
- }
2749
- assertUuid(feedbackId);
2750
- const body = JSON.stringify(feedbackUpdate);
2751
- await this.caller.call(async () => {
2752
- const res = await this._fetch(`${this.apiUrl}/feedback/${feedbackId}`, {
2753
- method: "PATCH",
2754
- headers: { ...this.headers, "Content-Type": "application/json" },
2755
- signal: AbortSignal.timeout(this.timeout_ms),
2756
- ...this.fetchOptions,
2757
- body
2758
- });
2759
- await raiseForStatus(res, "update feedback", true);
2760
- return res;
2761
- });
2762
- }
2763
- async readFeedback(feedbackId) {
2764
- assertUuid(feedbackId);
2765
- const path = `/feedback/${feedbackId}`;
2766
- const response = await this._get(path);
2767
- return response;
2768
- }
2769
- async deleteFeedback(feedbackId) {
2770
- assertUuid(feedbackId);
2771
- const path = `/feedback/${feedbackId}`;
2772
- await this.caller.call(async () => {
2773
- const res = await this._fetch(this.apiUrl + path, {
2774
- method: "DELETE",
2775
- headers: this.headers,
2776
- signal: AbortSignal.timeout(this.timeout_ms),
2777
- ...this.fetchOptions
2778
- });
2779
- await raiseForStatus(res, `delete ${path}`, true);
2780
- return res;
2781
- });
2782
- }
2783
- async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes } = {}) {
2784
- const queryParams = new URLSearchParams();
2785
- if (runIds) {
2786
- for (const runId of runIds) {
2787
- assertUuid(runId);
2788
- queryParams.append("run", runId);
2789
- }
2790
- }
2791
- if (feedbackKeys) {
2792
- for (const key of feedbackKeys) {
2793
- queryParams.append("key", key);
2794
- }
2795
- }
2796
- if (feedbackSourceTypes) {
2797
- for (const type of feedbackSourceTypes) {
2798
- queryParams.append("source", type);
2799
- }
2800
- }
2801
- for await (const feedbacks of this._getPaginated("/feedback", queryParams)) {
2802
- yield* feedbacks;
2803
- }
2804
- }
2805
- /**
2806
- * Creates a presigned feedback token and URL.
2807
- *
2808
- * The token can be used to authorize feedback metrics without
2809
- * needing an API key. This is useful for giving browser-based
2810
- * applications the ability to submit feedback without needing
2811
- * to expose an API key.
2812
- *
2813
- * @param runId The ID of the run.
2814
- * @param feedbackKey The feedback key.
2815
- * @param options Additional options for the token.
2816
- * @param options.expiration The expiration time for the token.
2817
- *
2818
- * @returns A promise that resolves to a FeedbackIngestToken.
2819
- */
2820
- async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig } = {}) {
2821
- const body = {
2822
- run_id: runId,
2823
- feedback_key: feedbackKey,
2824
- feedback_config: feedbackConfig
2825
- };
2826
- if (expiration) {
2827
- if (typeof expiration === "string") {
2828
- body["expires_at"] = expiration;
2829
- } else if (expiration?.hours || expiration?.minutes || expiration?.days) {
2830
- body["expires_in"] = expiration;
2831
- }
2832
- } else {
2833
- body["expires_in"] = {
2834
- hours: 3
2835
- };
2836
- }
2837
- const serializedBody = JSON.stringify(body);
2838
- const response = await this.caller.call(async () => {
2839
- const res = await this._fetch(`${this.apiUrl}/feedback/tokens`, {
2840
- method: "POST",
2841
- headers: { ...this.headers, "Content-Type": "application/json" },
2842
- signal: AbortSignal.timeout(this.timeout_ms),
2843
- ...this.fetchOptions,
2844
- body: serializedBody
2845
- });
2846
- await raiseForStatus(res, "create presigned feedback token");
2847
- return res;
2848
- });
2849
- return await response.json();
2850
- }
2851
- async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id }) {
2852
- if (experimentIds.length === 0) {
2853
- throw new Error("At least one experiment is required");
2854
- }
2855
- if (!referenceDatasetId) {
2856
- referenceDatasetId = (await this.readProject({
2857
- projectId: experimentIds[0]
2858
- })).reference_dataset_id;
2859
- }
2860
- if (!referenceDatasetId == null) {
2861
- throw new Error("A reference dataset is required");
2862
- }
2863
- const body = {
2864
- id,
2865
- name,
2866
- experiment_ids: experimentIds,
2867
- reference_dataset_id: referenceDatasetId,
2868
- description,
2869
- created_at: (createdAt ?? /* @__PURE__ */ new Date())?.toISOString(),
2870
- extra: {}
2871
- };
2872
- if (metadata)
2873
- body.extra["metadata"] = metadata;
2874
- const serializedBody = JSON.stringify(body);
2875
- const response = await this.caller.call(async () => {
2876
- const res = await this._fetch(`${this.apiUrl}/datasets/comparative`, {
2877
- method: "POST",
2878
- headers: { ...this.headers, "Content-Type": "application/json" },
2879
- signal: AbortSignal.timeout(this.timeout_ms),
2880
- ...this.fetchOptions,
2881
- body: serializedBody
2882
- });
2883
- await raiseForStatus(res, "create comparative experiment");
2884
- return res;
2885
- });
2886
- return response.json();
2887
- }
2888
- /**
2889
- * Retrieves a list of presigned feedback tokens for a given run ID.
2890
- * @param runId The ID of the run.
2891
- * @returns An async iterable of FeedbackIngestToken objects.
2892
- */
2893
- async *listPresignedFeedbackTokens(runId) {
2894
- assertUuid(runId);
2895
- const params = new URLSearchParams({ run_id: runId });
2896
- for await (const tokens of this._getPaginated("/feedback/tokens", params)) {
2897
- yield* tokens;
2898
- }
2899
- }
2900
- _selectEvalResults(results) {
2901
- let results_;
2902
- if ("results" in results) {
2903
- results_ = results.results;
2904
- } else if (Array.isArray(results)) {
2905
- results_ = results;
2906
- } else {
2907
- results_ = [results];
2908
- }
2909
- return results_;
2910
- }
2911
- async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {
2912
- const evalResults = this._selectEvalResults(evaluatorResponse);
2913
- const feedbacks = [];
2914
- for (const res of evalResults) {
2915
- let sourceInfo_ = sourceInfo || {};
2916
- if (res.evaluatorInfo) {
2917
- sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ };
2918
- }
2919
- let runId_ = null;
2920
- if (res.targetRunId) {
2921
- runId_ = res.targetRunId;
2922
- } else if (run) {
2923
- runId_ = run.id;
2924
- }
2925
- feedbacks.push(await this.createFeedback(runId_, res.key, {
2926
- score: res.score,
2927
- value: res.value,
2928
- comment: res.comment,
2929
- correction: res.correction,
2930
- sourceInfo: sourceInfo_,
2931
- sourceRunId: res.sourceRunId,
2932
- feedbackConfig: res.feedbackConfig,
2933
- feedbackSourceType: "model"
2934
- }));
2935
- }
2936
- return [evalResults, feedbacks];
2937
- }
2938
- async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) {
2939
- const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo);
2940
- return results;
2941
- }
2942
- /**
2943
- * API for managing annotation queues
2944
- */
2945
- /**
2946
- * List the annotation queues on the LangSmith API.
2947
- * @param options - The options for listing annotation queues
2948
- * @param options.queueIds - The IDs of the queues to filter by
2949
- * @param options.name - The name of the queue to filter by
2950
- * @param options.nameContains - The substring that the queue name should contain
2951
- * @param options.limit - The maximum number of queues to return
2952
- * @returns An iterator of AnnotationQueue objects
2953
- */
2954
- async *listAnnotationQueues(options = {}) {
2955
- const { queueIds, name, nameContains, limit } = options;
2956
- const params = new URLSearchParams();
2957
- if (queueIds) {
2958
- queueIds.forEach((id, i) => {
2959
- assertUuid(id, `queueIds[${i}]`);
2960
- params.append("ids", id);
2961
- });
2962
- }
2963
- if (name)
2964
- params.append("name", name);
2965
- if (nameContains)
2966
- params.append("name_contains", nameContains);
2967
- params.append("limit", (limit !== void 0 ? Math.min(limit, 100) : 100).toString());
2968
- let count = 0;
2969
- for await (const queues of this._getPaginated("/annotation-queues", params)) {
2970
- yield* queues;
2971
- count++;
2972
- if (limit !== void 0 && count >= limit)
2973
- break;
2974
- }
2975
- }
2976
- /**
2977
- * Create an annotation queue on the LangSmith API.
2978
- * @param options - The options for creating an annotation queue
2979
- * @param options.name - The name of the annotation queue
2980
- * @param options.description - The description of the annotation queue
2981
- * @param options.queueId - The ID of the annotation queue
2982
- * @returns The created AnnotationQueue object
2983
- */
2984
- async createAnnotationQueue(options) {
2985
- const { name, description, queueId, rubricInstructions } = options;
2986
- const body = {
2987
- name,
2988
- description,
2989
- id: queueId || uuid.v4(),
2990
- rubric_instructions: rubricInstructions
2991
- };
2992
- const serializedBody = JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== void 0)));
2993
- const response = await this.caller.call(async () => {
2994
- const res = await this._fetch(`${this.apiUrl}/annotation-queues`, {
2995
- method: "POST",
2996
- headers: { ...this.headers, "Content-Type": "application/json" },
2997
- signal: AbortSignal.timeout(this.timeout_ms),
2998
- ...this.fetchOptions,
2999
- body: serializedBody
3000
- });
3001
- await raiseForStatus(res, "create annotation queue");
3002
- return res;
3003
- });
3004
- return response.json();
3005
- }
3006
- /**
3007
- * Read an annotation queue with the specified queue ID.
3008
- * @param queueId - The ID of the annotation queue to read
3009
- * @returns The AnnotationQueueWithDetails object
3010
- */
3011
- async readAnnotationQueue(queueId) {
3012
- const response = await this.caller.call(async () => {
3013
- const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, {
3014
- method: "GET",
3015
- headers: this.headers,
3016
- signal: AbortSignal.timeout(this.timeout_ms),
3017
- ...this.fetchOptions
3018
- });
3019
- await raiseForStatus(res, "read annotation queue");
3020
- return res;
3021
- });
3022
- return response.json();
3023
- }
3024
- /**
3025
- * Update an annotation queue with the specified queue ID.
3026
- * @param queueId - The ID of the annotation queue to update
3027
- * @param options - The options for updating the annotation queue
3028
- * @param options.name - The new name for the annotation queue
3029
- * @param options.description - The new description for the annotation queue
3030
- */
3031
- async updateAnnotationQueue(queueId, options) {
3032
- const { name, description, rubricInstructions } = options;
3033
- const body = JSON.stringify({
3034
- name,
3035
- description,
3036
- rubric_instructions: rubricInstructions
3037
- });
3038
- await this.caller.call(async () => {
3039
- const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, {
3040
- method: "PATCH",
3041
- headers: { ...this.headers, "Content-Type": "application/json" },
3042
- signal: AbortSignal.timeout(this.timeout_ms),
3043
- ...this.fetchOptions,
3044
- body
3045
- });
3046
- await raiseForStatus(res, "update annotation queue", true);
3047
- return res;
3048
- });
3049
- }
3050
- /**
3051
- * Delete an annotation queue with the specified queue ID.
3052
- * @param queueId - The ID of the annotation queue to delete
3053
- */
3054
- async deleteAnnotationQueue(queueId) {
3055
- await this.caller.call(async () => {
3056
- const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, {
3057
- method: "DELETE",
3058
- headers: { ...this.headers, Accept: "application/json" },
3059
- signal: AbortSignal.timeout(this.timeout_ms),
3060
- ...this.fetchOptions
3061
- });
3062
- await raiseForStatus(res, "delete annotation queue", true);
3063
- return res;
3064
- });
3065
- }
3066
- /**
3067
- * Add runs to an annotation queue with the specified queue ID.
3068
- * @param queueId - The ID of the annotation queue
3069
- * @param runIds - The IDs of the runs to be added to the annotation queue
3070
- */
3071
- async addRunsToAnnotationQueue(queueId, runIds) {
3072
- const body = JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString()));
3073
- await this.caller.call(async () => {
3074
- const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, {
3075
- method: "POST",
3076
- headers: { ...this.headers, "Content-Type": "application/json" },
3077
- signal: AbortSignal.timeout(this.timeout_ms),
3078
- ...this.fetchOptions,
3079
- body
3080
- });
3081
- await raiseForStatus(res, "add runs to annotation queue", true);
3082
- return res;
3083
- });
3084
- }
3085
- /**
3086
- * Get a run from an annotation queue at the specified index.
3087
- * @param queueId - The ID of the annotation queue
3088
- * @param index - The index of the run to retrieve
3089
- * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object
3090
- * @throws {Error} If the run is not found at the given index or for other API-related errors
3091
- */
3092
- async getRunFromAnnotationQueue(queueId, index) {
3093
- const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`;
3094
- const response = await this.caller.call(async () => {
3095
- const res = await this._fetch(`${this.apiUrl}${baseUrl}/${index}`, {
3096
- method: "GET",
3097
- headers: this.headers,
3098
- signal: AbortSignal.timeout(this.timeout_ms),
3099
- ...this.fetchOptions
3100
- });
3101
- await raiseForStatus(res, "get run from annotation queue");
3102
- return res;
3103
- });
3104
- return response.json();
3105
- }
3106
- /**
3107
- * Delete a run from an an annotation queue.
3108
- * @param queueId - The ID of the annotation queue to delete the run from
3109
- * @param queueRunId - The ID of the run to delete from the annotation queue
3110
- */
3111
- async deleteRunFromAnnotationQueue(queueId, queueRunId) {
3112
- await this.caller.call(async () => {
3113
- const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, {
3114
- method: "DELETE",
3115
- headers: { ...this.headers, Accept: "application/json" },
3116
- signal: AbortSignal.timeout(this.timeout_ms),
3117
- ...this.fetchOptions
3118
- });
3119
- await raiseForStatus(res, "delete run from annotation queue", true);
3120
- return res;
3121
- });
3122
- }
3123
- /**
3124
- * Get the size of an annotation queue.
3125
- * @param queueId - The ID of the annotation queue
3126
- */
3127
- async getSizeFromAnnotationQueue(queueId) {
3128
- const response = await this.caller.call(async () => {
3129
- const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, {
3130
- method: "GET",
3131
- headers: this.headers,
3132
- signal: AbortSignal.timeout(this.timeout_ms),
3133
- ...this.fetchOptions
3134
- });
3135
- await raiseForStatus(res, "get size from annotation queue");
3136
- return res;
3137
- });
3138
- return response.json();
3139
- }
3140
- async _currentTenantIsOwner(owner) {
3141
- const settings = await this._getSettings();
3142
- return owner == "-" || settings.tenant_handle === owner;
3143
- }
3144
- async _ownerConflictError(action, owner) {
3145
- const settings = await this._getSettings();
3146
- return new Error(`Cannot ${action} for another tenant.
3147
-
3148
- Current tenant: ${settings.tenant_handle}
3149
-
3150
- Requested tenant: ${owner}`);
3151
- }
3152
- async _getLatestCommitHash(promptOwnerAndName) {
3153
- const response = await this.caller.call(async () => {
3154
- const res = await this._fetch(`${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, {
3155
- method: "GET",
3156
- headers: this.headers,
3157
- signal: AbortSignal.timeout(this.timeout_ms),
3158
- ...this.fetchOptions
3159
- });
3160
- await raiseForStatus(res, "get latest commit hash");
3161
- return res;
3162
- });
3163
- const json = await response.json();
3164
- if (json.commits.length === 0) {
3165
- return void 0;
3166
- }
3167
- return json.commits[0].commit_hash;
3168
- }
3169
- async _likeOrUnlikePrompt(promptIdentifier, like) {
3170
- const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier);
3171
- const body = JSON.stringify({ like });
3172
- const response = await this.caller.call(async () => {
3173
- const res = await this._fetch(`${this.apiUrl}/likes/${owner}/${promptName}`, {
3174
- method: "POST",
3175
- headers: { ...this.headers, "Content-Type": "application/json" },
3176
- signal: AbortSignal.timeout(this.timeout_ms),
3177
- ...this.fetchOptions,
3178
- body
3179
- });
3180
- await raiseForStatus(res, `${like ? "like" : "unlike"} prompt`);
3181
- return res;
3182
- });
3183
- return response.json();
3184
- }
3185
- async _getPromptUrl(promptIdentifier) {
3186
- const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier);
3187
- if (!await this._currentTenantIsOwner(owner)) {
3188
- if (commitHash !== "latest") {
3189
- return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`;
3190
- } else {
3191
- return `${this.getHostUrl()}/hub/${owner}/${promptName}`;
3192
- }
3193
- } else {
3194
- const settings = await this._getSettings();
3195
- if (commitHash !== "latest") {
3196
- return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`;
3197
- } else {
3198
- return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`;
3199
- }
3200
- }
3201
- }
3202
- async promptExists(promptIdentifier) {
3203
- const prompt = await this.getPrompt(promptIdentifier);
3204
- return !!prompt;
3205
- }
3206
- async likePrompt(promptIdentifier) {
3207
- return this._likeOrUnlikePrompt(promptIdentifier, true);
3208
- }
3209
- async unlikePrompt(promptIdentifier) {
3210
- return this._likeOrUnlikePrompt(promptIdentifier, false);
3211
- }
3212
- async *listCommits(promptOwnerAndName) {
3213
- for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) {
3214
- yield* commits;
3215
- }
3216
- }
3217
- async *listPrompts(options) {
3218
- const params = new URLSearchParams();
3219
- params.append("sort_field", options?.sortField ?? "updated_at");
3220
- params.append("sort_direction", "desc");
3221
- params.append("is_archived", (!!options?.isArchived).toString());
3222
- if (options?.isPublic !== void 0) {
3223
- params.append("is_public", options.isPublic.toString());
3224
- }
3225
- if (options?.query) {
3226
- params.append("query", options.query);
3227
- }
3228
- for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) {
3229
- yield* prompts;
3230
- }
3231
- }
3232
- async getPrompt(promptIdentifier) {
3233
- const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier);
3234
- const response = await this.caller.call(async () => {
3235
- const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, {
3236
- method: "GET",
3237
- headers: this.headers,
3238
- signal: AbortSignal.timeout(this.timeout_ms),
3239
- ...this.fetchOptions
3240
- });
3241
- if (res?.status === 404) {
3242
- return null;
3243
- }
3244
- await raiseForStatus(res, "get prompt");
3245
- return res;
3246
- });
3247
- const result = await response?.json();
3248
- if (result?.repo) {
3249
- return result.repo;
3250
- } else {
3251
- return null;
3252
- }
3253
- }
3254
- async createPrompt(promptIdentifier, options) {
3255
- const settings = await this._getSettings();
3256
- if (options?.isPublic && !settings.tenant_handle) {
3257
- throw new Error(`Cannot create a public prompt without first
3258
-
3259
- creating a LangChain Hub handle.
3260
- You can add a handle by creating a public prompt at:
3261
-
3262
- https://smith.langchain.com/prompts`);
3263
- }
3264
- const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier);
3265
- if (!await this._currentTenantIsOwner(owner)) {
3266
- throw await this._ownerConflictError("create a prompt", owner);
3267
- }
3268
- const data = {
3269
- repo_handle: promptName,
3270
- ...options?.description && { description: options.description },
3271
- ...options?.readme && { readme: options.readme },
3272
- ...options?.tags && { tags: options.tags },
3273
- is_public: !!options?.isPublic
3274
- };
3275
- const body = JSON.stringify(data);
3276
- const response = await this.caller.call(async () => {
3277
- const res = await this._fetch(`${this.apiUrl}/repos/`, {
3278
- method: "POST",
3279
- headers: { ...this.headers, "Content-Type": "application/json" },
3280
- signal: AbortSignal.timeout(this.timeout_ms),
3281
- ...this.fetchOptions,
3282
- body
3283
- });
3284
- await raiseForStatus(res, "create prompt");
3285
- return res;
3286
- });
3287
- const { repo } = await response.json();
3288
- return repo;
3289
- }
3290
- async createCommit(promptIdentifier, object, options) {
3291
- if (!await this.promptExists(promptIdentifier)) {
3292
- throw new Error("Prompt does not exist, you must create it first.");
3293
- }
3294
- const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier);
3295
- const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash ? await this._getLatestCommitHash(`${owner}/${promptName}`) : options?.parentCommitHash;
3296
- const payload = {
3297
- manifest: JSON.parse(JSON.stringify(object)),
3298
- parent_commit: resolvedParentCommitHash
3299
- };
3300
- const body = JSON.stringify(payload);
3301
- const response = await this.caller.call(async () => {
3302
- const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}`, {
3303
- method: "POST",
3304
- headers: { ...this.headers, "Content-Type": "application/json" },
3305
- signal: AbortSignal.timeout(this.timeout_ms),
3306
- ...this.fetchOptions,
3307
- body
3308
- });
3309
- await raiseForStatus(res, "create commit");
3310
- return res;
3311
- });
3312
- const result = await response.json();
3313
- return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`);
3314
- }
3315
- /**
3316
- * Update examples with attachments using multipart form data.
3317
- * @param updates List of ExampleUpdateWithAttachments objects to upsert
3318
- * @returns Promise with the update response
3319
- */
3320
- async updateExamplesMultipart(datasetId, updates = []) {
3321
- return this._updateExamplesMultipart(datasetId, updates);
3322
- }
3323
- async _updateExamplesMultipart(datasetId, updates = []) {
3324
- if (!await this._getDatasetExamplesMultiPartSupport()) {
3325
- throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");
3326
- }
3327
- const formData = new FormData();
3328
- for (const example of updates) {
3329
- const exampleId = example.id;
3330
- const exampleBody = {
3331
- ...example.metadata && { metadata: example.metadata },
3332
- ...example.split && { split: example.split }
3333
- };
3334
- const stringifiedExample = serialize(exampleBody, `Serializing body for example with id: ${exampleId}`);
3335
- const exampleBlob = new Blob([stringifiedExample], {
3336
- type: "application/json"
3337
- });
3338
- formData.append(exampleId, exampleBlob);
3339
- if (example.inputs) {
3340
- const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`);
3341
- const inputsBlob = new Blob([stringifiedInputs], {
3342
- type: "application/json"
3343
- });
3344
- formData.append(`${exampleId}.inputs`, inputsBlob);
3345
- }
3346
- if (example.outputs) {
3347
- const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`);
3348
- const outputsBlob = new Blob([stringifiedOutputs], {
3349
- type: "application/json"
3350
- });
3351
- formData.append(`${exampleId}.outputs`, outputsBlob);
3352
- }
3353
- if (example.attachments) {
3354
- for (const [name, attachment] of Object.entries(example.attachments)) {
3355
- let mimeType;
3356
- let data;
3357
- if (Array.isArray(attachment)) {
3358
- [mimeType, data] = attachment;
3359
- } else {
3360
- mimeType = attachment.mimeType;
3361
- data = attachment.data;
3362
- }
3363
- const attachmentBlob = new Blob([data], {
3364
- type: `${mimeType}; length=${data.byteLength}`
3365
- });
3366
- formData.append(`${exampleId}.attachment.${name}`, attachmentBlob);
3367
- }
3368
- }
3369
- if (example.attachments_operations) {
3370
- const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`);
3371
- const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], {
3372
- type: "application/json"
3373
- });
3374
- formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob);
3375
- }
3376
- }
3377
- const datasetIdToUse = datasetId ?? updates[0]?.dataset_id;
3378
- const response = await this.caller.call(async () => {
3379
- const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetIdToUse}/examples`)}`, {
3380
- method: "PATCH",
3381
- headers: this.headers,
3382
- signal: AbortSignal.timeout(this.timeout_ms),
3383
- ...this.fetchOptions,
3384
- body: formData
3385
- });
3386
- await raiseForStatus(res, "update examples");
3387
- return res;
3388
- });
3389
- return response.json();
3390
- }
3391
- /**
3392
- * Upload examples with attachments using multipart form data.
3393
- * @param uploads List of ExampleUploadWithAttachments objects to upload
3394
- * @returns Promise with the upload response
3395
- * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead
3396
- */
3397
- async uploadExamplesMultipart(datasetId, uploads = []) {
3398
- return this._uploadExamplesMultipart(datasetId, uploads);
3399
- }
3400
- async _uploadExamplesMultipart(datasetId, uploads = []) {
3401
- if (!await this._getDatasetExamplesMultiPartSupport()) {
3402
- throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");
3403
- }
3404
- const formData = new FormData();
3405
- for (const example of uploads) {
3406
- const exampleId = (example.id ?? uuid.v4()).toString();
3407
- const exampleBody = {
3408
- created_at: example.created_at,
3409
- ...example.metadata && { metadata: example.metadata },
3410
- ...example.split && { split: example.split },
3411
- ...example.source_run_id && { source_run_id: example.source_run_id },
3412
- ...example.use_source_run_io && {
3413
- use_source_run_io: example.use_source_run_io
3414
- },
3415
- ...example.use_source_run_attachments && {
3416
- use_source_run_attachments: example.use_source_run_attachments
3417
- }
3418
- };
3419
- const stringifiedExample = serialize(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`);
3420
- const exampleBlob = new Blob([stringifiedExample], {
3421
- type: "application/json"
3422
- });
3423
- formData.append(exampleId, exampleBlob);
3424
- if (example.inputs) {
3425
- const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`);
3426
- const inputsBlob = new Blob([stringifiedInputs], {
3427
- type: "application/json"
3428
- });
3429
- formData.append(`${exampleId}.inputs`, inputsBlob);
3430
- }
3431
- if (example.outputs) {
3432
- const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`);
3433
- const outputsBlob = new Blob([stringifiedOutputs], {
3434
- type: "application/json"
3435
- });
3436
- formData.append(`${exampleId}.outputs`, outputsBlob);
3437
- }
3438
- if (example.attachments) {
3439
- for (const [name, attachment] of Object.entries(example.attachments)) {
3440
- let mimeType;
3441
- let data;
3442
- if (Array.isArray(attachment)) {
3443
- [mimeType, data] = attachment;
3444
- } else {
3445
- mimeType = attachment.mimeType;
3446
- data = attachment.data;
3447
- }
3448
- const attachmentBlob = new Blob([data], {
3449
- type: `${mimeType}; length=${data.byteLength}`
3450
- });
3451
- formData.append(`${exampleId}.attachment.${name}`, attachmentBlob);
3452
- }
3453
- }
3454
- }
3455
- const response = await this.caller.call(async () => {
3456
- const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetId}/examples`)}`, {
3457
- method: "POST",
3458
- headers: this.headers,
3459
- signal: AbortSignal.timeout(this.timeout_ms),
3460
- ...this.fetchOptions,
3461
- body: formData
3462
- });
3463
- await raiseForStatus(res, "upload examples");
3464
- return res;
3465
- });
3466
- return response.json();
3467
- }
3468
- async updatePrompt(promptIdentifier, options) {
3469
- if (!await this.promptExists(promptIdentifier)) {
3470
- throw new Error("Prompt does not exist, you must create it first.");
3471
- }
3472
- const [owner, promptName] = parsePromptIdentifier(promptIdentifier);
3473
- if (!await this._currentTenantIsOwner(owner)) {
3474
- throw await this._ownerConflictError("update a prompt", owner);
3475
- }
3476
- const payload = {};
3477
- if (options?.description !== void 0)
3478
- payload.description = options.description;
3479
- if (options?.readme !== void 0)
3480
- payload.readme = options.readme;
3481
- if (options?.tags !== void 0)
3482
- payload.tags = options.tags;
3483
- if (options?.isPublic !== void 0)
3484
- payload.is_public = options.isPublic;
3485
- if (options?.isArchived !== void 0)
3486
- payload.is_archived = options.isArchived;
3487
- if (Object.keys(payload).length === 0) {
3488
- throw new Error("No valid update options provided");
3489
- }
3490
- const body = JSON.stringify(payload);
3491
- const response = await this.caller.call(async () => {
3492
- const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, {
3493
- method: "PATCH",
3494
- headers: {
3495
- ...this.headers,
3496
- "Content-Type": "application/json"
3497
- },
3498
- signal: AbortSignal.timeout(this.timeout_ms),
3499
- ...this.fetchOptions,
3500
- body
3501
- });
3502
- await raiseForStatus(res, "update prompt");
3503
- return res;
3504
- });
3505
- return response.json();
3506
- }
3507
- async deletePrompt(promptIdentifier) {
3508
- if (!await this.promptExists(promptIdentifier)) {
3509
- throw new Error("Prompt does not exist, you must create it first.");
3510
- }
3511
- const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier);
3512
- if (!await this._currentTenantIsOwner(owner)) {
3513
- throw await this._ownerConflictError("delete a prompt", owner);
3514
- }
3515
- const response = await this.caller.call(async () => {
3516
- const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, {
3517
- method: "DELETE",
3518
- headers: this.headers,
3519
- signal: AbortSignal.timeout(this.timeout_ms),
3520
- ...this.fetchOptions
3521
- });
3522
- await raiseForStatus(res, "delete prompt");
3523
- return res;
3524
- });
3525
- return response.json();
3526
- }
3527
- /**
3528
- * Generate a cache key for a prompt.
3529
- * Format: "{identifier}" or "{identifier}:with_model"
3530
- */
3531
- _getPromptCacheKey(promptIdentifier, includeModel) {
3532
- const suffix = includeModel ? ":with_model" : "";
3533
- return `${promptIdentifier}${suffix}`;
3534
- }
3535
- /**
3536
- * Fetch a prompt commit directly from the API (bypassing cache).
3537
- */
3538
- async _fetchPromptFromApi(promptIdentifier, options) {
3539
- const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier);
3540
- const response = await this.caller.call(async () => {
3541
- const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, {
3542
- method: "GET",
3543
- headers: this.headers,
3544
- signal: AbortSignal.timeout(this.timeout_ms),
3545
- ...this.fetchOptions
3546
- });
3547
- await raiseForStatus(res, "pull prompt commit");
3548
- return res;
3549
- });
3550
- const result = await response.json();
3551
- return {
3552
- owner,
3553
- repo: promptName,
3554
- commit_hash: result.commit_hash,
3555
- manifest: result.manifest,
3556
- examples: result.examples
3557
- };
3558
- }
3559
- async pullPromptCommit(promptIdentifier, options) {
3560
- if (!options?.skipCache && this._cache) {
3561
- const cacheKey = this._getPromptCacheKey(promptIdentifier, options?.includeModel);
3562
- const cached = this._cache.get(cacheKey);
3563
- if (cached) {
3564
- return cached;
3565
- }
3566
- const result = await this._fetchPromptFromApi(promptIdentifier, options);
3567
- this._cache.set(cacheKey, result);
3568
- return result;
3569
- }
3570
- return this._fetchPromptFromApi(promptIdentifier, options);
3571
- }
3572
- /**
3573
- * This method should not be used directly, use `import { pull } from "langchain/hub"` instead.
3574
- * Using this method directly returns the JSON string of the prompt rather than a LangChain object.
3575
- * @private
3576
- */
3577
- async _pullPrompt(promptIdentifier, options) {
3578
- const promptObject = await this.pullPromptCommit(promptIdentifier, {
3579
- includeModel: options?.includeModel,
3580
- skipCache: options?.skipCache
3581
- });
3582
- const prompt = JSON.stringify(promptObject.manifest);
3583
- return prompt;
3584
- }
3585
- async pushPrompt(promptIdentifier, options) {
3586
- if (await this.promptExists(promptIdentifier)) {
3587
- if (options && Object.keys(options).some((key) => key !== "object")) {
3588
- await this.updatePrompt(promptIdentifier, {
3589
- description: options?.description,
3590
- readme: options?.readme,
3591
- tags: options?.tags,
3592
- isPublic: options?.isPublic
3593
- });
3594
- }
3595
- } else {
3596
- await this.createPrompt(promptIdentifier, {
3597
- description: options?.description,
3598
- readme: options?.readme,
3599
- tags: options?.tags,
3600
- isPublic: options?.isPublic
3601
- });
3602
- }
3603
- if (!options?.object) {
3604
- return await this._getPromptUrl(promptIdentifier);
3605
- }
3606
- const url = await this.createCommit(promptIdentifier, options?.object, {
3607
- parentCommitHash: options?.parentCommitHash
3608
- });
3609
- return url;
3610
- }
3611
- /**
3612
- * Clone a public dataset to your own langsmith tenant.
3613
- * This operation is idempotent. If you already have a dataset with the given name,
3614
- * this function will do nothing.
3615
-
3616
- * @param {string} tokenOrUrl The token of the public dataset to clone.
3617
- * @param {Object} [options] Additional options for cloning the dataset.
3618
- * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client.
3619
- * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset.
3620
- * @returns {Promise<void>}
3621
- */
3622
- async clonePublicDataset(tokenOrUrl, options = {}) {
3623
- const { sourceApiUrl = this.apiUrl, datasetName } = options;
3624
- const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl);
3625
- const sourceClient = new Client({
3626
- apiUrl: parsedApiUrl,
3627
- // Placeholder API key not needed anymore in most cases, but
3628
- // some private deployments may have API key-based rate limiting
3629
- // that would cause this to fail if we provide no value.
3630
- apiKey: "placeholder"
3631
- });
3632
- const ds = await sourceClient.readSharedDataset(tokenUuid);
3633
- const finalDatasetName = datasetName || ds.name;
3634
- try {
3635
- if (await this.hasDataset({ datasetId: finalDatasetName })) {
3636
- console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`);
3637
- return;
3638
- }
3639
- } catch (_) {
3640
- }
3641
- const examples = await sourceClient.listSharedExamples(tokenUuid);
3642
- const dataset = await this.createDataset(finalDatasetName, {
3643
- description: ds.description,
3644
- dataType: ds.data_type || "kv",
3645
- inputsSchema: ds.inputs_schema_definition ?? void 0,
3646
- outputsSchema: ds.outputs_schema_definition ?? void 0
3647
- });
3648
- try {
3649
- await this.createExamples({
3650
- inputs: examples.map((e) => e.inputs),
3651
- outputs: examples.flatMap((e) => e.outputs ? [e.outputs] : []),
3652
- datasetId: dataset.id
3653
- });
3654
- } catch (e) {
3655
- console.error(`An error occurred while creating dataset ${finalDatasetName}. You should delete it manually.`);
3656
- throw e;
3657
- }
3658
- }
3659
- parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") {
3660
- try {
3661
- assertUuid(urlOrToken);
3662
- return [apiUrl, urlOrToken];
3663
- } catch (_) {
3664
- }
3665
- try {
3666
- const parsedUrl = new URL(urlOrToken);
3667
- const pathParts = parsedUrl.pathname.split("/").filter((part) => part !== "");
3668
- if (pathParts.length >= numParts) {
3669
- const tokenUuid = pathParts[pathParts.length - numParts];
3670
- return [apiUrl, tokenUuid];
3671
- } else {
3672
- throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`);
3673
- }
3674
- } catch (error) {
3675
- throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`);
3676
- }
3677
- }
3678
- /**
3679
- * Get the cache instance, if caching is enabled.
3680
- * Useful for accessing cache metrics or manually managing the cache.
3681
- */
3682
- get cache() {
3683
- return this._cache;
3684
- }
3685
- /**
3686
- * Cleanup resources held by the client.
3687
- * Stops the cache's background refresh timer.
3688
- */
3689
- cleanup() {
3690
- if (this._cache) {
3691
- this._cache.stop();
3692
- }
3693
- }
3694
- /**
3695
- * Awaits all pending trace batches. Useful for environments where
3696
- * you need to be sure that all tracing requests finish before execution ends,
3697
- * such as serverless environments.
3698
- *
3699
- * @example
3700
- * ```
3701
- * import { Client } from "langsmith";
3702
- *
3703
- * const client = new Client();
3704
- *
3705
- * try {
3706
- * // Tracing happens here
3707
- * ...
3708
- * } finally {
3709
- * await client.awaitPendingTraceBatches();
3710
- * }
3711
- * ```
3712
- *
3713
- * @returns A promise that resolves once all currently pending traces have sent.
3714
- */
3715
- async awaitPendingTraceBatches() {
3716
- if (this.manualFlushMode) {
3717
- console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches.");
3718
- return Promise.resolve();
3719
- }
3720
- await new Promise((resolve) => setTimeout(resolve, 1));
3721
- await Promise.all([
3722
- ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise),
3723
- this.batchIngestCaller.queue.onIdle()
3724
- ]);
3725
- if (this.langSmithToOTELTranslator !== void 0) {
3726
- await getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush();
3727
- }
3728
- }
3729
- }
3730
- function isExampleCreate(input) {
3731
- return "dataset_id" in input || "dataset_name" in input;
3732
- }
1
+ var errorUtil;
2
+ (function(errorUtil2) {
3
+ errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
4
+ errorUtil2.toString = (message) => typeof message === "string" ? message : message?.message;
5
+ })(errorUtil || (errorUtil = {}));
3733
6
  export {
3734
- AutoBatchQueue,
3735
- Client,
3736
- DEFAULT_MAX_SIZE_BYTES,
3737
- DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES,
3738
- mergeRuntimeEnvIntoRun
7
+ errorUtil
3739
8
  };
3740
9
  //# sourceMappingURL=index.es174.js.map