import { AsyncCallerParams } from "./utils/async_caller.js"; import { ComparativeExperiment, DataType, Dataset, DatasetDiffInfo, DatasetShareSchema, Example, ExampleUpdate, ExampleUpdateWithId, Feedback, FeedbackConfig, FeedbackIngestToken, KVMap, LangChainBaseMessage, LangSmithSettings, LikePromptResponse, Prompt, PromptCommit, PromptSortField, Run, RunCreate, RunUpdate, ScoreType, ExampleSearch, TimeDelta, TracerSession, TracerSessionResult, ValueType, AnnotationQueue, RunWithAnnotationQueueInfo } from "./schemas.js"; import { EvaluationResult, EvaluationResults, RunEvaluator } from "./evaluation/evaluator.js"; export interface ClientConfig { apiUrl?: string; apiKey?: string; callerOptions?: AsyncCallerParams; timeout_ms?: number; webUrl?: string; anonymizer?: (values: KVMap) => KVMap; hideInputs?: boolean | ((inputs: KVMap) => KVMap); hideOutputs?: boolean | ((outputs: KVMap) => KVMap); autoBatchTracing?: boolean; pendingAutoBatchedRunLimit?: number; fetchOptions?: RequestInit; } /** * Represents the parameters for listing runs (spans) from the Langsmith server. */ interface ListRunsParams { /** * The ID or IDs of the project(s) to filter by. */ projectId?: string | string[]; /** * The name or names of the project(s) to filter by. */ projectName?: string | string[]; /** * The ID of the trace to filter by. */ traceId?: string; /** * isRoot - Whether to only include root runs. * */ isRoot?: boolean; /** * The execution order to filter by. */ executionOrder?: number; /** * The ID of the parent run to filter by. */ parentRunId?: string; /** * The ID of the reference example to filter by. */ referenceExampleId?: string; /** * The start time to filter by. */ startTime?: Date; /** * The run type to filter by. */ runType?: string; /** * Indicates whether to filter by error runs. */ error?: boolean; /** * The ID or IDs of the runs to filter by. */ id?: string[]; /** * The maximum number of runs to retrieve. */ limit?: number; /** * The query string to filter by. */ query?: string; /** * The filter string to apply. * * Run Filtering: * 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. * 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. * 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. * * Grammar: * The filtering grammar is based on common comparators on fields in the run object. Supported comparators include: * - gte (greater than or equal to) * - gt (greater than) * - lte (less than or equal to) * - lt (less than) * - eq (equal to) * - neq (not equal to) * - has (check if run contains a tag or metadata json blob) * - search (search for a substring in a string field) */ filter?: string; /** * Filter to apply to the ROOT run in the trace tree. This is meant to be used in conjunction with the regular * `filter` parameter to let you filter runs by attributes of the root run within a trace. Example is filtering by * feedback assigned to the trace. */ traceFilter?: string; /** * Filter to apply to OTHER runs in the trace tree, including sibling and child runs. This is meant to be used in * conjunction with the regular `filter` parameter to let you filter runs by attributes of any run within a trace. */ treeFilter?: string; /** * The values to include in the response. */ select?: string[]; } interface UploadCSVParams { csvFile: Blob; fileName: string; inputKeys: string[]; outputKeys: string[]; description?: string; dataType?: DataType; name?: string; } interface CreateRunParams { name: string; inputs: KVMap; run_type: string; id?: string; start_time?: number; end_time?: number; extra?: KVMap; error?: string; serialized?: object; outputs?: KVMap; reference_example_id?: string; child_runs?: RunCreate[]; parent_run_id?: string; project_name?: string; revision_id?: string; trace_id?: string; dotted_order?: string; } interface ProjectOptions { projectName?: string; projectId?: string; } type RecordStringAny = Record; export type FeedbackSourceType = "model" | "api" | "app"; export type CreateExampleOptions = { /** The ID of the dataset to create the example in. */ datasetId?: string; /** The name of the dataset to create the example in (if dataset ID is not provided). */ datasetName?: string; /** The creation date of the example. */ createdAt?: Date; /** A unique identifier for the example. */ exampleId?: string; /** Additional metadata associated with the example. */ metadata?: KVMap; /** The split(s) to assign the example to. */ split?: string | string[]; /** The ID of the source run associated with this example. */ sourceRunId?: string; }; export declare class Queue { items: [T, () => void][]; get size(): number; push(item: T): Promise; pop(upToN: number): [T[], () => void]; } export declare const DEFAULT_BATCH_SIZE_LIMIT_BYTES = 20971520; export declare class Client { private apiKey?; private apiUrl; private webUrl?; private caller; private batchIngestCaller; private timeout_ms; private _tenantId; private hideInputs?; private hideOutputs?; private tracingSampleRate?; private filteredPostUuids; private autoBatchTracing; private batchEndpointSupported?; private autoBatchQueue; private pendingAutoBatchedRunLimit; private autoBatchTimeout; private autoBatchInitialDelayMs; private autoBatchAggregationDelayMs; private serverInfo; private fetchOptions; private settings; constructor(config?: ClientConfig); static getDefaultClientConfig(): { apiUrl: string; apiKey?: string; webUrl?: string; hideInputs?: boolean; hideOutputs?: boolean; }; getHostUrl(): string; private get headers(); private processInputs; private processOutputs; private prepareRunCreateOrUpdateInputs; private _getResponse; private _get; private _getPaginated; private _getCursorPaginatedList; private _filterForSampling; private drainAutoBatchQueue; private processRunOperation; protected _getServerInfo(): Promise; protected batchEndpointIsSupported(): Promise; protected _getSettings(): Promise; createRun(run: CreateRunParams): Promise; /** * Batch ingest/upsert multiple runs in the Langsmith system. * @param runs */ batchIngestRuns({ runCreates, runUpdates, }: { runCreates?: RunCreate[]; runUpdates?: RunUpdate[]; }): Promise; private _postBatchIngestRuns; updateRun(runId: string, run: RunUpdate): Promise; readRun(runId: string, { loadChildRuns }?: { loadChildRuns: boolean; }): Promise; getRunUrl({ runId, run, projectOpts, }: { runId?: string; run?: Run; projectOpts?: ProjectOptions; }): Promise; private _loadChildRuns; /** * List runs from the LangSmith server. * @param projectId - The ID of the project to filter by. * @param projectName - The name of the project to filter by. * @param parentRunId - The ID of the parent run to filter by. * @param traceId - The ID of the trace to filter by. * @param referenceExampleId - The ID of the reference example to filter by. * @param startTime - The start time to filter by. * @param isRoot - Indicates whether to only return root runs. * @param runType - The run type to filter by. * @param error - Indicates whether to filter by error runs. * @param id - The ID of the run to filter by. * @param query - The query string to filter by. * @param filter - The filter string to apply to the run spans. * @param traceFilter - The filter string to apply on the root run of the trace. * @param limit - The maximum number of runs to retrieve. * @returns {AsyncIterable} - The runs. * * @example * // List all runs in a project * const projectRuns = client.listRuns({ projectName: "" }); * * @example * // List LLM and Chat runs in the last 24 hours * const todaysLLMRuns = client.listRuns({ * projectName: "", * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), * run_type: "llm", * }); * * @example * // List traces in a project * const rootRuns = client.listRuns({ * projectName: "", * execution_order: 1, * }); * * @example * // List runs without errors * const correctRuns = client.listRuns({ * projectName: "", * error: false, * }); * * @example * // List runs by run ID * const runIds = [ * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", * ]; * const selectedRuns = client.listRuns({ run_ids: runIds }); * * @example * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 * const chainRuns = client.listRuns({ * projectName: "", * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', * }); * * @example * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 * const goodExtractorRuns = client.listRuns({ * projectName: "", * filter: 'eq(name, "extractor")', * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', * }); * * @example * // 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 * const complexRuns = client.listRuns({ * projectName: "", * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', * }); * * @example * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds * const taggedRuns = client.listRuns({ * projectName: "", * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', * }); */ listRuns(props: ListRunsParams): AsyncIterable; getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }: { id?: string[]; trace?: string; parentRun?: string; runType?: string; projectNames?: string[]; projectIds?: string[]; referenceExampleIds?: string[]; startTime?: string; endTime?: string; error?: boolean; query?: string; filter?: string; traceFilter?: string; treeFilter?: string; isRoot?: boolean; dataSourceType?: string; }): Promise; shareRun(runId: string, { shareId }?: { shareId?: string; }): Promise; unshareRun(runId: string): Promise; readRunSharedLink(runId: string): Promise; listSharedRuns(shareToken: string, { runIds, }?: { runIds?: string[]; }): Promise; readDatasetSharedSchema(datasetId?: string, datasetName?: string): Promise; shareDataset(datasetId?: string, datasetName?: string): Promise; unshareDataset(datasetId: string): Promise; readSharedDataset(shareToken: string): Promise; /** * Get shared examples. * * @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. * @param {Object} [options] Additional options for listing the examples. * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. * @returns {Promise} The shared examples. */ listSharedExamples(shareToken: string, options?: { exampleIds?: string[]; }): Promise; createProject({ projectName, description, metadata, upsert, projectExtra, referenceDatasetId, }: { projectName: string; description?: string | null; metadata?: RecordStringAny | null; upsert?: boolean; projectExtra?: RecordStringAny | null; referenceDatasetId?: string | null; }): Promise; updateProject(projectId: string, { name, description, metadata, projectExtra, endTime, }: { name?: string | null; description?: string | null; metadata?: RecordStringAny | null; projectExtra?: RecordStringAny | null; endTime?: string | null; }): Promise; hasProject({ projectId, projectName, }: { projectId?: string; projectName?: string; }): Promise; readProject({ projectId, projectName, includeStats, }: { projectId?: string; projectName?: string; includeStats?: boolean; }): Promise; getProjectUrl({ projectId, projectName, }: { projectId?: string; projectName?: string; }): Promise; getDatasetUrl({ datasetId, datasetName, }: { datasetId?: string; datasetName?: string; }): Promise; private _getTenantId; listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, referenceFree, metadata, }?: { projectIds?: string[]; name?: string; nameContains?: string; referenceDatasetId?: string; referenceDatasetName?: string; referenceFree?: boolean; metadata?: RecordStringAny; }): AsyncIterable; deleteProject({ projectId, projectName, }: { projectId?: string; projectName?: string; }): Promise; uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }: UploadCSVParams): Promise; createDataset(name: string, { description, dataType, inputsSchema, outputsSchema, metadata, }?: { description?: string; dataType?: DataType; inputsSchema?: KVMap; outputsSchema?: KVMap; metadata?: RecordStringAny; }): Promise; readDataset({ datasetId, datasetName, }: { datasetId?: string; datasetName?: string; }): Promise; hasDataset({ datasetId, datasetName, }: { datasetId?: string; datasetName?: string; }): Promise; diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }: { datasetId?: string; datasetName?: string; fromVersion: string | Date; toVersion: string | Date; }): Promise; readDatasetOpenaiFinetuning({ datasetId, datasetName, }: { datasetId?: string; datasetName?: string; }): Promise; listDatasets({ limit, offset, datasetIds, datasetName, datasetNameContains, metadata, }?: { limit?: number; offset?: number; datasetIds?: string[]; datasetName?: string; datasetNameContains?: string; metadata?: RecordStringAny; }): AsyncIterable; /** * Update a dataset * @param props The dataset details to update * @returns The updated dataset */ updateDataset(props: { datasetId?: string; datasetName?: string; name?: string; description?: string; }): Promise; deleteDataset({ datasetId, datasetName, }: { datasetId?: string; datasetName?: string; }): Promise; indexDataset({ datasetId, datasetName, tag, }: { datasetId?: string; datasetName?: string; tag?: string; }): Promise; /** * Lets you run a similarity search query on a dataset. * * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. * * @param inputs The input on which to run the similarity search. Must have the * same schema as the dataset. * * @param datasetId The dataset to search for similar examples. * * @param limit The maximum number of examples to return. Will return the top `limit` most * similar examples in order of most similar to least similar. If no similar * examples are found, random examples will be returned. * * @param filter A filter string to apply to the search. Only examples will be returned that * match the filter string. Some examples of filters * * - eq(metadata.mykey, "value") * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) * * @returns A list of similar examples. * * * @example * dataset_id = "123e4567-e89b-12d3-a456-426614174000" * inputs = {"text": "How many people live in Berlin?"} * limit = 5 * examples = await client.similarExamples(inputs, dataset_id, limit) */ similarExamples(inputs: KVMap, datasetId: string, limit: number, { filter, }?: { filter?: string; }): Promise; createExample(inputs: KVMap, outputs: KVMap, { datasetId, datasetName, createdAt, exampleId, metadata, split, sourceRunId, }: CreateExampleOptions): Promise; createExamples(props: { inputs: Array; outputs?: Array; metadata?: Array; splits?: Array>; sourceRunIds?: Array; exampleIds?: Array; datasetId?: string; datasetName?: string; }): Promise; createLLMExample(input: string, generation: string | undefined, options: CreateExampleOptions): Promise; createChatExample(input: KVMap[] | LangChainBaseMessage[], generations: KVMap | LangChainBaseMessage | undefined, options: CreateExampleOptions): Promise; readExample(exampleId: string): Promise; listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, }?: { datasetId?: string; datasetName?: string; exampleIds?: string[]; asOf?: string | Date; splits?: string[]; inlineS3Urls?: boolean; metadata?: KVMap; limit?: number; offset?: number; filter?: string; }): AsyncIterable; deleteExample(exampleId: string): Promise; updateExample(exampleId: string, update: ExampleUpdate): Promise; updateExamples(update: ExampleUpdateWithId[]): Promise; listDatasetSplits({ datasetId, datasetName, asOf, }: { datasetId?: string; datasetName?: string; asOf?: string | Date; }): Promise; updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove, }: { datasetId?: string; datasetName?: string; splitName: string; exampleIds: string[]; remove?: boolean; }): Promise; /** * @deprecated This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead. */ evaluateRun(run: Run | string, evaluator: RunEvaluator, { sourceInfo, loadChildRuns, referenceExample, }?: { sourceInfo?: KVMap; loadChildRuns: boolean; referenceExample?: Example; }): Promise; createFeedback(runId: string | null, key: string, { score, value, correction, comment, sourceInfo, feedbackSourceType, sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }: { score?: ScoreType; value?: ValueType; correction?: object; comment?: string; sourceInfo?: object; feedbackSourceType?: FeedbackSourceType; feedbackConfig?: FeedbackConfig; sourceRunId?: string; feedbackId?: string; eager?: boolean; projectId?: string; comparativeExperimentId?: string; }): Promise; updateFeedback(feedbackId: string, { score, value, correction, comment, }: { score?: number | boolean | null; value?: number | boolean | string | object | null; correction?: object | null; comment?: string | null; }): Promise; readFeedback(feedbackId: string): Promise; deleteFeedback(feedbackId: string): Promise; listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, }?: { runIds?: string[]; feedbackKeys?: string[]; feedbackSourceTypes?: FeedbackSourceType[]; }): AsyncIterable; /** * Creates a presigned feedback token and URL. * * The token can be used to authorize feedback metrics without * needing an API key. This is useful for giving browser-based * applications the ability to submit feedback without needing * to expose an API key. * * @param runId - The ID of the run. * @param feedbackKey - The feedback key. * @param options - Additional options for the token. * @param options.expiration - The expiration time for the token. * * @returns A promise that resolves to a FeedbackIngestToken. */ createPresignedFeedbackToken(runId: string, feedbackKey: string, { expiration, feedbackConfig, }?: { expiration?: string | TimeDelta; feedbackConfig?: FeedbackConfig; }): Promise; createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }: { name: string; experimentIds: Array; referenceDatasetId?: string; createdAt?: Date; description?: string; metadata?: Record; id?: string; }): Promise; /** * Retrieves a list of presigned feedback tokens for a given run ID. * @param runId The ID of the run. * @returns An async iterable of FeedbackIngestToken objects. */ listPresignedFeedbackTokens(runId: string): AsyncIterable; _selectEvalResults(results: EvaluationResult | EvaluationResults): Array; _logEvaluationFeedback(evaluatorResponse: EvaluationResult | EvaluationResults, run?: Run, sourceInfo?: { [key: string]: any; }): Promise<[results: EvaluationResult[], feedbacks: Feedback[]]>; logEvaluationFeedback(evaluatorResponse: EvaluationResult | EvaluationResults, run?: Run, sourceInfo?: { [key: string]: any; }): Promise; /** * API for managing annotation queues */ /** * List the annotation queues on the LangSmith API. * @param options - The options for listing annotation queues * @param options.queueIds - The IDs of the queues to filter by * @param options.name - The name of the queue to filter by * @param options.nameContains - The substring that the queue name should contain * @param options.limit - The maximum number of queues to return * @returns An iterator of AnnotationQueue objects */ listAnnotationQueues(options?: { queueIds?: string[]; name?: string; nameContains?: string; limit?: number; }): AsyncIterableIterator; /** * Create an annotation queue on the LangSmith API. * @param options - The options for creating an annotation queue * @param options.name - The name of the annotation queue * @param options.description - The description of the annotation queue * @param options.queueId - The ID of the annotation queue * @returns The created AnnotationQueue object */ createAnnotationQueue(options: { name: string; description?: string; queueId?: string; }): Promise; /** * Read an annotation queue with the specified queue ID. * @param queueId - The ID of the annotation queue to read * @returns The AnnotationQueue object */ readAnnotationQueue(queueId: string): Promise; /** * Update an annotation queue with the specified queue ID. * @param queueId - The ID of the annotation queue to update * @param options - The options for updating the annotation queue * @param options.name - The new name for the annotation queue * @param options.description - The new description for the annotation queue */ updateAnnotationQueue(queueId: string, options: { name: string; description?: string; }): Promise; /** * Delete an annotation queue with the specified queue ID. * @param queueId - The ID of the annotation queue to delete */ deleteAnnotationQueue(queueId: string): Promise; /** * Add runs to an annotation queue with the specified queue ID. * @param queueId - The ID of the annotation queue * @param runIds - The IDs of the runs to be added to the annotation queue */ addRunsToAnnotationQueue(queueId: string, runIds: string[]): Promise; /** * Get a run from an annotation queue at the specified index. * @param queueId - The ID of the annotation queue * @param index - The index of the run to retrieve * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object * @throws {Error} If the run is not found at the given index or for other API-related errors */ getRunFromAnnotationQueue(queueId: string, index: number): Promise; protected _currentTenantIsOwner(owner: string): Promise; protected _ownerConflictError(action: string, owner: string): Promise; protected _getLatestCommitHash(promptOwnerAndName: string): Promise; protected _likeOrUnlikePrompt(promptIdentifier: string, like: boolean): Promise; protected _getPromptUrl(promptIdentifier: string): Promise; promptExists(promptIdentifier: string): Promise; likePrompt(promptIdentifier: string): Promise; unlikePrompt(promptIdentifier: string): Promise; listCommits(promptOwnerAndName: string): AsyncIterableIterator; listPrompts(options?: { isPublic?: boolean; isArchived?: boolean; sortField?: PromptSortField; query?: string; }): AsyncIterableIterator; getPrompt(promptIdentifier: string): Promise; createPrompt(promptIdentifier: string, options?: { description?: string; readme?: string; tags?: string[]; isPublic?: boolean; }): Promise; createCommit(promptIdentifier: string, object: any, options?: { parentCommitHash?: string; }): Promise; updatePrompt(promptIdentifier: string, options?: { description?: string; readme?: string; tags?: string[]; isPublic?: boolean; isArchived?: boolean; }): Promise>; deletePrompt(promptIdentifier: string): Promise; pullPromptCommit(promptIdentifier: string, options?: { includeModel?: boolean; }): Promise; /** * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. * Using this method directly returns the JSON string of the prompt rather than a LangChain object. * @private */ _pullPrompt(promptIdentifier: string, options?: { includeModel?: boolean; }): Promise; pushPrompt(promptIdentifier: string, options?: { object?: any; parentCommitHash?: string; isPublic?: boolean; description?: string; readme?: string; tags?: string[]; }): Promise; /** * Clone a public dataset to your own langsmith tenant. * This operation is idempotent. If you already have a dataset with the given name, * this function will do nothing. * @param {string} tokenOrUrl The token of the public dataset to clone. * @param {Object} [options] Additional options for cloning the dataset. * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. * @returns {Promise} */ clonePublicDataset(tokenOrUrl: string, options?: { sourceApiUrl?: string; datasetName?: string; }): Promise; private parseTokenOrUrl; } export {};