client.d.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  1. import { AsyncCallerParams } from "./utils/async_caller.js";
  2. import { ComparativeExperiment, DataType, Dataset, DatasetDiffInfo, DatasetShareSchema, Example, ExampleCreate, ExampleUpdate, ExampleUpdateWithoutId, Feedback, FeedbackConfig, FeedbackIngestToken, KVMap, LangChainBaseMessage, LangSmithSettings, LikePromptResponse, Prompt, PromptCommit, PromptSortField, Run, RunCreate, RunUpdate, ScoreType, ExampleSearch, TimeDelta, TracerSession, TracerSessionResult, ValueType, AnnotationQueue, RunWithAnnotationQueueInfo, Attachments, UploadExamplesResponse, UpdateExamplesResponse, DatasetVersion, AnnotationQueueWithDetails } from "./schemas.js";
  3. import { EvaluationResult, EvaluationResults, RunEvaluator } from "./evaluation/evaluator.js";
  4. export interface ClientConfig {
  5. apiUrl?: string;
  6. apiKey?: string;
  7. callerOptions?: AsyncCallerParams;
  8. timeout_ms?: number;
  9. webUrl?: string;
  10. anonymizer?: (values: KVMap) => KVMap | Promise<KVMap>;
  11. hideInputs?: boolean | ((inputs: KVMap) => KVMap | Promise<KVMap>);
  12. hideOutputs?: boolean | ((outputs: KVMap) => KVMap | Promise<KVMap>);
  13. autoBatchTracing?: boolean;
  14. batchSizeBytesLimit?: number;
  15. blockOnRootRunFinalization?: boolean;
  16. traceBatchConcurrency?: number;
  17. fetchOptions?: RequestInit;
  18. /**
  19. * Whether to require manual .flush() calls before sending traces.
  20. * Useful if encountering network rate limits at trace high volumes.
  21. */
  22. manualFlushMode?: boolean;
  23. tracingSamplingRate?: number;
  24. /**
  25. * Enable debug mode for the client. If set, all sent HTTP requests will be logged.
  26. */
  27. debug?: boolean;
  28. }
  29. /**
  30. * Represents the parameters for listing runs (spans) from the Langsmith server.
  31. */
  32. interface ListRunsParams {
  33. /**
  34. * The ID or IDs of the project(s) to filter by.
  35. */
  36. projectId?: string | string[];
  37. /**
  38. * The name or names of the project(s) to filter by.
  39. */
  40. projectName?: string | string[];
  41. /**
  42. * The ID of the trace to filter by.
  43. */
  44. traceId?: string;
  45. /**
  46. * isRoot - Whether to only include root runs.
  47. * */
  48. isRoot?: boolean;
  49. /**
  50. * The execution order to filter by.
  51. */
  52. executionOrder?: number;
  53. /**
  54. * The ID of the parent run to filter by.
  55. */
  56. parentRunId?: string;
  57. /**
  58. * The order by run start date
  59. */
  60. order?: "asc" | "desc";
  61. /**
  62. * The ID of the reference example to filter by.
  63. */
  64. referenceExampleId?: string;
  65. /**
  66. * The start time to filter by.
  67. */
  68. startTime?: Date;
  69. /**
  70. * The run type to filter by.
  71. */
  72. runType?: string;
  73. /**
  74. * Indicates whether to filter by error runs.
  75. */
  76. error?: boolean;
  77. /**
  78. * The ID or IDs of the runs to filter by.
  79. */
  80. id?: string[];
  81. /**
  82. * The maximum number of runs to retrieve.
  83. */
  84. limit?: number;
  85. /**
  86. * The query string to filter by.
  87. */
  88. query?: string;
  89. /**
  90. * The filter string to apply.
  91. *
  92. * Run Filtering:
  93. * Listing runs with query params is useful for simple queries, but doesn't support many common needs, such as filtering by metadata, tags, or other fields.
  94. * LangSmith supports a filter query language to permit more complex filtering operations when fetching runs. This guide will provide a high level overview of the grammar as well as a few examples of when it can be useful.
  95. * If you'd prefer a more visual guide, you can get a taste of the language by viewing the table of runs on any of your projects' pages. We provide some recommended filters to get you started that you can copy and use the SDK.
  96. *
  97. * Grammar:
  98. * The filtering grammar is based on common comparators on fields in the run object. Supported comparators include:
  99. * - gte (greater than or equal to)
  100. * - gt (greater than)
  101. * - lte (less than or equal to)
  102. * - lt (less than)
  103. * - eq (equal to)
  104. * - neq (not equal to)
  105. * - has (check if run contains a tag or metadata json blob)
  106. * - search (search for a substring in a string field)
  107. */
  108. filter?: string;
  109. /**
  110. * Filter to apply to the ROOT run in the trace tree. This is meant to be used in conjunction with the regular
  111. * `filter` parameter to let you filter runs by attributes of the root run within a trace. Example is filtering by
  112. * feedback assigned to the trace.
  113. */
  114. traceFilter?: string;
  115. /**
  116. * Filter to apply to OTHER runs in the trace tree, including sibling and child runs. This is meant to be used in
  117. * conjunction with the regular `filter` parameter to let you filter runs by attributes of any run within a trace.
  118. */
  119. treeFilter?: string;
  120. /**
  121. * The values to include in the response.
  122. */
  123. select?: string[];
  124. }
  125. interface GroupRunsParams {
  126. /**
  127. * The ID or IDs of the project(s) to filter by.
  128. */
  129. projectId?: string;
  130. /**
  131. * The ID or IDs of the project(s) to filter by.
  132. */
  133. projectName?: string;
  134. /**
  135. * @example "conversation"
  136. */
  137. groupBy: string;
  138. /**
  139. * The filter string to apply.
  140. *
  141. * Run Filtering:
  142. * Listing runs with query params is useful for simple queries, but doesn't support many common needs, such as filtering by metadata, tags, or other fields.
  143. * LangSmith supports a filter query language to permit more complex filtering operations when fetching runs. This guide will provide a high level overview of the grammar as well as a few examples of when it can be useful.
  144. * If you'd prefer a more visual guide, you can get a taste of the language by viewing the table of runs on any of your projects' pages. We provide some recommended filters to get you started that you can copy and use the SDK.
  145. *
  146. * Grammar:
  147. * The filtering grammar is based on common comparators on fields in the run object. Supported comparators include:
  148. * - gte (greater than or equal to)
  149. * - gt (greater than)
  150. * - lte (less than or equal to)
  151. * - lt (less than)
  152. * - eq (equal to)
  153. * - neq (not equal to)
  154. * - has (check if run contains a tag or metadata json blob)
  155. * - search (search for a substring in a string field)
  156. */
  157. filter?: string;
  158. /**
  159. * The start time to filter by.
  160. */
  161. startTime?: Date;
  162. /**
  163. * The end time to filter by.
  164. */
  165. endTime?: Date;
  166. /**
  167. * The maximum number of runs to retrieve.
  168. */
  169. limit?: number;
  170. /**
  171. * The maximum number of runs to retrieve.
  172. */
  173. offset?: number;
  174. }
  175. interface UploadCSVParams {
  176. csvFile: Blob;
  177. fileName: string;
  178. inputKeys: string[];
  179. outputKeys: string[];
  180. description?: string;
  181. dataType?: DataType;
  182. name?: string;
  183. }
  184. interface CreateRunParams {
  185. name: string;
  186. inputs: KVMap;
  187. run_type: string;
  188. id?: string;
  189. start_time?: number;
  190. end_time?: number;
  191. extra?: KVMap;
  192. error?: string;
  193. serialized?: object;
  194. outputs?: KVMap;
  195. reference_example_id?: string;
  196. child_runs?: RunCreate[];
  197. parent_run_id?: string;
  198. project_name?: string;
  199. revision_id?: string;
  200. trace_id?: string;
  201. dotted_order?: string;
  202. attachments?: Attachments;
  203. }
  204. interface ProjectOptions {
  205. projectName?: string;
  206. projectId?: string;
  207. }
  208. type RecordStringAny = Record<string, any>;
  209. export type FeedbackSourceType = "model" | "api" | "app";
  210. export type CreateExampleOptions = {
  211. /** The ID of the dataset to create the example in. */
  212. datasetId?: string;
  213. /** The name of the dataset to create the example in (if dataset ID is not provided). */
  214. datasetName?: string;
  215. /** The creation date of the example. */
  216. createdAt?: Date;
  217. /** A unique identifier for the example. */
  218. exampleId?: string;
  219. /** Additional metadata associated with the example. */
  220. metadata?: KVMap;
  221. /** The split(s) to assign the example to. */
  222. split?: string | string[];
  223. /** The ID of the source run associated with this example. */
  224. sourceRunId?: string;
  225. /** Whether to use the inputs and outputs from the source run. */
  226. useSourceRunIO?: boolean;
  227. /** Which attachments from the source run to use. */
  228. useSourceRunAttachments?: string[];
  229. /** Attachments for the example */
  230. attachments?: Attachments;
  231. };
  232. export type CreateProjectParams = {
  233. projectName: string;
  234. description?: string | null;
  235. metadata?: RecordStringAny | null;
  236. upsert?: boolean;
  237. projectExtra?: RecordStringAny | null;
  238. referenceDatasetId?: string | null;
  239. };
  240. type AutoBatchQueueItem = {
  241. action: "create" | "update";
  242. item: RunCreate | RunUpdate;
  243. };
  244. type Thread = {
  245. filter: string;
  246. count: number;
  247. total_tokens: number;
  248. total_cost: number | null;
  249. min_start_time: string;
  250. max_start_time: string;
  251. latency_p50: number;
  252. latency_p99: number;
  253. feedback_stats: any | null;
  254. group_key: string;
  255. first_inputs: string;
  256. last_outputs: string;
  257. last_error: string | null;
  258. };
  259. export declare function mergeRuntimeEnvIntoRunCreate(run: RunCreate): RunCreate;
  260. export declare class AutoBatchQueue {
  261. items: {
  262. action: "create" | "update";
  263. payload: RunCreate | RunUpdate;
  264. itemPromiseResolve: () => void;
  265. itemPromise: Promise<void>;
  266. size: number;
  267. }[];
  268. sizeBytes: number;
  269. peek(): {
  270. action: "create" | "update";
  271. payload: RunCreate | RunUpdate;
  272. itemPromiseResolve: () => void;
  273. itemPromise: Promise<void>;
  274. size: number;
  275. };
  276. push(item: AutoBatchQueueItem): Promise<void>;
  277. pop(upToSizeBytes: number): [AutoBatchQueueItem[], () => void];
  278. }
  279. export declare const DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20971520;
  280. export declare class Client implements LangSmithTracingClientInterface {
  281. private apiKey?;
  282. private apiUrl;
  283. private webUrl?;
  284. private caller;
  285. private batchIngestCaller;
  286. private timeout_ms;
  287. private _tenantId;
  288. private hideInputs?;
  289. private hideOutputs?;
  290. private tracingSampleRate?;
  291. private filteredPostUuids;
  292. private autoBatchTracing;
  293. private autoBatchQueue;
  294. private autoBatchTimeout;
  295. private autoBatchAggregationDelayMs;
  296. private batchSizeBytesLimit?;
  297. private fetchOptions;
  298. private settings;
  299. private blockOnRootRunFinalization;
  300. private traceBatchConcurrency;
  301. private _serverInfo;
  302. private _getServerInfoPromise?;
  303. private manualFlushMode;
  304. debug: boolean;
  305. constructor(config?: ClientConfig);
  306. static getDefaultClientConfig(): {
  307. apiUrl: string;
  308. apiKey?: string;
  309. webUrl?: string;
  310. hideInputs?: boolean;
  311. hideOutputs?: boolean;
  312. };
  313. getHostUrl(): string;
  314. private get headers();
  315. private processInputs;
  316. private processOutputs;
  317. private prepareRunCreateOrUpdateInputs;
  318. private _getResponse;
  319. private _get;
  320. private _getPaginated;
  321. private _getCursorPaginatedList;
  322. private _shouldSample;
  323. private _filterForSampling;
  324. private _getBatchSizeLimitBytes;
  325. private _getMultiPartSupport;
  326. private drainAutoBatchQueue;
  327. private _processBatch;
  328. private processRunOperation;
  329. protected _getServerInfo(): Promise<any>;
  330. protected _ensureServerInfo(): Promise<Record<string, any>>;
  331. protected _getSettings(): Promise<LangSmithSettings>;
  332. /**
  333. * Flushes current queued traces.
  334. */
  335. flush(): Promise<void>;
  336. createRun(run: CreateRunParams): Promise<void>;
  337. /**
  338. * Batch ingest/upsert multiple runs in the Langsmith system.
  339. * @param runs
  340. */
  341. batchIngestRuns({ runCreates, runUpdates, }: {
  342. runCreates?: RunCreate[];
  343. runUpdates?: RunUpdate[];
  344. }): Promise<void>;
  345. private _postBatchIngestRuns;
  346. /**
  347. * Batch ingest/upsert multiple runs in the Langsmith system.
  348. * @param runs
  349. */
  350. multipartIngestRuns({ runCreates, runUpdates, }: {
  351. runCreates?: RunCreate[];
  352. runUpdates?: RunUpdate[];
  353. }): Promise<void>;
  354. private _createNodeFetchBody;
  355. private _createMultipartStream;
  356. private _sendMultipartRequest;
  357. updateRun(runId: string, run: RunUpdate): Promise<void>;
  358. readRun(runId: string, { loadChildRuns }?: {
  359. loadChildRuns: boolean;
  360. }): Promise<Run>;
  361. getRunUrl({ runId, run, projectOpts, }: {
  362. runId?: string;
  363. run?: Run;
  364. projectOpts?: ProjectOptions;
  365. }): Promise<string>;
  366. private _loadChildRuns;
  367. /**
  368. * List runs from the LangSmith server.
  369. * @param projectId - The ID of the project to filter by.
  370. * @param projectName - The name of the project to filter by.
  371. * @param parentRunId - The ID of the parent run to filter by.
  372. * @param traceId - The ID of the trace to filter by.
  373. * @param referenceExampleId - The ID of the reference example to filter by.
  374. * @param startTime - The start time to filter by.
  375. * @param isRoot - Indicates whether to only return root runs.
  376. * @param runType - The run type to filter by.
  377. * @param error - Indicates whether to filter by error runs.
  378. * @param id - The ID of the run to filter by.
  379. * @param query - The query string to filter by.
  380. * @param filter - The filter string to apply to the run spans.
  381. * @param traceFilter - The filter string to apply on the root run of the trace.
  382. * @param treeFilter - The filter string to apply on other runs in the trace.
  383. * @param limit - The maximum number of runs to retrieve.
  384. * @returns {AsyncIterable<Run>} - The runs.
  385. *
  386. * @example
  387. * // List all runs in a project
  388. * const projectRuns = client.listRuns({ projectName: "<your_project>" });
  389. *
  390. * @example
  391. * // List LLM and Chat runs in the last 24 hours
  392. * const todaysLLMRuns = client.listRuns({
  393. * projectName: "<your_project>",
  394. * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000),
  395. * run_type: "llm",
  396. * });
  397. *
  398. * @example
  399. * // List traces in a project
  400. * const rootRuns = client.listRuns({
  401. * projectName: "<your_project>",
  402. * execution_order: 1,
  403. * });
  404. *
  405. * @example
  406. * // List runs without errors
  407. * const correctRuns = client.listRuns({
  408. * projectName: "<your_project>",
  409. * error: false,
  410. * });
  411. *
  412. * @example
  413. * // List runs by run ID
  414. * const runIds = [
  415. * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836",
  416. * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074",
  417. * ];
  418. * const selectedRuns = client.listRuns({ run_ids: runIds });
  419. *
  420. * @example
  421. * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000
  422. * const chainRuns = client.listRuns({
  423. * projectName: "<your_project>",
  424. * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))',
  425. * });
  426. *
  427. * @example
  428. * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1
  429. * const goodExtractorRuns = client.listRuns({
  430. * projectName: "<your_project>",
  431. * filter: 'eq(name, "extractor")',
  432. * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))',
  433. * });
  434. *
  435. * @example
  436. * // 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
  437. * const complexRuns = client.listRuns({
  438. * projectName: "<your_project>",
  439. * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))',
  440. * });
  441. *
  442. * @example
  443. * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds
  444. * const taggedRuns = client.listRuns({
  445. * projectName: "<your_project>",
  446. * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))',
  447. * });
  448. */
  449. listRuns(props: ListRunsParams): AsyncIterable<Run>;
  450. listGroupRuns(props: GroupRunsParams): AsyncIterable<Thread>;
  451. getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }: {
  452. id?: string[];
  453. trace?: string;
  454. parentRun?: string;
  455. runType?: string;
  456. projectNames?: string[];
  457. projectIds?: string[];
  458. referenceExampleIds?: string[];
  459. startTime?: string;
  460. endTime?: string;
  461. error?: boolean;
  462. query?: string;
  463. filter?: string;
  464. traceFilter?: string;
  465. treeFilter?: string;
  466. isRoot?: boolean;
  467. dataSourceType?: string;
  468. }): Promise<any>;
  469. shareRun(runId: string, { shareId }?: {
  470. shareId?: string;
  471. }): Promise<string>;
  472. unshareRun(runId: string): Promise<void>;
  473. readRunSharedLink(runId: string): Promise<string | undefined>;
  474. listSharedRuns(shareToken: string, { runIds, }?: {
  475. runIds?: string[];
  476. }): Promise<Run[]>;
  477. readDatasetSharedSchema(datasetId?: string, datasetName?: string): Promise<DatasetShareSchema>;
  478. shareDataset(datasetId?: string, datasetName?: string): Promise<DatasetShareSchema>;
  479. unshareDataset(datasetId: string): Promise<void>;
  480. readSharedDataset(shareToken: string): Promise<Dataset>;
  481. /**
  482. * Get shared examples.
  483. *
  484. * @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.
  485. * @param {Object} [options] Additional options for listing the examples.
  486. * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by.
  487. * @returns {Promise<Example[]>} The shared examples.
  488. */
  489. listSharedExamples(shareToken: string, options?: {
  490. exampleIds?: string[];
  491. }): Promise<Example[]>;
  492. createProject({ projectName, description, metadata, upsert, projectExtra, referenceDatasetId, }: CreateProjectParams): Promise<TracerSession>;
  493. updateProject(projectId: string, { name, description, metadata, projectExtra, endTime, }: {
  494. name?: string | null;
  495. description?: string | null;
  496. metadata?: RecordStringAny | null;
  497. projectExtra?: RecordStringAny | null;
  498. endTime?: string | null;
  499. }): Promise<TracerSession>;
  500. hasProject({ projectId, projectName, }: {
  501. projectId?: string;
  502. projectName?: string;
  503. }): Promise<boolean>;
  504. readProject({ projectId, projectName, includeStats, }: {
  505. projectId?: string;
  506. projectName?: string;
  507. includeStats?: boolean;
  508. }): Promise<TracerSessionResult>;
  509. getProjectUrl({ projectId, projectName, }: {
  510. projectId?: string;
  511. projectName?: string;
  512. }): Promise<string>;
  513. getDatasetUrl({ datasetId, datasetName, }: {
  514. datasetId?: string;
  515. datasetName?: string;
  516. }): Promise<string>;
  517. private _getTenantId;
  518. listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata, }?: {
  519. projectIds?: string[];
  520. name?: string;
  521. nameContains?: string;
  522. referenceDatasetId?: string;
  523. referenceDatasetName?: string;
  524. referenceFree?: boolean;
  525. metadata?: RecordStringAny;
  526. }): AsyncIterable<TracerSession>;
  527. deleteProject({ projectId, projectName, }: {
  528. projectId?: string;
  529. projectName?: string;
  530. }): Promise<void>;
  531. uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }: UploadCSVParams): Promise<Dataset>;
  532. createDataset(name: string, { description, dataType, inputsSchema, outputsSchema, metadata, }?: {
  533. description?: string;
  534. dataType?: DataType;
  535. inputsSchema?: KVMap;
  536. outputsSchema?: KVMap;
  537. metadata?: RecordStringAny;
  538. }): Promise<Dataset>;
  539. readDataset({ datasetId, datasetName, }: {
  540. datasetId?: string;
  541. datasetName?: string;
  542. }): Promise<Dataset>;
  543. hasDataset({ datasetId, datasetName, }: {
  544. datasetId?: string;
  545. datasetName?: string;
  546. }): Promise<boolean>;
  547. diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }: {
  548. datasetId?: string;
  549. datasetName?: string;
  550. fromVersion: string | Date;
  551. toVersion: string | Date;
  552. }): Promise<DatasetDiffInfo>;
  553. readDatasetOpenaiFinetuning({ datasetId, datasetName, }: {
  554. datasetId?: string;
  555. datasetName?: string;
  556. }): Promise<any[]>;
  557. listDatasets({ limit, offset, datasetIds, datasetName, datasetNameContains, metadata, }?: {
  558. limit?: number;
  559. offset?: number;
  560. datasetIds?: string[];
  561. datasetName?: string;
  562. datasetNameContains?: string;
  563. metadata?: RecordStringAny;
  564. }): AsyncIterable<Dataset>;
  565. /**
  566. * Update a dataset
  567. * @param props The dataset details to update
  568. * @returns The updated dataset
  569. */
  570. updateDataset(props: {
  571. datasetId?: string;
  572. datasetName?: string;
  573. name?: string;
  574. description?: string;
  575. }): Promise<Dataset>;
  576. /**
  577. * Updates a tag on a dataset.
  578. *
  579. * If the tag is already assigned to a different version of this dataset,
  580. * the tag will be moved to the new version. The as_of parameter is used to
  581. * determine which version of the dataset to apply the new tags to.
  582. *
  583. * It must be an exact version of the dataset to succeed. You can
  584. * use the "readDatasetVersion" method to find the exact version
  585. * to apply the tags to.
  586. * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided.
  587. * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided.
  588. * @param params.asOf The timestamp of the dataset to apply the new tags to.
  589. * @param params.tag The new tag to apply to the dataset.
  590. */
  591. updateDatasetTag(props: {
  592. datasetId?: string;
  593. datasetName?: string;
  594. asOf: string | Date;
  595. tag: string;
  596. }): Promise<void>;
  597. deleteDataset({ datasetId, datasetName, }: {
  598. datasetId?: string;
  599. datasetName?: string;
  600. }): Promise<void>;
  601. indexDataset({ datasetId, datasetName, tag, }: {
  602. datasetId?: string;
  603. datasetName?: string;
  604. tag?: string;
  605. }): Promise<void>;
  606. /**
  607. * Lets you run a similarity search query on a dataset.
  608. *
  609. * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing.
  610. *
  611. * @param inputs The input on which to run the similarity search. Must have the
  612. * same schema as the dataset.
  613. *
  614. * @param datasetId The dataset to search for similar examples.
  615. *
  616. * @param limit The maximum number of examples to return. Will return the top `limit` most
  617. * similar examples in order of most similar to least similar. If no similar
  618. * examples are found, random examples will be returned.
  619. *
  620. * @param filter A filter string to apply to the search. Only examples will be returned that
  621. * match the filter string. Some examples of filters
  622. *
  623. * - eq(metadata.mykey, "value")
  624. * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value"))
  625. * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue"))
  626. *
  627. * @returns A list of similar examples.
  628. *
  629. *
  630. * @example
  631. * dataset_id = "123e4567-e89b-12d3-a456-426614174000"
  632. * inputs = {"text": "How many people live in Berlin?"}
  633. * limit = 5
  634. * examples = await client.similarExamples(inputs, dataset_id, limit)
  635. */
  636. similarExamples(inputs: KVMap, datasetId: string, limit: number, { filter, }?: {
  637. filter?: string;
  638. }): Promise<ExampleSearch[]>;
  639. createExample(update: ExampleCreate): Promise<Example>;
  640. /**
  641. * @deprecated This signature is deprecated, use createExample(update: ExampleCreate) instead
  642. */
  643. createExample(inputs: KVMap, outputs: KVMap, options: CreateExampleOptions): Promise<Example>;
  644. createExamples(uploads: ExampleCreate[]): Promise<Example[]>;
  645. /** @deprecated Use the uploads-only overload instead */
  646. createExamples(props: {
  647. inputs?: Array<KVMap>;
  648. outputs?: Array<KVMap>;
  649. metadata?: Array<KVMap>;
  650. splits?: Array<string | Array<string>>;
  651. sourceRunIds?: Array<string>;
  652. useSourceRunIOs?: Array<boolean>;
  653. useSourceRunAttachments?: Array<string[]>;
  654. attachments?: Array<Attachments>;
  655. exampleIds?: Array<string>;
  656. datasetId?: string;
  657. datasetName?: string;
  658. }): Promise<Example[]>;
  659. createLLMExample(input: string, generation: string | undefined, options: CreateExampleOptions): Promise<Example>;
  660. createChatExample(input: KVMap[] | LangChainBaseMessage[], generations: KVMap | LangChainBaseMessage | undefined, options: CreateExampleOptions): Promise<Example>;
  661. readExample(exampleId: string): Promise<Example>;
  662. listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, }?: {
  663. datasetId?: string;
  664. datasetName?: string;
  665. exampleIds?: string[];
  666. asOf?: string | Date;
  667. splits?: string[];
  668. inlineS3Urls?: boolean;
  669. metadata?: KVMap;
  670. limit?: number;
  671. offset?: number;
  672. filter?: string;
  673. includeAttachments?: boolean;
  674. }): AsyncIterable<Example>;
  675. deleteExample(exampleId: string): Promise<void>;
  676. /**
  677. * @deprecated This signature is deprecated, use updateExample(update: ExampleUpdate) instead
  678. */
  679. updateExample(exampleId: string, update: ExampleUpdateWithoutId): Promise<object>;
  680. updateExample(update: ExampleUpdate): Promise<object>;
  681. updateExamples(update: ExampleUpdate[]): Promise<object>;
  682. /**
  683. * Get dataset version by closest date or exact tag.
  684. *
  685. * Use this to resolve the nearest version to a given timestamp or for a given tag.
  686. *
  687. * @param options The options for getting the dataset version
  688. * @param options.datasetId The ID of the dataset
  689. * @param options.datasetName The name of the dataset
  690. * @param options.asOf The timestamp of the dataset to retrieve
  691. * @param options.tag The tag of the dataset to retrieve
  692. * @returns The dataset version
  693. */
  694. readDatasetVersion({ datasetId, datasetName, asOf, tag, }: {
  695. datasetId?: string;
  696. datasetName?: string;
  697. asOf?: string | Date;
  698. tag?: string;
  699. }): Promise<DatasetVersion>;
  700. listDatasetSplits({ datasetId, datasetName, asOf, }: {
  701. datasetId?: string;
  702. datasetName?: string;
  703. asOf?: string | Date;
  704. }): Promise<string[]>;
  705. updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove, }: {
  706. datasetId?: string;
  707. datasetName?: string;
  708. splitName: string;
  709. exampleIds: string[];
  710. remove?: boolean;
  711. }): Promise<void>;
  712. /**
  713. * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.
  714. */
  715. evaluateRun(run: Run | string, evaluator: RunEvaluator, { sourceInfo, loadChildRuns, referenceExample, }?: {
  716. sourceInfo?: KVMap;
  717. loadChildRuns: boolean;
  718. referenceExample?: Example;
  719. }): Promise<Feedback>;
  720. createFeedback(runId: string | null, key: string, { score, value, correction, comment, sourceInfo, feedbackSourceType, sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }: {
  721. score?: ScoreType;
  722. value?: ValueType;
  723. correction?: object;
  724. comment?: string;
  725. sourceInfo?: object;
  726. feedbackSourceType?: FeedbackSourceType;
  727. feedbackConfig?: FeedbackConfig;
  728. sourceRunId?: string;
  729. feedbackId?: string;
  730. eager?: boolean;
  731. projectId?: string;
  732. comparativeExperimentId?: string;
  733. }): Promise<Feedback>;
  734. updateFeedback(feedbackId: string, { score, value, correction, comment, }: {
  735. score?: number | boolean | null;
  736. value?: number | boolean | string | object | null;
  737. correction?: object | null;
  738. comment?: string | null;
  739. }): Promise<void>;
  740. readFeedback(feedbackId: string): Promise<Feedback>;
  741. deleteFeedback(feedbackId: string): Promise<void>;
  742. listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, }?: {
  743. runIds?: string[];
  744. feedbackKeys?: string[];
  745. feedbackSourceTypes?: FeedbackSourceType[];
  746. }): AsyncIterable<Feedback>;
  747. /**
  748. * Creates a presigned feedback token and URL.
  749. *
  750. * The token can be used to authorize feedback metrics without
  751. * needing an API key. This is useful for giving browser-based
  752. * applications the ability to submit feedback without needing
  753. * to expose an API key.
  754. *
  755. * @param runId The ID of the run.
  756. * @param feedbackKey The feedback key.
  757. * @param options Additional options for the token.
  758. * @param options.expiration The expiration time for the token.
  759. *
  760. * @returns A promise that resolves to a FeedbackIngestToken.
  761. */
  762. createPresignedFeedbackToken(runId: string, feedbackKey: string, { expiration, feedbackConfig, }?: {
  763. expiration?: string | TimeDelta;
  764. feedbackConfig?: FeedbackConfig;
  765. }): Promise<FeedbackIngestToken>;
  766. createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }: {
  767. name: string;
  768. experimentIds: Array<string>;
  769. referenceDatasetId?: string;
  770. createdAt?: Date;
  771. description?: string;
  772. metadata?: Record<string, unknown>;
  773. id?: string;
  774. }): Promise<ComparativeExperiment>;
  775. /**
  776. * Retrieves a list of presigned feedback tokens for a given run ID.
  777. * @param runId The ID of the run.
  778. * @returns An async iterable of FeedbackIngestToken objects.
  779. */
  780. listPresignedFeedbackTokens(runId: string): AsyncIterable<FeedbackIngestToken>;
  781. _selectEvalResults(results: EvaluationResult | EvaluationResult[] | EvaluationResults): Array<EvaluationResult>;
  782. _logEvaluationFeedback(evaluatorResponse: EvaluationResult | EvaluationResult[] | EvaluationResults, run?: Run, sourceInfo?: {
  783. [key: string]: any;
  784. }): Promise<[results: EvaluationResult[], feedbacks: Feedback[]]>;
  785. logEvaluationFeedback(evaluatorResponse: EvaluationResult | EvaluationResult[] | EvaluationResults, run?: Run, sourceInfo?: {
  786. [key: string]: any;
  787. }): Promise<EvaluationResult[]>;
  788. /**
  789. * API for managing annotation queues
  790. */
  791. /**
  792. * List the annotation queues on the LangSmith API.
  793. * @param options - The options for listing annotation queues
  794. * @param options.queueIds - The IDs of the queues to filter by
  795. * @param options.name - The name of the queue to filter by
  796. * @param options.nameContains - The substring that the queue name should contain
  797. * @param options.limit - The maximum number of queues to return
  798. * @returns An iterator of AnnotationQueue objects
  799. */
  800. listAnnotationQueues(options?: {
  801. queueIds?: string[];
  802. name?: string;
  803. nameContains?: string;
  804. limit?: number;
  805. }): AsyncIterableIterator<AnnotationQueue>;
  806. /**
  807. * Create an annotation queue on the LangSmith API.
  808. * @param options - The options for creating an annotation queue
  809. * @param options.name - The name of the annotation queue
  810. * @param options.description - The description of the annotation queue
  811. * @param options.queueId - The ID of the annotation queue
  812. * @returns The created AnnotationQueue object
  813. */
  814. createAnnotationQueue(options: {
  815. name: string;
  816. description?: string;
  817. queueId?: string;
  818. rubricInstructions?: string;
  819. }): Promise<AnnotationQueueWithDetails>;
  820. /**
  821. * Read an annotation queue with the specified queue ID.
  822. * @param queueId - The ID of the annotation queue to read
  823. * @returns The AnnotationQueueWithDetails object
  824. */
  825. readAnnotationQueue(queueId: string): Promise<AnnotationQueueWithDetails>;
  826. /**
  827. * Update an annotation queue with the specified queue ID.
  828. * @param queueId - The ID of the annotation queue to update
  829. * @param options - The options for updating the annotation queue
  830. * @param options.name - The new name for the annotation queue
  831. * @param options.description - The new description for the annotation queue
  832. */
  833. updateAnnotationQueue(queueId: string, options: {
  834. name: string;
  835. description?: string;
  836. rubricInstructions?: string;
  837. }): Promise<void>;
  838. /**
  839. * Delete an annotation queue with the specified queue ID.
  840. * @param queueId - The ID of the annotation queue to delete
  841. */
  842. deleteAnnotationQueue(queueId: string): Promise<void>;
  843. /**
  844. * Add runs to an annotation queue with the specified queue ID.
  845. * @param queueId - The ID of the annotation queue
  846. * @param runIds - The IDs of the runs to be added to the annotation queue
  847. */
  848. addRunsToAnnotationQueue(queueId: string, runIds: string[]): Promise<void>;
  849. /**
  850. * Get a run from an annotation queue at the specified index.
  851. * @param queueId - The ID of the annotation queue
  852. * @param index - The index of the run to retrieve
  853. * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object
  854. * @throws {Error} If the run is not found at the given index or for other API-related errors
  855. */
  856. getRunFromAnnotationQueue(queueId: string, index: number): Promise<RunWithAnnotationQueueInfo>;
  857. /**
  858. * Delete a run from an an annotation queue.
  859. * @param queueId - The ID of the annotation queue to delete the run from
  860. * @param queueRunId - The ID of the run to delete from the annotation queue
  861. */
  862. deleteRunFromAnnotationQueue(queueId: string, queueRunId: string): Promise<void>;
  863. /**
  864. * Get the size of an annotation queue.
  865. * @param queueId - The ID of the annotation queue
  866. */
  867. getSizeFromAnnotationQueue(queueId: string): Promise<{
  868. size: number;
  869. }>;
  870. protected _currentTenantIsOwner(owner: string): Promise<boolean>;
  871. protected _ownerConflictError(action: string, owner: string): Promise<Error>;
  872. protected _getLatestCommitHash(promptOwnerAndName: string): Promise<string | undefined>;
  873. protected _likeOrUnlikePrompt(promptIdentifier: string, like: boolean): Promise<LikePromptResponse>;
  874. protected _getPromptUrl(promptIdentifier: string): Promise<string>;
  875. promptExists(promptIdentifier: string): Promise<boolean>;
  876. likePrompt(promptIdentifier: string): Promise<LikePromptResponse>;
  877. unlikePrompt(promptIdentifier: string): Promise<LikePromptResponse>;
  878. listCommits(promptOwnerAndName: string): AsyncIterableIterator<PromptCommit>;
  879. listPrompts(options?: {
  880. isPublic?: boolean;
  881. isArchived?: boolean;
  882. sortField?: PromptSortField;
  883. query?: string;
  884. }): AsyncIterableIterator<Prompt>;
  885. getPrompt(promptIdentifier: string): Promise<Prompt | null>;
  886. createPrompt(promptIdentifier: string, options?: {
  887. description?: string;
  888. readme?: string;
  889. tags?: string[];
  890. isPublic?: boolean;
  891. }): Promise<Prompt>;
  892. createCommit(promptIdentifier: string, object: any, options?: {
  893. parentCommitHash?: string;
  894. }): Promise<string>;
  895. /**
  896. * Update examples with attachments using multipart form data.
  897. * @param updates List of ExampleUpdateWithAttachments objects to upsert
  898. * @returns Promise with the update response
  899. */
  900. updateExamplesMultipart(datasetId: string, updates?: ExampleUpdate[]): Promise<UpdateExamplesResponse>;
  901. private _updateExamplesMultipart;
  902. /**
  903. * Upload examples with attachments using multipart form data.
  904. * @param uploads List of ExampleUploadWithAttachments objects to upload
  905. * @returns Promise with the upload response
  906. * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead
  907. */
  908. uploadExamplesMultipart(datasetId: string, uploads?: ExampleCreate[]): Promise<UploadExamplesResponse>;
  909. private _uploadExamplesMultipart;
  910. updatePrompt(promptIdentifier: string, options?: {
  911. description?: string;
  912. readme?: string;
  913. tags?: string[];
  914. isPublic?: boolean;
  915. isArchived?: boolean;
  916. }): Promise<Record<string, any>>;
  917. deletePrompt(promptIdentifier: string): Promise<void>;
  918. pullPromptCommit(promptIdentifier: string, options?: {
  919. includeModel?: boolean;
  920. }): Promise<PromptCommit>;
  921. /**
  922. * This method should not be used directly, use `import { pull } from "langchain/hub"` instead.
  923. * Using this method directly returns the JSON string of the prompt rather than a LangChain object.
  924. * @private
  925. */
  926. _pullPrompt(promptIdentifier: string, options?: {
  927. includeModel?: boolean;
  928. }): Promise<any>;
  929. pushPrompt(promptIdentifier: string, options?: {
  930. object?: any;
  931. parentCommitHash?: string;
  932. isPublic?: boolean;
  933. description?: string;
  934. readme?: string;
  935. tags?: string[];
  936. }): Promise<string>;
  937. /**
  938. * Clone a public dataset to your own langsmith tenant.
  939. * This operation is idempotent. If you already have a dataset with the given name,
  940. * this function will do nothing.
  941. * @param {string} tokenOrUrl The token of the public dataset to clone.
  942. * @param {Object} [options] Additional options for cloning the dataset.
  943. * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client.
  944. * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset.
  945. * @returns {Promise<void>}
  946. */
  947. clonePublicDataset(tokenOrUrl: string, options?: {
  948. sourceApiUrl?: string;
  949. datasetName?: string;
  950. }): Promise<void>;
  951. private parseTokenOrUrl;
  952. /**
  953. * Awaits all pending trace batches. Useful for environments where
  954. * you need to be sure that all tracing requests finish before execution ends,
  955. * such as serverless environments.
  956. *
  957. * @example
  958. * ```
  959. * import { Client } from "langsmith";
  960. *
  961. * const client = new Client();
  962. *
  963. * try {
  964. * // Tracing happens here
  965. * ...
  966. * } finally {
  967. * await client.awaitPendingTraceBatches();
  968. * }
  969. * ```
  970. *
  971. * @returns A promise that resolves once all currently pending traces have sent.
  972. */
  973. awaitPendingTraceBatches(): Promise<void> | Promise<[...void[], void]>;
  974. }
  975. export interface LangSmithTracingClientInterface {
  976. createRun: (run: CreateRunParams) => Promise<void>;
  977. updateRun: (runId: string, run: RunUpdate) => Promise<void>;
  978. }
  979. export {};