{"name":"langsmith","version":"0.7.5","keywords":["LLM","Tracing","Evaluation","LangChain"],"author":{"name":"LangChain"},"license":"MIT","_id":"langsmith@0.7.5","maintainers":[{"name":"jacoblee93","email":"jacoblee93@gmail.com"},{"name":"davidduong","email":"david@duong.cz"},{"name":"basproul","email":"braceasproul@gmail.com"},{"name":"wifuhi","email":"whinthorn@gmail.com"},{"name":"maddyadams","email":"madelyn.adams1@gmail.com"}],"homepage":"https://github.com/langchain-ai/langsmith-sdk#readme","bugs":{"url":"https://github.com/langchain-ai/langsmith-sdk/issues"},"dist":{"shasum":"5d0e38135f6a3b6f0061e779fa77f792007b0dd4","tarball":"http://registry-npm.ywwl.com/langsmith/download/langsmith-0.7.5.tgz","fileCount":517,"integrity":"sha512-OeD6+yKtWwy6sAboq25kD5DICzYv7j2KgtV2n4LsJ8nU2LpEdt1UwbjA6BON/zTggmS/YjV2TtLTHd7VEJhtEA==","signatures":[{"sig":"MEUCIQDUN6IOraYchXQS4g5fqBJD7jqTdHmf3trYv4ND0ualXAIgeyZgRACjWjJfpUGHOQ+rJSxAe1S0/wWO5phnzOrh2ro=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/langsmith@0.7.5","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":2453851,"size":516124,"noattachment":false,"key":"/langsmith/-/langsmith-0.7.5.tgz"},"main":"./dist/index.js","pnpm":{"overrides":{"vite":"^7.3.2","js-yaml":"^4.1.1"}},"type":"module","types":"./dist/index.d.ts","browser":{"./dist/utils/fs.js":"./dist/utils/fs.browser.js","./dist/utils/worker_threads.js":"./dist/utils/worker_threads.browser.js"},"exports":{".":{"types":{"import":"./index.d.ts","default":"./index.d.ts","require":"./index.d.cts"},"import":"./index.js","require":"./index.cjs"},"./jest":{"types":{"import":"./jest.d.ts","default":"./jest.d.ts","require":"./jest.d.cts"},"import":"./jest.js","require":"./jest.cjs"},"./client":{"types":{"import":"./client.d.ts","default":"./client.d.ts","require":"./client.d.cts"},"import":"./client.js","require":"./client.cjs"},"./vitest":{"types":{"import":"./vitest.d.ts","default":"./vitest.d.ts","require":"./vitest.d.cts"},"import":"./vitest.js","require":"./vitest.cjs"},"./sandbox":{"types":{"import":"./sandbox.d.ts","default":"./sandbox.d.ts","require":"./sandbox.d.cts"},"import":"./sandbox.js","require":"./sandbox.cjs"},"./schemas":{"types":{"import":"./schemas.d.ts","default":"./schemas.d.ts","require":"./schemas.d.cts"},"import":"./schemas.js","require":"./schemas.cjs"},"./wrappers":{"types":{"import":"./wrappers.d.ts","default":"./wrappers.d.ts","require":"./wrappers.d.cts"},"import":"./wrappers.js","require":"./wrappers.cjs"},"./langchain":{"types":{"import":"./langchain.d.ts","default":"./langchain.d.ts","require":"./langchain.d.cts"},"import":"./langchain.js","require":"./langchain.cjs"},"./run_trees":{"types":{"import":"./run_trees.d.ts","default":"./run_trees.d.ts","require":"./run_trees.d.cts"},"import":"./run_trees.js","require":"./run_trees.cjs"},"./traceable":{"types":{"import":"./traceable.d.ts","default":"./traceable.d.ts","require":"./traceable.d.cts"},"import":"./traceable.js","require":"./traceable.cjs"},"./anonymizer":{"types":{"import":"./anonymizer.d.ts","default":"./anonymizer.d.ts","require":"./anonymizer.d.cts"},"import":"./anonymizer.js","require":"./anonymizer.cjs"},"./evaluation":{"types":{"import":"./evaluation.d.ts","default":"./evaluation.d.ts","require":"./evaluation.d.cts"},"import":"./evaluation.js","require":"./evaluation.cjs"},"./package.json":"./package.json","./jest/reporter":{"types":{"import":"./jest/reporter.d.ts","default":"./jest/reporter.d.ts","require":"./jest/reporter.d.cts"},"import":"./jest/reporter.js","require":"./jest/reporter.cjs"},"./utils/jestlike":{"types":{"import":"./utils/jestlike.d.ts","default":"./utils/jestlike.d.ts","require":"./utils/jestlike.d.cts"},"import":"./utils/jestlike.js","require":"./utils/jestlike.cjs"},"./vitest/reporter":{"types":{"import":"./vitest/reporter.d.ts","default":"./vitest/reporter.d.ts","require":"./vitest/reporter.d.cts"},"import":"./vitest/reporter.js","require":"./vitest/reporter.cjs"},"./wrappers/gemini":{"types":{"import":"./wrappers/gemini.d.ts","default":"./wrappers/gemini.d.ts","require":"./wrappers/gemini.d.cts"},"import":"./wrappers/gemini.js","require":"./wrappers/gemini.cjs"},"./wrappers/openai":{"types":{"import":"./wrappers/openai.d.ts","default":"./wrappers/openai.d.ts","require":"./wrappers/openai.d.cts"},"import":"./wrappers/openai.js","require":"./wrappers/openai.cjs"},"./wrappers/anthropic":{"types":{"import":"./wrappers/anthropic.d.ts","default":"./wrappers/anthropic.d.ts","require":"./wrappers/anthropic.d.cts"},"import":"./wrappers/anthropic.js","require":"./wrappers/anthropic.cjs"},"./experimental/vercel":{"types":{"import":"./experimental/vercel.d.ts","default":"./experimental/vercel.d.ts","require":"./experimental/vercel.d.cts"},"import":"./experimental/vercel.js","require":"./experimental/vercel.cjs"},"./experimental/sandbox":{"types":{"import":"./experimental/sandbox.d.ts","default":"./experimental/sandbox.d.ts","require":"./experimental/sandbox.d.cts"},"import":"./experimental/sandbox.js","require":"./experimental/sandbox.cjs"},"./singletons/traceable":{"types":{"import":"./singletons/traceable.d.ts","default":"./singletons/traceable.d.ts","require":"./singletons/traceable.d.cts"},"import":"./singletons/traceable.js","require":"./singletons/traceable.cjs"},"./experimental/anthropic":{"types":{"import":"./experimental/anthropic.d.ts","default":"./experimental/anthropic.d.ts","require":"./experimental/anthropic.d.cts"},"import":"./experimental/anthropic.js","require":"./experimental/anthropic.cjs"},"./wrappers/openai_agents":{"types":{"import":"./wrappers/openai_agents.d.ts","default":"./wrappers/openai_agents.d.ts","require":"./wrappers/openai_agents.d.cts"},"import":"./wrappers/openai_agents.js","require":"./wrappers/openai_agents.cjs"},"./experimental/otel/setup":{"types":{"import":"./experimental/otel/setup.d.ts","default":"./experimental/otel/setup.d.ts","require":"./experimental/otel/setup.d.cts"},"import":"./experimental/otel/setup.js","require":"./experimental/otel/setup.cjs"},"./experimental/otel/exporter":{"types":{"import":"./experimental/otel/exporter.d.ts","default":"./experimental/otel/exporter.d.ts","require":"./experimental/otel/exporter.d.cts"},"import":"./experimental/otel/exporter.js","require":"./experimental/otel/exporter.cjs"},"./experimental/otel/processor":{"types":{"import":"./experimental/otel/processor.d.ts","default":"./experimental/otel/processor.d.ts","require":"./experimental/otel/processor.d.cts"},"import":"./experimental/otel/processor.js","require":"./experimental/otel/processor.cjs"}},"gitHead":"8049af9b0f3d2739d875f1dae472fb07990a4fec","scripts":{"lint":"oxlint src/","test":"cross-env NODE_OPTIONS=--experimental-vm-modules jest --passWithNoTests --testPathIgnorePatterns='\\.int\\.test.[tj]s' --testTimeout 30000","build":"pnpm clean && pnpm build:esm && pnpm build:cjs && node scripts/create-entrypoints.js","clean":"rm -rf dist/ && node scripts/create-entrypoints.js clean","format":"oxfmt --write 'src/**/*.{ts,tsx,mts}'","lint:fix":"oxlint --fix src/","build:cjs":"echo '{}' > src/package.json && tsc --outDir dist-cjs/ -p tsconfig.cjs.json && node scripts/move-cjs-to-dist.js && rm -r dist-cjs src/package.json","build:esm":"rm -f src/package.json && tsc --outDir dist/ && rm -rf dist/tests dist/**/tests","precommit":"lint-staged","prepublish":"pnpm run build","check:types":"tsc --noEmit","test:single":"NODE_OPTIONS=--experimental-vm-modules pnpm jest --config jest.config.cjs --testTimeout 100000","test:vitest":"vitest run --config vitest.config.ts","bump-version":"node scripts/bump-version.js","format:check":"oxfmt --check 'src/**/*.{ts,tsx,mts}'","watch:single":"NODE_OPTIONS=--experimental-vm-modules pnpm jest --watch --config jest.config.cjs --testTimeout 100000","build:typedoc":"pnpm build && rm -rf ./_build/api_refs && npx typedoc","check-version":"node scripts/check-version.js","test:eval:vitest":"vitest run --config ls.vitest.config.ts","test:integration":"cross-env NODE_OPTIONS=--experimental-vm-modules jest --testPathPattern=\\.int\\.test.ts --testTimeout 100000","check-npm-version":"node scripts/check-npm-version.js"},"_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"oidc:db1dd763-e5d6-497b-8730-ff9baf1bae7c"}},"repository":{"url":"git+https://github.com/langchain-ai/langsmith-sdk.git","type":"git"},"_npmVersion":"11.13.0","description":"Client library to connect to the LangSmith Observability and Evaluation Platform.","directories":{},"lint-staged":{"**/*.{ts,tsx}":["oxfmt --write","oxlint --fix"]},"_nodeVersion":"24.16.0","dependencies":{"p-queue":"6.6.2"},"_hasShrinkwrap":false,"packageManager":"pnpm@10.33.0","devDependencies":{"ai":"7.0.0-canary.142","ws":"^8.19.0","msw":"^2.11.2","zod":"^4.3.6","jest":"^29.5.0","oxfmt":"^0.47.0","dotenv":"^17.3.1","openai":"^6.18.0","oxlint":"^1.62.0","semver":"^7.7.4","vitest":"^3.1.3","ts-jest":"^29.1.0","ts-node":"^10.9.1","typedoc":"^0.28.16","mongoose":"^9.5.0","@types/ws":"^8.18.1","cross-env":"^10.1.0","langchain":"^0.3.29","babel-jest":"^30.2.0","node-fetch":"^3.3.2","typescript":"^6.0.3","@types/jest":"^29.5.1","@types/node":"^25.9.1","@google/genai":"^2.0.1","@jest/globals":"^29.5.0","@types/semver":"^7.7.1","@ai-sdk/openai":"4.0.0-canary.59","@openai/agents":"^0.11.5","@faker-js/faker":"^8.4.1","@jest/reporters":"^30.2.0","@langchain/core":"^0.3.72","@ai-sdk/provider":"4.0.0-canary.16","@ai-sdk/anthropic":"4.0.0-canary.55","@anthropic-ai/sdk":"^0.98.0","@babel/preset-env":"^7.22.4","@langchain/openai":"^0.6.17","@types/node-fetch":"^2.6.12","@opentelemetry/api":"^1.9.0","@langchain/langgraph":"^0.3.6","@tsconfig/recommended":"^1.0.2","@opentelemetry/sdk-node":"^0.218.0","@typescript-eslint/parser":"^5.59.8","@opentelemetry/sdk-trace-base":"^2.0.0","@opentelemetry/sdk-trace-node":"^2.0.0","@anthropic-ai/claude-agent-sdk":"^0.3.150","@typescript-eslint/eslint-plugin":"^5.59.8","@opentelemetry/context-async-hooks":"^2.6.1","typedoc-plugin-expand-object-like-types":"^0.1.2","@opentelemetry/auto-instrumentations-node":"^0.76.0"},"peerDependencies":{"ws":">=7","openai":"*","@opentelemetry/api":"*","@opentelemetry/sdk-trace-base":"*","@opentelemetry/exporter-trace-otlp-proto":"*"},"peerDependenciesMeta":{"ws":{"optional":true},"openai":{"optional":true},"@opentelemetry/api":{"optional":true},"@opentelemetry/sdk-trace-base":{"optional":true},"@opentelemetry/exporter-trace-otlp-proto":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/langsmith_0.7.5_1780620585812_0.7645365642295354","host":"s3://npm-registry-packages-npm-production"},"readme":"# LangSmith Client SDK\n\n![NPM Version](https://img.shields.io/npm/v/langsmith?logo=npm)\n[![JS Downloads](https://img.shields.io/npm/dm/langsmith)](https://www.npmjs.com/package/langsmith)\n\nThis package contains the TypeScript client for interacting with the [LangSmith platform](https://smith.langchain.com/).\n\nTo install:\n\n```bash\npnpm add langsmith\n```\n\nLangSmith helps you and your team develop and evaluate language models and intelligent agents. It is compatible with any LLM Application and provides seamless integration with [LangChain](https://github.com/hwchase17/langchainjs), a widely recognized open-source framework that simplifies the process for developers to create powerful language model applications.\n\n> **Note**: You can enjoy the benefits of LangSmith without using the LangChain open-source packages! To get started with your own proprietary framework, set up your account and then skip to [Logging Traces Outside LangChain](#logging-traces-outside-langchain).\n\n> **Cookbook:** For tutorials on how to get more value out of LangSmith, check out the [Langsmith Cookbook](https://github.com/langchain-ai/langsmith-cookbook/tree/main) repo.\n\nA typical workflow looks like:\n\n1. Set up an account with LangSmith.\n2. Log traces.\n3. Debug, Create Datasets, and Evaluate Runs.\n\nWe'll walk through these steps in more detail below.\n\n## Sandbox AWS Auth Proxy\n\nWhen sandbox code needs to call AWS services, use the sandbox AWS auth proxy.\nThe proxy keeps the real AWS credentials outside the sandbox and signs supported\nAWS HTTPS requests with SigV4, so code in the sandbox can use AWS SDKs normally\nwithout storing long-lived AWS keys in files, environment variables, shell\nhistory, or logs.\n\nStore AWS credentials as LangSmith workspace secrets using names that make sense\nfor your workspace. Then create the sandbox with an AWS auth proxy config:\n\n```ts\nimport {\n  SandboxClient,\n  awsAuth,\n  proxyConfig,\n  workspaceSecret,\n} from \"langsmith/sandbox\";\n\nconst client = new SandboxClient();\nconst authConfig = proxyConfig({\n  rules: [\n    awsAuth({\n      accessKeyId: workspaceSecret(\"SANDBOX_AWS_ACCESS_KEY_ID\"),\n      secretAccessKey: workspaceSecret(\"SANDBOX_AWS_SECRET_ACCESS_KEY\"),\n    }),\n  ],\n});\n\nconst sandbox = await client.createSandbox({\n  name: \"aws-sandbox\",\n  proxyConfig: authConfig,\n});\n\ntry {\n  const result = await sandbox.run(\"node your-aws-script.js\");\n  console.log(result.stdout);\n} finally {\n  await sandbox.delete();\n}\n```\n\nUse `opaqueSecret(\"...\")` instead of `workspaceSecret(...)` when your application\nneeds to pass short-lived write-only AWS credentials at sandbox creation time.\nPlaintext AWS credential values are not accepted directly; wrap them as\n`opaqueSecret(...)` values.\n\n## Sandbox GCP Auth Proxy\n\nWhen sandbox code needs to call Google APIs, use the sandbox GCP auth proxy.\nThe proxy keeps the service account JSON outside the sandbox and injects OAuth\nbearer tokens for Google API hosts matched automatically by the sandbox proxy.\n\nStore the service account JSON as a LangSmith workspace secret. Then create the\nsandbox with a GCP auth proxy config:\n\n```ts\nimport {\n  SandboxClient,\n  gcpAuth,\n  proxyConfig,\n  workspaceSecret,\n} from \"langsmith/sandbox\";\n\nconst client = new SandboxClient();\nconst authConfig = proxyConfig({\n  rules: [\n    gcpAuth({\n      serviceAccountJson: workspaceSecret(\"SANDBOX_GCP_SERVICE_ACCOUNT_JSON\"),\n      scopes: [\"https://www.googleapis.com/auth/devstorage.read_write\"],\n    }),\n  ],\n});\n\nconst sandbox = await client.createSandbox({\n  name: \"gcp-sandbox\",\n  proxyConfig: authConfig,\n});\n\ntry {\n  const result = await sandbox.run(\"node your-gcp-script.js\");\n  console.log(result.stdout);\n} finally {\n  await sandbox.delete();\n}\n```\n\nUse `opaqueSecret(\"...\")` for short-lived write-only service account JSON.\nPlaintext service account JSON is not accepted directly.\n\n## Sandbox Mounts\n\nWhen you create a LangSmith sandbox that needs filesystem access to external\ndata such as object storage buckets or public Git repositories, pass a\n`mountConfig` on sandbox creation. Mount specs contain only the mount target.\nProvider credentials stay in `mountConfig.auth`; the backend expands them into\nruntime proxy auth rules. You can also pass `proxyConfig` for non-mount proxy\nbehavior such as custom headers, callbacks, access control, and generic egress\nrules. Explicit AWS/GCP proxy auth rules conflict with `mountConfig` auth for\nthe same provider.\n\nS3 mounts require AWS auth:\n\n```ts\nimport {\n  awsAuth,\n  mountConfig,\n  s3Mount,\n  workspaceSecret,\n} from \"langsmith/sandbox\";\n\nconst mountCfg = mountConfig({\n  auth: [\n    awsAuth({\n      accessKeyId: workspaceSecret(\"SANDBOX_AWS_ACCESS_KEY_ID\"),\n      secretAccessKey: workspaceSecret(\"SANDBOX_AWS_SECRET_ACCESS_KEY\"),\n    }),\n  ],\n  mounts: [\n    s3Mount({\n      id: \"customer_data\",\n      mountPath: \"/mnt/mounts/customer-data\",\n      bucket: \"example-bucket\",\n      prefix: \"datasets/customer-data\",\n      region: \"us-east-1\",\n      endpointUrl: \"https://s3.amazonaws.com\",\n      pathStyle: false,\n      readOnly: false,\n    }),\n  ],\n});\n\nconst sandbox = await client.createSandbox({\n  name: \"s3-mount-sandbox\",\n  mountConfig: mountCfg,\n});\n\ntry {\n  const result = await sandbox.run(\"ls /mnt/mounts/customer-data\");\n  console.log(result.stdout);\n} finally {\n  await sandbox.delete();\n}\n```\n\nGCS mounts require GCP auth:\n\n```ts\nimport {\n  gcpAuth,\n  gcsMount,\n  mountConfig,\n  workspaceSecret,\n} from \"langsmith/sandbox\";\n\nconst mountCfg = mountConfig({\n  auth: [\n    gcpAuth({\n      serviceAccountJson: workspaceSecret(\"SANDBOX_GCP_SERVICE_ACCOUNT_JSON\"),\n    }),\n  ],\n  mounts: [\n    gcsMount({\n      id: \"customer_data\",\n      mountPath: \"/mnt/mounts/customer-data\",\n      bucket: \"example-bucket\",\n      prefix: \"datasets/customer-data\",\n    }),\n  ],\n});\n\nconst sandbox = await client.createSandbox({\n  name: \"gcs-mount-sandbox\",\n  mountConfig: mountCfg,\n});\n\ntry {\n  const result = await sandbox.run(\"ls /mnt/mounts/customer-data\");\n  console.log(result.stdout);\n} finally {\n  await sandbox.delete();\n}\n```\n\nPublic Git mounts do not require AWS or GCP auth:\n\n```ts\nimport { gitMount, mountConfig } from \"langsmith/sandbox\";\n\nconst mountCfg = mountConfig({\n  mounts: [\n    gitMount({\n      id: \"repo\",\n      mountPath: \"/mnt/repo\",\n      remoteUrl: \"https://github.com/langchain-ai/langsmith-sdk.git\",\n      ref: { type: \"branch\", name: \"main\" },\n      refreshIntervalSeconds: 60,\n    }),\n  ],\n});\n\nconst sandbox = await client.createSandbox({\n  name: \"git-mount-sandbox\",\n  mountConfig: mountCfg,\n});\n\ntry {\n  const result = await sandbox.run(\"ls /mnt/repo\");\n  console.log(result.stdout);\n} finally {\n  await sandbox.delete();\n}\n```\n\nPrivate Git repositories can use low-level `proxyConfig` rules when the remote\nrequires proxy-managed auth. There is not yet a high-level private Git auth\nhelper.\n\n## 1. Connect to LangSmith\n\nSign up for [LangSmith](https://smith.langchain.com/) using your GitHub, Discord accounts, or an email address and password. If you sign up with an email, make sure to verify your email address before logging in.\n\nThen, create a unique API key on the [Settings Page](https://smith.langchain.com/settings).\n\n> [!NOTE]\n> Save the API Key in a secure location. It will not be shown again.\n\n## 2. Log Traces\n\nYou can log traces natively in your LangChain application or using a LangSmith RunTree.\n\n### Logging Traces with LangChain\n\nLangSmith seamlessly integrates with the JavaScript LangChain library to record traces from your LLM applications.\n\n```bash\npnpm add langchain\n```\n\n1. **Copy the environment variables from the Settings Page and add them to your application.**\n\nTracing can be activated by setting the following environment variables or by manually specifying the LangChainTracer.\n\n```typescript\nprocess.env.LANGSMITH_TRACING = \"true\";\nprocess.env.LANGSMITH_ENDPOINT = \"https://api.smith.langchain.com\";\n// process.env.LANGSMITH_ENDPOINT = \"https://eu.api.smith.langchain.com\"; // If signed up in the EU region\nprocess.env.LANGSMITH_API_KEY = \"<YOUR-LANGSMITH-API-KEY>\";\n// process.env.LANGSMITH_PROJECT = \"My Project Name\"; // Optional: \"default\" is used if not set\n// process.env.LANGSMITH_WORKSPACE_ID = \"<YOUR-WORKSPACE-ID>\"; // Required for org-scoped API keys\n```\n\n> **Tip:** Projects are groups of traces. All runs are logged to a project. If not specified, the project is set to `default`.\n\n2. **Run an Agent, Chain, or Language Model in LangChain**\n\nIf the environment variables are correctly set, your application will automatically connect to the LangSmith platform.\n\n```typescript\nimport { ChatOpenAI } from \"langchain/chat_models/openai\";\n\nconst chat = new ChatOpenAI({ temperature: 0 });\nconst response = await chat.predict(\n  \"Translate this sentence from English to French. I love programming.\"\n);\nconsole.log(response);\n```\n\n### Logging Traces Outside LangChain\n\nYou can still use the LangSmith development platform without depending on any\nLangChain code. You can connect either by setting the appropriate environment variables,\nor by directly specifying the connection information in the RunTree.\n\n1. **Copy the environment variables from the Settings Page and add them to your application.**\n\n```shell\nexport LANGSMITH_TRACING=\"true\";\nexport LANGSMITH_API_KEY=<YOUR-LANGSMITH-API-KEY>\n# export LANGSMITH_PROJECT=\"My Project Name\" #  Optional: \"default\" is used if not set\n# export LANGSMITH_ENDPOINT=https://api.smith.langchain.com # or your own server\n```\n\n## Integrations\n\nLangsmith's `traceable` wrapper function makes it easy to trace any function or LLM call in your own favorite framework. Below are some examples.\n\n### OpenAI SDK\n\n<!-- markdown-link-check-disable -->\n\nThe easiest way to trace calls from the [OpenAI SDK](https://platform.openai.com/docs/api-reference) with LangSmith\nis using the `wrapOpenAI` wrapper function available in LangSmith 0.1.3 and up.\n\nIn order to use, you first need to set your LangSmith API key:\n\n```shell\nexport LANGSMITH_TRACING=\"true\";\nexport LANGSMITH_API_KEY=<your-api-key>\n```\n\nNext, you will need to install the LangSmith SDK and the OpenAI SDK:\n\n```shell\nnpm install langsmith openai\n```\n\nAfter that, initialize your OpenAI client and wrap the client with `wrapOpenAI` method to enable tracing for the completions and chat completions methods:\n\n```ts\nimport { OpenAI } from \"openai\";\nimport { wrapOpenAI } from \"langsmith/wrappers\";\n\nconst openai = wrapOpenAI(new OpenAI());\n\nawait openai.chat.completions.create({\n  model: \"gpt-5.4\",\n  messages: [{ content: \"Hi there!\", role: \"user\" }],\n});\n```\n\nAlternatively, you can use the `traceable` function to wrap the client methods you want to use:\n\n```ts\nimport { traceable } from \"langsmith/traceable\";\n\nconst openai = new OpenAI();\n\nconst createCompletion = traceable(\n  openai.chat.completions.create.bind(openai.chat.completions),\n  { name: \"OpenAI Chat Completion\", run_type: \"llm\" }\n);\n\nawait createCompletion({\n  model: \"gpt-5.4\",\n  messages: [{ content: \"Hi there!\", role: \"user\" }],\n});\n```\n\nNote the use of `.bind` to preserve the function's context. The `run_type` field in the\nextra config object marks the function as an LLM call, and enables token usage tracking\nfor OpenAI.\n\nOftentimes, you use the OpenAI client inside of other functions or as part of a longer\nsequence. You can automatically get nested traces by using this wrapped method\nwithin other functions wrapped with `traceable`.\n\n```ts\nconst nestedTrace = traceable(async (text: string) => {\n  const completion = await openai.chat.completions.create({\n    model: \"gpt-5.4\",\n    messages: [{ content: text, role: \"user\" }],\n  });\n  return completion;\n});\n\nawait nestedTrace(\"Why is the sky blue?\");\n```\n\n```\n{\n  \"id\": \"chatcmpl-8sPToJQLLVepJvyeTfzZMOMVIKjMo\",\n  \"object\": \"chat.completion\",\n  \"created\": 1707978348,\n  \"model\": \"gpt-5.4\",\n  \"choices\": [\n    {\n      \"index\": 0,\n      \"message\": {\n        \"role\": \"assistant\",\n        \"content\": \"The sky appears blue because of a phenomenon known as Rayleigh scattering. The Earth's atmosphere is composed of tiny molecules, such as nitrogen and oxygen, which are much smaller than the wavelength of visible light. When sunlight interacts with these molecules, it gets scattered in all directions. However, shorter wavelengths of light (blue and violet) are scattered more compared to longer wavelengths (red, orange, and yellow). \\n\\nAs a result, when sunlight passes through the Earth's atmosphere, the blue and violet wavelengths are scattered in all directions, making the sky appear blue. This scattering of shorter wavelengths is also responsible for the vibrant colors observed during sunrise and sunset, when the sunlight has to pass through a thicker portion of the atmosphere, causing the longer wavelengths to dominate the scattered light.\"\n      },\n      \"logprobs\": null,\n      \"finish_reason\": \"stop\"\n    }\n  ],\n  \"usage\": {\n    \"prompt_tokens\": 13,\n    \"completion_tokens\": 154,\n    \"total_tokens\": 167\n  },\n  \"system_fingerprint\": null\n}\n```\n\n:::tip\n[Click here](https://smith.langchain.com/public/4af46ef6-b065-46dc-9cf0-70f1274edb01/r) to see an example LangSmith trace of the above.\n:::\n\n## Next.js\n\nYou can use the `traceable` wrapper function in Next.js apps to wrap arbitrary functions much like in the example above.\n\nOne neat trick you can use for Next.js and other similar server frameworks is to wrap the entire exported handler for a route\nto group traces for the any sub-runs. Here's an example:\n\n```ts\nimport { NextRequest, NextResponse } from \"next/server\";\n\nimport { OpenAI } from \"openai\";\nimport { traceable } from \"langsmith/traceable\";\nimport { wrapOpenAI } from \"langsmith/wrappers\";\n\nexport const runtime = \"edge\";\n\nconst handler = traceable(\n  async function () {\n    const openai = wrapOpenAI(new OpenAI());\n\n    const completion = await openai.chat.completions.create({\n      model: \"gpt-5.4\",\n      messages: [{ content: \"Why is the sky blue?\", role: \"user\" }],\n    });\n\n    const response1 = completion.choices[0].message.content;\n\n    const completion2 = await openai.chat.completions.create({\n      model: \"gpt-5.4\",\n      messages: [\n        { content: \"Why is the sky blue?\", role: \"user\" },\n        { content: response1, role: \"assistant\" },\n        { content: \"Cool thank you!\", role: \"user\" },\n      ],\n    });\n\n    const response2 = completion2.choices[0].message.content;\n\n    return {\n      text: response2,\n    };\n  },\n  {\n    name: \"Simple Next.js handler\",\n  }\n);\n\nexport async function POST(req: NextRequest) {\n  const result = await handler();\n  return NextResponse.json(result);\n}\n```\n\nThe two OpenAI calls within the handler will be traced with appropriate inputs, outputs,\nand token usage information.\n\n:::tip\n[Click here](https://smith.langchain.com/public/faaf26ad-8c59-4622-bcfe-b7d896733ca6/r) to see an example LangSmith trace of the above.\n:::\n\n## Vercel AI SDK\n\nThe [Vercel AI SDK](https://sdk.vercel.ai/docs) contains integrations with a variety of model providers.\nHere's an example of how you can trace outputs in a Next.js handler:\n\n```ts\nimport { traceable } from \"langsmith/traceable\";\nimport { OpenAIStream, StreamingTextResponse } from \"ai\";\n\n// Note: There are no types for the Mistral API client yet.\nimport MistralClient from \"@mistralai/mistralai\";\n\nconst client = new MistralClient(process.env.MISTRAL_API_KEY || \"\");\n\nexport async function POST(req: Request) {\n  // Extract the `messages` from the body of the request\n  const { messages } = await req.json();\n\n  const mistralChatStream = traceable(client.chatStream.bind(client), {\n    name: \"Mistral Stream\",\n    run_type: \"llm\",\n  });\n\n  const response = await mistralChatStream({\n    model: \"mistral-tiny\",\n    maxTokens: 1000,\n    messages,\n  });\n\n  // Convert the response into a friendly text-stream. The Mistral client responses are\n  // compatible with the Vercel AI SDK OpenAIStream adapter.\n  const stream = OpenAIStream(response as any);\n\n  // Respond with the stream\n  return new StreamingTextResponse(stream);\n}\n```\n\nSee the [AI SDK docs](https://sdk.vercel.ai/docs) for more examples.\n\n## Arbitrary SDKs\n\nYou can use the generic `wrapSDK` method to add tracing for arbitrary SDKs.\n\nDo note that this will trace ALL methods in the SDK, not just chat completion endpoints.\nIf the SDK you are wrapping has other methods, we recommend using it for only LLM calls.\n\nHere's an example using the Anthropic SDK:\n\n```ts\nimport { wrapSDK } from \"langsmith/wrappers\";\nimport { Anthropic } from \"@anthropic-ai/sdk\";\n\nconst originalSDK = new Anthropic();\nconst sdkWithTracing = wrapSDK(originalSDK);\n\nconst response = await sdkWithTracing.messages.create({\n  messages: [\n    {\n      role: \"user\",\n      content: `What is 1 + 1? Respond only with \"2\" and nothing else.`,\n    },\n  ],\n  model: \"claude-3-sonnet-20240229\",\n  max_tokens: 1024,\n});\n```\n\n:::tip\n[Click here](https://smith.langchain.com/public/0e7248af-bbed-47cf-be9f-5967fea1dec1/r) to see an example LangSmith trace of the above.\n:::\n\n#### Alternatives: **Log traces using a RunTree.**\n\nA RunTree tracks your application. Each RunTree object is required to have a name and run_type. These and other important attributes are as follows:\n\n- `name`: `string` - used to identify the component's purpose\n- `run_type`: `string` - Currently one of \"llm\", \"chain\" or \"tool\"; more options will be added in the future\n- `inputs`: `Record<string, any>` - the inputs to the component\n- `outputs`: `Optional<Record<string, any>>` - the (optional) returned values from the component\n- `error`: `Optional<string>` - Any error messages that may have arisen during the call\n\n```typescript\nimport { RunTree, RunTreeConfig } from \"langsmith\";\n\nconst parentRunConfig: RunTreeConfig = {\n  name: \"My Chat Bot\",\n  run_type: \"chain\",\n  inputs: {\n    text: \"Summarize this morning's meetings.\",\n  },\n  serialized: {}, // Serialized representation of this chain\n  // project_name: \"Defaults to the LANGSMITH_PROJECT env var\"\n  // apiUrl: \"Defaults to the LANGSMITH_ENDPOINT env var\"\n  // apiKey: \"Defaults to the LANGSMITH_API_KEY env var\"\n};\n\nconst parentRun = new RunTree(parentRunConfig);\n\nawait parentRun.postRun();\n\nconst childLlmRun = await parentRun.createChild({\n  name: \"My Proprietary LLM\",\n  run_type: \"llm\",\n  inputs: {\n    prompts: [\n      \"You are an AI Assistant. The time is XYZ.\" +\n        \" Summarize this morning's meetings.\",\n    ],\n  },\n});\n\nawait childLlmRun.postRun();\n\nawait childLlmRun.end({\n  outputs: {\n    generations: [\n      \"I should use the transcript_loader tool\" +\n        \" to fetch meeting_transcripts from XYZ\",\n    ],\n  },\n});\n\nawait childLlmRun.patchRun();\n\nconst childToolRun = await parentRun.createChild({\n  name: \"transcript_loader\",\n  run_type: \"tool\",\n  inputs: {\n    date: \"XYZ\",\n    content_type: \"meeting_transcripts\",\n  },\n});\nawait childToolRun.postRun();\n\nawait childToolRun.end({\n  outputs: {\n    meetings: [\"Meeting1 notes..\"],\n  },\n});\n\nawait childToolRun.patchRun();\n\nconst childChainRun = await parentRun.createChild({\n  name: \"Unreliable Component\",\n  run_type: \"tool\",\n  inputs: {\n    input: \"Summarize these notes...\",\n  },\n});\n\nawait childChainRun.postRun();\n\ntry {\n  // .... the component does work\n  throw new Error(\"Something went wrong\");\n} catch (e) {\n  await childChainRun.end({\n    error: `I errored again ${e.message}`,\n  });\n  await childChainRun.patchRun();\n  throw e;\n}\n\nawait childChainRun.patchRun();\n\nawait parentRun.end({\n  outputs: {\n    output: [\"The meeting notes are as follows:...\"],\n  },\n});\n\n// False directs to not exclude child runs\nawait parentRun.patchRun();\n```\n\n## Evaluation\n\n#### Create a Dataset from Existing Runs\n\nOnce your runs are stored in LangSmith, you can convert them into a dataset.\nFor this example, we will do so using the Client, but you can also do this using\nthe web interface, as explained in the [LangSmith docs](https://docs.smith.langchain.com/docs/).\n\n```typescript\nimport { Client } from \"langsmith/client\";\nconst client = new Client({\n  // apiUrl: \"https://api.langchain.com\", // Defaults to the LANGSMITH_ENDPOINT env var\n  // apiKey: \"my_api_key\", // Defaults to the LANGSMITH_API_KEY env var\n  /* callerOptions: {\n         maxConcurrency?: Infinity; // Maximum number of concurrent requests to make\n         maxRetries?: 6; // Maximum number of retries to make\n    */\n});\nconst datasetName = \"Example Dataset\";\n// We will only use examples from the top level AgentExecutor run here,\n// and exclude runs that errored.\nconst runs = await client.listRuns({\n  projectName: \"my_project\",\n  executionOrder: 1,\n  error: false,\n});\n\nconst dataset = await client.createDataset(datasetName, {\n  description: \"An example dataset\",\n});\n\nfor (const run of runs) {\n  await client.createExample(run.inputs, run.outputs ?? {}, {\n    datasetId: dataset.id,\n  });\n}\n```\n\n## Additional Documentation\n\nTo learn more about the LangSmith platform, check out the [docs](https://docs.smith.langchain.com/docs/).\n","publish_time":1780620585957,"_cnpm_publish_time":1780620585957,"dist-tags":{"latest":"0.11.8","next":"0.10.10-rc.1","rc":"0.1.60-rc1","tag-for-publishing-older-releases":"0.1.68"}}