From cb4518131f743c1c3c84793dd7b554b1b135f1f5 Mon Sep 17 00:00:00 2001 From: ericdong-langchain Date: Wed, 25 Mar 2026 16:24:52 -0400 Subject: [PATCH 01/35] Revert "main to next (#108)" (#110) This reverts commit 5a8988d3f6f1e424c49597394c77cbc8a5f41fb7. --- .github/workflows/ci.yml | 4 +- .github/workflows/codeql.yml | 2 +- .github/workflows/count-methods.yml | 58 +++++++++++++++++++ .release-please-manifest.json | 2 +- CHANGELOG.md | 52 ----------------- README.md | 10 ++-- build.gradle.kts | 2 +- .../smith/prompts/PromptClientTest.kt | 7 ++- 8 files changed, 74 insertions(+), 63 deletions(-) create mode 100644 .github/workflows/count-methods.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e37c2e99..fd1492e28 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,7 +34,7 @@ jobs: cache: gradle - name: Set up Gradle - uses: gradle/actions/setup-gradle@v6 + uses: gradle/actions/setup-gradle@v5 - name: Run lints run: ./scripts/lint @@ -61,7 +61,7 @@ jobs: cache: gradle - name: Set up Gradle - uses: gradle/actions/setup-gradle@v6 + uses: gradle/actions/setup-gradle@v5 - name: Build SDK run: ./scripts/build diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index ba587fe4f..fa69f341c 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -28,7 +28,7 @@ jobs: 8 21 - name: Set up Gradle - uses: gradle/actions/setup-gradle@v6 + uses: gradle/actions/setup-gradle@v5 - name: Initialize CodeQL uses: github/codeql-action/init@v4 diff --git a/.github/workflows/count-methods.yml b/.github/workflows/count-methods.yml new file mode 100644 index 000000000..1782d5aef --- /dev/null +++ b/.github/workflows/count-methods.yml @@ -0,0 +1,58 @@ +name: Count number of methods in the SDK +on: + workflow_dispatch: + push: + pull_request: + branches-ignore: + - 'generated' + - 'codegen/**' + - 'integrated/**' + - 'stl-preview-head/**' + - 'stl-preview-base/**' + +jobs: + count-methods: + name: count methods + runs-on: ubuntu-latest + if: github.event_name == 'push' || github.event_name == 'pull_request' + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Read method count from .stats.yml + id: read_method_count + run: | + if [ ! -f .stats.yml ]; then + echo "Error: .stats.yml file not found" + exit 1 + fi + + METHOD_COUNT=$(grep -E '^configured_endpoints:\s*[0-9]+' .stats.yml | awk '{print $2}' || echo "") + + if [ -z "$METHOD_COUNT" ]; then + echo "Error: Could not find configured_endpoints in .stats.yml" + exit 1 + fi + + echo "Method count from .stats.yml: $METHOD_COUNT" + echo "method_count=$METHOD_COUNT" >> $GITHUB_OUTPUT + + - name: Fail if method count exceeds threshold + uses: actions/github-script@v8 + with: + script: | + const methodCount = parseInt('${{ steps.read_method_count.outputs.method_count }}'); + const threshold = 100; + + if (methodCount > threshold) { + core.setFailed( + ` Method count check failed!\n` + + ` Current method count: ${methodCount}\n` + + ` Maximum allowed: ${threshold}\n` + + ` Excess: ${methodCount - threshold} methods\n\n` + + `This check ensures the SDK doesn't exceed the configured endpoint limit.` + ); + } else { + console.log(`Currently at ${methodCount} methods`); + } diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 380b6f913..1c0bb8852 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.1.0-alpha.24" + ".": "0.1.0-alpha.23" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c0df92411..26d640782 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,57 +1,5 @@ # Changelog -## 0.1.0-alpha.24 (2026-03-25) - -Full Changelog: [v0.1.0-alpha.23...v0.1.0-alpha.24](https://github.com/langchain-ai/langsmith-java/compare/v0.1.0-alpha.23...v0.1.0-alpha.24) - -### Features - -* **api:** api update ([8e94d9d](https://github.com/langchain-ai/langsmith-java/commit/8e94d9dc65dfacd3f238e88631623a1338edec2e)) -* **api:** api update ([3288052](https://github.com/langchain-ai/langsmith-java/commit/32880529fe17d465d20ee922894a9e1af3351edd)) -* **api:** api update ([a4e3e5c](https://github.com/langchain-ai/langsmith-java/commit/a4e3e5cb858e66a9409ac162f04660c514cc24df)) -* **api:** api update ([ff16250](https://github.com/langchain-ai/langsmith-java/commit/ff162506f81ad1616567c9119ded36c1a344c774)) -* **api:** api update ([ef7c7a7](https://github.com/langchain-ai/langsmith-java/commit/ef7c7a798786b073e403d994ee2a9367d4db59ee)) -* **api:** api update ([643c7b1](https://github.com/langchain-ai/langsmith-java/commit/643c7b121acd874a72c36e80fbd6d8d4aa772319)) -* **api:** api update ([4b9c97d](https://github.com/langchain-ai/langsmith-java/commit/4b9c97d873492f919885fc1e394d1819fbedd09a)) -* **api:** api update ([ea4e843](https://github.com/langchain-ai/langsmith-java/commit/ea4e843eea1709113fd259659c2cc85fd6317fa5)) -* **api:** api update ([74d2131](https://github.com/langchain-ai/langsmith-java/commit/74d213181b7a2398fa8852235de5a1123ff0a7fe)) -* **api:** api update ([2708533](https://github.com/langchain-ai/langsmith-java/commit/27085335b36f0ecb249a3bd079f96d8d9fad6c1f)) -* **api:** api update ([8f48677](https://github.com/langchain-ai/langsmith-java/commit/8f48677e5ca0dfd9c9e9bc248c204863f233542a)) -* **api:** api update ([c11821f](https://github.com/langchain-ai/langsmith-java/commit/c11821f56ba08939568332468a1e9376c78e6372)) -* **api:** api update ([44fe8b3](https://github.com/langchain-ai/langsmith-java/commit/44fe8b31986af7ae7ac489c0a59335afb8021f9f)) -* **api:** api update ([d11c759](https://github.com/langchain-ai/langsmith-java/commit/d11c759b1cf0d360f07aa0807f554c36f3262b14)) -* **api:** manual updates ([09f1302](https://github.com/langchain-ai/langsmith-java/commit/09f1302329d0fcd9082bc52b2381271aabd71bab)) -* **api:** manual updates ([dbed70a](https://github.com/langchain-ai/langsmith-java/commit/dbed70af760f0e807626650a2a7d6ecb8d30f0ad)) -* **api:** manual updates ([48e2ca2](https://github.com/langchain-ai/langsmith-java/commit/48e2ca294bd412398290777db3ef14655ed47b1c)) -* **api:** manual updates ([d8ac870](https://github.com/langchain-ai/langsmith-java/commit/d8ac87089db42004a53e880f419dcf6749c60817)) -* **api:** manual updates ([bdb35f0](https://github.com/langchain-ai/langsmith-java/commit/bdb35f01f6374860fe6fa3c83f6f102f22590b23)) - - -### Bug Fixes - -* **client:** allow updating header/query affecting fields in `toBuilder()` ([5069881](https://github.com/langchain-ai/langsmith-java/commit/5069881aebcffc8ea2058de667a7af33efc15ec3)) -* **client:** incorrect `Retry-After` parsing ([b607264](https://github.com/langchain-ai/langsmith-java/commit/b607264e2c7e10374f5d79d922c6850208b6f839)) -* fix streaming in java sdk ([#95](https://github.com/langchain-ai/langsmith-java/issues/95)) ([76da93f](https://github.com/langchain-ai/langsmith-java/commit/76da93f2c0c3a0466feee196243a214e8642b303)) - - -### Chores - -* align user agent format ([#96](https://github.com/langchain-ai/langsmith-java/issues/96)) ([5cf06d6](https://github.com/langchain-ai/langsmith-java/commit/5cf06d612963f01b49d6f62117226d948e004046)) -* **ci:** skip lint on metadata-only changes ([4c1197c](https://github.com/langchain-ai/langsmith-java/commit/4c1197ce483f317defed85f81d3ec3f5053f68d3)) -* **ci:** skip uploading artifacts on stainless-internal branches ([c994122](https://github.com/langchain-ai/langsmith-java/commit/c994122d8c4eea78bb8a942b0ed1db58e6338e1e)) -* **deps:** bump the all-actions group with 5 updates ([#92](https://github.com/langchain-ai/langsmith-java/issues/92)) ([3a1a72f](https://github.com/langchain-ai/langsmith-java/commit/3a1a72f5595393a437a8ddf1acc69bb44529b0e8)) -* drop apache dependency ([75ca9d7](https://github.com/langchain-ai/langsmith-java/commit/75ca9d71b49bad02bdbd66141f693204b296a9ec)) -* **internal:** bump ktfmt ([d9a4a39](https://github.com/langchain-ai/langsmith-java/commit/d9a4a396ad92c9f33c5922dabc00a8ba2451199b)) -* **internal:** bump palantir-java-format ([576ebd2](https://github.com/langchain-ai/langsmith-java/commit/576ebd2a02613c632dd1e00ba9c606df99de8f37)) -* **internal:** codegen related update ([29d55b0](https://github.com/langchain-ai/langsmith-java/commit/29d55b0ee9f40c2d327f1c08a714ccd9cad1384b)) -* **internal:** expand imports ([4c7542f](https://github.com/langchain-ai/langsmith-java/commit/4c7542f4525b43d8fc2adcd7d084a080581b5c48)) -* **internal:** tweak CI branches ([b7cecc1](https://github.com/langchain-ai/langsmith-java/commit/b7cecc1caa774426df72acd5734a2c29a96a3e60)) -* **internal:** update gitignore ([d0df3fa](https://github.com/langchain-ai/langsmith-java/commit/d0df3fa13a923514d9d3c66d5d96b4fa1fea4a22)) -* **internal:** update retry delay tests ([a9c7999](https://github.com/langchain-ai/langsmith-java/commit/a9c7999f55bc12c2d1bac268ce3a2ca5bbd58dc5)) -* make `Properties` more resilient to `null` ([47c70f9](https://github.com/langchain-ai/langsmith-java/commit/47c70f91d5ec941fafc08a81baabf946602076c9)) -* remove old test ([#97](https://github.com/langchain-ai/langsmith-java/issues/97)) ([79d708b](https://github.com/langchain-ai/langsmith-java/commit/79d708b935ba234c50d10980a7fef8ad12c58f61)) -* update placeholder string ([be1baa7](https://github.com/langchain-ai/langsmith-java/commit/be1baa704ad8ebe899fbf8e4003f706fbc3d3f73)) - ## 0.1.0-alpha.23 (2026-02-20) Full Changelog: [v0.1.0-alpha.22...v0.1.0-alpha.23](https://github.com/langchain-ai/langsmith-java/compare/v0.1.0-alpha.22...v0.1.0-alpha.23) diff --git a/README.md b/README.md index 27a9835c8..955bc4b0f 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ -[![Maven Central](https://img.shields.io/maven-central/v/com.langchain.smith/langsmith-java)](https://central.sonatype.com/artifact/com.langchain.smith/langsmith-java/0.1.0-alpha.24) -[![javadoc](https://javadoc.io/badge2/com.langchain.smith/langsmith-java/0.1.0-alpha.24/javadoc.svg)](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.24) +[![Maven Central](https://img.shields.io/maven-central/v/com.langchain.smith/langsmith-java)](https://central.sonatype.com/artifact/com.langchain.smith/langsmith-java/0.1.0-alpha.23) +[![javadoc](https://javadoc.io/badge2/com.langchain.smith/langsmith-java/0.1.0-alpha.23/javadoc.svg)](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.23) @@ -13,7 +13,7 @@ To learn more about LangSmith, check out the [docs](https://docs.smith.langchain -The REST API documentation can be found on [docs.smith.langchain.com](https://docs.smith.langchain.com/). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.24). +The REST API documentation can be found on [docs.smith.langchain.com](https://docs.smith.langchain.com/). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.23). @@ -24,7 +24,7 @@ The REST API documentation can be found on [docs.smith.langchain.com](https://do ### Gradle ```kotlin -implementation("com.langchain.smith:langsmith-java:0.1.0-alpha.24") +implementation("com.langchain.smith:langsmith-java:0.1.0-alpha.23") ``` ### Maven @@ -33,7 +33,7 @@ implementation("com.langchain.smith:langsmith-java:0.1.0-alpha.24") com.langchain.smith langsmith-java - 0.1.0-alpha.24 + 0.1.0-alpha.23 ``` diff --git a/build.gradle.kts b/build.gradle.kts index 4c1f4f2c0..579c36df4 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -8,7 +8,7 @@ repositories { allprojects { group = "com.langchain.smith" - version = "0.1.0-alpha.24" // x-release-please-version + version = "0.1.0-alpha.23" // x-release-please-version } subprojects { diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptClientTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptClientTest.kt index 74e2b0f97..023a329b6 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptClientTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptClientTest.kt @@ -8,7 +8,12 @@ import org.junit.jupiter.params.provider.MethodSource internal class PromptClientTest { - data class Case(val identifier: String, val owner: String, val repo: String, val commit: String) + data class Case( + val identifier: String, + val owner: String, + val repo: String, + val commit: String, + ) data class ErrorCase(val identifier: String, val expectedMessage: String) From 30813f8f626a19826d584d0f3b487f5644d2bdb6 Mon Sep 17 00:00:00 2001 From: ericdong-langchain Date: Wed, 25 Mar 2026 16:26:43 -0400 Subject: [PATCH 02/35] Fix/lint and remove method count (#111) * release: 0.1.0-alpha.24 * fix: lint and remove outdated method count ci test Made-with: Cursor --------- Co-authored-by: stainless-app[bot] <142633134+stainless-app[bot]@users.noreply.github.com> --- .github/workflows/count-methods.yml | 58 ------------------- .release-please-manifest.json | 2 +- CHANGELOG.md | 52 +++++++++++++++++ README.md | 10 ++-- build.gradle.kts | 2 +- .../smith/prompts/PromptClientTest.kt | 7 +-- 6 files changed, 60 insertions(+), 71 deletions(-) delete mode 100644 .github/workflows/count-methods.yml diff --git a/.github/workflows/count-methods.yml b/.github/workflows/count-methods.yml deleted file mode 100644 index 1782d5aef..000000000 --- a/.github/workflows/count-methods.yml +++ /dev/null @@ -1,58 +0,0 @@ -name: Count number of methods in the SDK -on: - workflow_dispatch: - push: - pull_request: - branches-ignore: - - 'generated' - - 'codegen/**' - - 'integrated/**' - - 'stl-preview-head/**' - - 'stl-preview-base/**' - -jobs: - count-methods: - name: count methods - runs-on: ubuntu-latest - if: github.event_name == 'push' || github.event_name == 'pull_request' - - steps: - - name: Checkout repository - uses: actions/checkout@v6 - - - name: Read method count from .stats.yml - id: read_method_count - run: | - if [ ! -f .stats.yml ]; then - echo "Error: .stats.yml file not found" - exit 1 - fi - - METHOD_COUNT=$(grep -E '^configured_endpoints:\s*[0-9]+' .stats.yml | awk '{print $2}' || echo "") - - if [ -z "$METHOD_COUNT" ]; then - echo "Error: Could not find configured_endpoints in .stats.yml" - exit 1 - fi - - echo "Method count from .stats.yml: $METHOD_COUNT" - echo "method_count=$METHOD_COUNT" >> $GITHUB_OUTPUT - - - name: Fail if method count exceeds threshold - uses: actions/github-script@v8 - with: - script: | - const methodCount = parseInt('${{ steps.read_method_count.outputs.method_count }}'); - const threshold = 100; - - if (methodCount > threshold) { - core.setFailed( - ` Method count check failed!\n` + - ` Current method count: ${methodCount}\n` + - ` Maximum allowed: ${threshold}\n` + - ` Excess: ${methodCount - threshold} methods\n\n` + - `This check ensures the SDK doesn't exceed the configured endpoint limit.` - ); - } else { - console.log(`Currently at ${methodCount} methods`); - } diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 1c0bb8852..380b6f913 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.1.0-alpha.23" + ".": "0.1.0-alpha.24" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 26d640782..c0df92411 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,57 @@ # Changelog +## 0.1.0-alpha.24 (2026-03-25) + +Full Changelog: [v0.1.0-alpha.23...v0.1.0-alpha.24](https://github.com/langchain-ai/langsmith-java/compare/v0.1.0-alpha.23...v0.1.0-alpha.24) + +### Features + +* **api:** api update ([8e94d9d](https://github.com/langchain-ai/langsmith-java/commit/8e94d9dc65dfacd3f238e88631623a1338edec2e)) +* **api:** api update ([3288052](https://github.com/langchain-ai/langsmith-java/commit/32880529fe17d465d20ee922894a9e1af3351edd)) +* **api:** api update ([a4e3e5c](https://github.com/langchain-ai/langsmith-java/commit/a4e3e5cb858e66a9409ac162f04660c514cc24df)) +* **api:** api update ([ff16250](https://github.com/langchain-ai/langsmith-java/commit/ff162506f81ad1616567c9119ded36c1a344c774)) +* **api:** api update ([ef7c7a7](https://github.com/langchain-ai/langsmith-java/commit/ef7c7a798786b073e403d994ee2a9367d4db59ee)) +* **api:** api update ([643c7b1](https://github.com/langchain-ai/langsmith-java/commit/643c7b121acd874a72c36e80fbd6d8d4aa772319)) +* **api:** api update ([4b9c97d](https://github.com/langchain-ai/langsmith-java/commit/4b9c97d873492f919885fc1e394d1819fbedd09a)) +* **api:** api update ([ea4e843](https://github.com/langchain-ai/langsmith-java/commit/ea4e843eea1709113fd259659c2cc85fd6317fa5)) +* **api:** api update ([74d2131](https://github.com/langchain-ai/langsmith-java/commit/74d213181b7a2398fa8852235de5a1123ff0a7fe)) +* **api:** api update ([2708533](https://github.com/langchain-ai/langsmith-java/commit/27085335b36f0ecb249a3bd079f96d8d9fad6c1f)) +* **api:** api update ([8f48677](https://github.com/langchain-ai/langsmith-java/commit/8f48677e5ca0dfd9c9e9bc248c204863f233542a)) +* **api:** api update ([c11821f](https://github.com/langchain-ai/langsmith-java/commit/c11821f56ba08939568332468a1e9376c78e6372)) +* **api:** api update ([44fe8b3](https://github.com/langchain-ai/langsmith-java/commit/44fe8b31986af7ae7ac489c0a59335afb8021f9f)) +* **api:** api update ([d11c759](https://github.com/langchain-ai/langsmith-java/commit/d11c759b1cf0d360f07aa0807f554c36f3262b14)) +* **api:** manual updates ([09f1302](https://github.com/langchain-ai/langsmith-java/commit/09f1302329d0fcd9082bc52b2381271aabd71bab)) +* **api:** manual updates ([dbed70a](https://github.com/langchain-ai/langsmith-java/commit/dbed70af760f0e807626650a2a7d6ecb8d30f0ad)) +* **api:** manual updates ([48e2ca2](https://github.com/langchain-ai/langsmith-java/commit/48e2ca294bd412398290777db3ef14655ed47b1c)) +* **api:** manual updates ([d8ac870](https://github.com/langchain-ai/langsmith-java/commit/d8ac87089db42004a53e880f419dcf6749c60817)) +* **api:** manual updates ([bdb35f0](https://github.com/langchain-ai/langsmith-java/commit/bdb35f01f6374860fe6fa3c83f6f102f22590b23)) + + +### Bug Fixes + +* **client:** allow updating header/query affecting fields in `toBuilder()` ([5069881](https://github.com/langchain-ai/langsmith-java/commit/5069881aebcffc8ea2058de667a7af33efc15ec3)) +* **client:** incorrect `Retry-After` parsing ([b607264](https://github.com/langchain-ai/langsmith-java/commit/b607264e2c7e10374f5d79d922c6850208b6f839)) +* fix streaming in java sdk ([#95](https://github.com/langchain-ai/langsmith-java/issues/95)) ([76da93f](https://github.com/langchain-ai/langsmith-java/commit/76da93f2c0c3a0466feee196243a214e8642b303)) + + +### Chores + +* align user agent format ([#96](https://github.com/langchain-ai/langsmith-java/issues/96)) ([5cf06d6](https://github.com/langchain-ai/langsmith-java/commit/5cf06d612963f01b49d6f62117226d948e004046)) +* **ci:** skip lint on metadata-only changes ([4c1197c](https://github.com/langchain-ai/langsmith-java/commit/4c1197ce483f317defed85f81d3ec3f5053f68d3)) +* **ci:** skip uploading artifacts on stainless-internal branches ([c994122](https://github.com/langchain-ai/langsmith-java/commit/c994122d8c4eea78bb8a942b0ed1db58e6338e1e)) +* **deps:** bump the all-actions group with 5 updates ([#92](https://github.com/langchain-ai/langsmith-java/issues/92)) ([3a1a72f](https://github.com/langchain-ai/langsmith-java/commit/3a1a72f5595393a437a8ddf1acc69bb44529b0e8)) +* drop apache dependency ([75ca9d7](https://github.com/langchain-ai/langsmith-java/commit/75ca9d71b49bad02bdbd66141f693204b296a9ec)) +* **internal:** bump ktfmt ([d9a4a39](https://github.com/langchain-ai/langsmith-java/commit/d9a4a396ad92c9f33c5922dabc00a8ba2451199b)) +* **internal:** bump palantir-java-format ([576ebd2](https://github.com/langchain-ai/langsmith-java/commit/576ebd2a02613c632dd1e00ba9c606df99de8f37)) +* **internal:** codegen related update ([29d55b0](https://github.com/langchain-ai/langsmith-java/commit/29d55b0ee9f40c2d327f1c08a714ccd9cad1384b)) +* **internal:** expand imports ([4c7542f](https://github.com/langchain-ai/langsmith-java/commit/4c7542f4525b43d8fc2adcd7d084a080581b5c48)) +* **internal:** tweak CI branches ([b7cecc1](https://github.com/langchain-ai/langsmith-java/commit/b7cecc1caa774426df72acd5734a2c29a96a3e60)) +* **internal:** update gitignore ([d0df3fa](https://github.com/langchain-ai/langsmith-java/commit/d0df3fa13a923514d9d3c66d5d96b4fa1fea4a22)) +* **internal:** update retry delay tests ([a9c7999](https://github.com/langchain-ai/langsmith-java/commit/a9c7999f55bc12c2d1bac268ce3a2ca5bbd58dc5)) +* make `Properties` more resilient to `null` ([47c70f9](https://github.com/langchain-ai/langsmith-java/commit/47c70f91d5ec941fafc08a81baabf946602076c9)) +* remove old test ([#97](https://github.com/langchain-ai/langsmith-java/issues/97)) ([79d708b](https://github.com/langchain-ai/langsmith-java/commit/79d708b935ba234c50d10980a7fef8ad12c58f61)) +* update placeholder string ([be1baa7](https://github.com/langchain-ai/langsmith-java/commit/be1baa704ad8ebe899fbf8e4003f706fbc3d3f73)) + ## 0.1.0-alpha.23 (2026-02-20) Full Changelog: [v0.1.0-alpha.22...v0.1.0-alpha.23](https://github.com/langchain-ai/langsmith-java/compare/v0.1.0-alpha.22...v0.1.0-alpha.23) diff --git a/README.md b/README.md index 955bc4b0f..27a9835c8 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ -[![Maven Central](https://img.shields.io/maven-central/v/com.langchain.smith/langsmith-java)](https://central.sonatype.com/artifact/com.langchain.smith/langsmith-java/0.1.0-alpha.23) -[![javadoc](https://javadoc.io/badge2/com.langchain.smith/langsmith-java/0.1.0-alpha.23/javadoc.svg)](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.23) +[![Maven Central](https://img.shields.io/maven-central/v/com.langchain.smith/langsmith-java)](https://central.sonatype.com/artifact/com.langchain.smith/langsmith-java/0.1.0-alpha.24) +[![javadoc](https://javadoc.io/badge2/com.langchain.smith/langsmith-java/0.1.0-alpha.24/javadoc.svg)](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.24) @@ -13,7 +13,7 @@ To learn more about LangSmith, check out the [docs](https://docs.smith.langchain -The REST API documentation can be found on [docs.smith.langchain.com](https://docs.smith.langchain.com/). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.23). +The REST API documentation can be found on [docs.smith.langchain.com](https://docs.smith.langchain.com/). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.24). @@ -24,7 +24,7 @@ The REST API documentation can be found on [docs.smith.langchain.com](https://do ### Gradle ```kotlin -implementation("com.langchain.smith:langsmith-java:0.1.0-alpha.23") +implementation("com.langchain.smith:langsmith-java:0.1.0-alpha.24") ``` ### Maven @@ -33,7 +33,7 @@ implementation("com.langchain.smith:langsmith-java:0.1.0-alpha.23") com.langchain.smith langsmith-java - 0.1.0-alpha.23 + 0.1.0-alpha.24 ``` diff --git a/build.gradle.kts b/build.gradle.kts index 579c36df4..4c1f4f2c0 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -8,7 +8,7 @@ repositories { allprojects { group = "com.langchain.smith" - version = "0.1.0-alpha.23" // x-release-please-version + version = "0.1.0-alpha.24" // x-release-please-version } subprojects { diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptClientTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptClientTest.kt index 023a329b6..74e2b0f97 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptClientTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptClientTest.kt @@ -8,12 +8,7 @@ import org.junit.jupiter.params.provider.MethodSource internal class PromptClientTest { - data class Case( - val identifier: String, - val owner: String, - val repo: String, - val commit: String, - ) + data class Case(val identifier: String, val owner: String, val repo: String, val commit: String) data class ErrorCase(val identifier: String, val expectedMessage: String) From 31cc0037be79a336cd86f6d53c7093f6c3fb7034 Mon Sep 17 00:00:00 2001 From: Jacob Lee Date: Wed, 25 Mar 2026 13:38:16 -0700 Subject: [PATCH 03/35] feat: Adds package version resource to build (#100) * codegen metadata * codegen metadata * chore: make `Properties` more resilient to `null` * chore: drop apache dependency * codegen metadata * codegen metadata * codegen metadata * chore(internal): expand imports * feat(api): manual updates * codegen metadata * feat(api): manual updates * codegen metadata * feat(api): manual updates * codegen metadata * codegen metadata * feat(api): api update * codegen metadata * codegen metadata * feat(api): api update * feat(api): api update * codegen metadata * codegen metadata * codegen metadata * codegen metadata * feat(api): api update * codegen metadata * codegen metadata * codegen metadata * codegen metadata * codegen metadata * codegen metadata * codegen metadata * codegen metadata * feat(api): api update * codegen metadata * feat(api): manual updates removed endpoints not in openAPI spec * codegen metadata * codegen metadata * codegen metadata * chore: align user agent format (#96) * feat(api): api update * codegen metadata * codegen metadata * feat(api): api update * chore(internal): codegen related update * chore(internal): bump palantir-java-format * chore(ci): skip uploading artifacts on stainless-internal branches * chore: update placeholder string * codegen metadata * codegen metadata * codegen metadata * codegen metadata * feat(api): api update * codegen metadata * codegen metadata * fix(client): incorrect `Retry-After` parsing * codegen metadata * codegen metadata * feat(api): api update * feat(api): api update * codegen metadata * codegen metadata * feat(api): api update * codegen metadata * chore(internal): tweak CI branches * codegen metadata * codegen metadata * codegen metadata * codegen metadata * codegen metadata * chore(internal): update retry delay tests * fix(client): allow updating header/query affecting fields in `toBuilder()` * codegen metadata * codegen metadata * feat(api): api update * feat(api): api update * codegen metadata * chore(internal): bump ktfmt * chore: remove old test (#97) * codegen metadata * feat(api): manual updates * codegen metadata * feat(api): api update * codegen metadata * codegen metadata * codegen metadata * chore(internal): update gitignore * codegen metadata * codegen metadata * codegen metadata * chore(ci): skip lint on metadata-only changes Note that we still want to run tests, as these depend on the metadata. * Fix error messages (#102) * codegen metadata * Merge * Merge * Lint * Add debug log * main to next (#108) * codegen metadata * codegen metadata * chore: make `Properties` more resilient to `null` * chore: drop apache dependency * codegen metadata * codegen metadata * codegen metadata * chore(internal): expand imports * feat(api): manual updates * codegen metadata * feat(api): manual updates * codegen metadata * feat(api): manual updates * codegen metadata * codegen metadata * feat(api): api update * codegen metadata * codegen metadata * feat(api): api update * feat(api): api update * codegen metadata * codegen metadata * codegen metadata * codegen metadata * feat(api): api update * codegen metadata * codegen metadata * codegen metadata * codegen metadata * codegen metadata * codegen metadata * codegen metadata * codegen metadata * feat(api): api update * codegen metadata * feat(api): manual updates removed endpoints not in openAPI spec * codegen metadata * codegen metadata * codegen metadata * chore: align user agent format (#96) * feat(api): api update * codegen metadata * codegen metadata * feat(api): api update * chore(internal): codegen related update * chore(internal): bump palantir-java-format * chore(ci): skip uploading artifacts on stainless-internal branches * chore: update placeholder string * codegen metadata * codegen metadata * codegen metadata * codegen metadata * feat(api): api update * codegen metadata * codegen metadata * fix(client): incorrect `Retry-After` parsing * codegen metadata * codegen metadata * feat(api): api update * feat(api): api update * codegen metadata * codegen metadata * feat(api): api update * codegen metadata * chore(internal): tweak CI branches * codegen metadata * codegen metadata * codegen metadata * codegen metadata * codegen metadata * chore(internal): update retry delay tests * fix(client): allow updating header/query affecting fields in `toBuilder()` * codegen metadata * codegen metadata * feat(api): api update * feat(api): api update * codegen metadata * chore(internal): bump ktfmt * chore: remove old test (#97) * codegen metadata * feat(api): manual updates * codegen metadata * feat(api): api update * codegen metadata * codegen metadata * codegen metadata * chore(internal): update gitignore * codegen metadata * codegen metadata * codegen metadata * chore(ci): skip lint on metadata-only changes Note that we still want to run tests, as these depend on the metadata. * Fix error messages (#102) * codegen metadata * release: 0.1.0-alpha.24 * fix: lint and remove outdated method count ci test (#103) Made-with: Cursor * chore(deps): bump gradle/actions from 5 to 6 in the all-actions group (#99) Bumps the all-actions group with 1 update: [gradle/actions](https://github.com/gradle/actions). Updates `gradle/actions` from 5 to 6 - [Release notes](https://github.com/gradle/actions/releases) - [Commits](https://github.com/gradle/actions/compare/v5...v6) --- updated-dependencies: - dependency-name: gradle/actions dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major dependency-group: all-actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --------- Signed-off-by: dependabot[bot] Co-authored-by: stainless-app[bot] <142633134+stainless-app[bot]@users.noreply.github.com> Co-authored-by: Jacob Lee Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Change to warning and add a test --------- Signed-off-by: dependabot[bot] Co-authored-by: stainless-app[bot] <142633134+stainless-app[bot]@users.noreply.github.com> Co-authored-by: ericdong-langchain Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 4 +- .github/workflows/codeql.yml | 2 +- .gitignore | 2 + langsmith-java-core/build.gradle.kts | 20 ++++++++- .../com/langchain/smith/core/Properties.kt | 23 +++++++++- .../langchain/smith/core/PropertiesTest.kt | 42 +++++++++++++++++++ 6 files changed, 86 insertions(+), 7 deletions(-) create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/core/PropertiesTest.kt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fd1492e28..7e37c2e99 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,7 +34,7 @@ jobs: cache: gradle - name: Set up Gradle - uses: gradle/actions/setup-gradle@v5 + uses: gradle/actions/setup-gradle@v6 - name: Run lints run: ./scripts/lint @@ -61,7 +61,7 @@ jobs: cache: gradle - name: Set up Gradle - uses: gradle/actions/setup-gradle@v5 + uses: gradle/actions/setup-gradle@v6 - name: Build SDK run: ./scripts/build diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index fa69f341c..ba587fe4f 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -28,7 +28,7 @@ jobs: 8 21 - name: Set up Gradle - uses: gradle/actions/setup-gradle@v5 + uses: gradle/actions/setup-gradle@v6 - name: Initialize CodeQL uses: github/codeql-action/init@v4 diff --git a/.gitignore b/.gitignore index 90b85e944..c45496803 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ .gradle .idea .kotlin +**/bin/main/ +**/bin/test/ build/ codegen.log kls_database.db diff --git a/langsmith-java-core/build.gradle.kts b/langsmith-java-core/build.gradle.kts index 777d7a9c6..878625786 100644 --- a/langsmith-java-core/build.gradle.kts +++ b/langsmith-java-core/build.gradle.kts @@ -3,6 +3,22 @@ plugins { id("langchain.publish") } +val generateVersionProperties by tasks.registering { + val outputDir = layout.buildDirectory.dir("generated/resources/version") + val projectVersion = provider { project.version.toString() } + outputs.dir(outputDir) + inputs.property("version", projectVersion) + doLast { + val dir = outputDir.get().asFile.resolve("com/langchain/smith") + dir.mkdirs() + dir.resolve("version.properties").writeText("version=${projectVersion.get()}\n") + } +} + +sourceSets.main { + resources.srcDir(generateVersionProperties) +} + configurations.all { resolutionStrategy { // Compile and test against a lower Jackson version to ensure we're compatible with it. Note that @@ -29,13 +45,13 @@ dependencies { implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.18.2") implementation("org.apache.httpcomponents.core5:httpcore5:5.2.4") implementation("org.apache.httpcomponents.client5:httpclient5:5.3.1") - + // OpenTelemetry dependencies api("io.opentelemetry:opentelemetry-api:1.32.0") api("io.opentelemetry:opentelemetry-sdk:1.32.0") api("io.opentelemetry:opentelemetry-exporter-otlp:1.32.0") api("io.opentelemetry.semconv:opentelemetry-semconv:1.23.1-alpha") - + // OpenAI SDK (for OpenTelemetry wrappers) api("com.openai:openai-java:4.6.1") diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/core/Properties.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/core/Properties.kt index c18124cfb..67fb8c4f2 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/core/Properties.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/core/Properties.kt @@ -3,6 +3,9 @@ package com.langchain.smith.core import com.langchain.smith.client.LangsmithClient +import org.slf4j.LoggerFactory + +private val logger = LoggerFactory.getLogger("com.langchain.smith.core.Properties") fun getOsArch(): String { val osArch = System.getProperty("os.arch") @@ -12,8 +15,10 @@ fun getOsArch(): String { "i386", "x32", "x86" -> "x32" + "amd64", "x86_64" -> "x64" + "arm" -> "arm" "aarch64" -> "arm64" else -> "other:$osArch" @@ -36,7 +41,21 @@ fun getOsName(): String { fun getOsVersion(): String = System.getProperty("os.version", "unknown") ?: "unknown" -fun getPackageVersion(): String = - LangsmithClient::class.java.`package`?.implementationVersion ?: "unknown" +fun getPackageVersion(): String { + try { + val props = java.util.Properties() + LangsmithClient::class + .java + .classLoader + .getResourceAsStream("com/langchain/smith/version.properties") + ?.use { props.load(it) } + props.getProperty("version")?.let { + return it + } + } catch (e: Exception) { + logger.warn("Failed to read version from version.properties", e) + } + return LangsmithClient::class.java.`package`.implementationVersion ?: "unknown" +} fun getJavaVersion(): String = System.getProperty("java.version", "unknown") ?: "unknown" diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/core/PropertiesTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/core/PropertiesTest.kt new file mode 100644 index 000000000..8769c4ce0 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/core/PropertiesTest.kt @@ -0,0 +1,42 @@ +package com.langchain.smith.core + +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class PropertiesTest { + + @Test + fun getPackageVersion_returnsNonBlankValue() { + val version = getPackageVersion() + + assertThat(version).isNotBlank() + } + + @Test + fun getOsArch_returnsNonBlankValue() { + val osArch = getOsArch() + + assertThat(osArch).isNotBlank() + } + + @Test + fun getOsName_returnsNonBlankValue() { + val osName = getOsName() + + assertThat(osName).isNotBlank() + } + + @Test + fun getOsVersion_returnsNonBlankValue() { + val osVersion = getOsVersion() + + assertThat(osVersion).isNotBlank() + } + + @Test + fun getJavaVersion_returnsNonBlankValue() { + val javaVersion = getJavaVersion() + + assertThat(javaVersion).isNotBlank() + } +} From 5f83650d3211e3dcbdcd6a59a99ef744eb8fab71 Mon Sep 17 00:00:00 2001 From: Jacob Lee Date: Wed, 25 Mar 2026 13:52:07 -0700 Subject: [PATCH 04/35] Adds contributing guide (#112) --- CONTRIBUTING.md | 122 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..a9d19c04d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,122 @@ +# Contributing + +Thanks for your interest in contributing to the LangSmith Java SDK! + +## Overview + +This SDK is **auto-generated by [Stainless](https://www.stainless.com/)** from our OpenAPI spec. Custom code (prompts, OTel wrappers, etc.) lives alongside generated code — Stainless is configured to [preserve custom code](https://www.stainless.com/docs/sdks/configure/custom-code/) and never overwrite it. + +> **Important:** Most files in the SDK are generated. If you need to change generated code, talk to @edongashi — there may be weird errors in the Stainless config, but they're generally fixable. + +## Branching and workflow + +| Branch | Purpose | +| ----------------------------------------------- | ----------------------------------------------------- | +| `next` | **Development branch.** All PRs should target `next`. | +| `main` | Release branch. Only updated via release-please. | +| `release-please--branches--main--changes--next` | Auto-generated release PR. Merges `next` → `main`. | + +**Always work off `next`.** Do not merge directly to `main` — Dependabot or other bots occasionally violate this, which can cause headaches. + +### Release process + +1. Merge your PR into `next`. +2. A release-please PR is automatically created/updated (`release-please--branches--main--changes--next`). +3. Verify your change appears in the release PR diff and description. +4. Approve the release PR — it auto-merges on approval. +5. A GitHub Action publishes to Maven Central via `./gradlew publishAndReleaseToMavenCentral`. +6. Maven Central can be slow to index — verify on [repo1.maven.org](https://repo1.maven.org/maven2/com/langchain/smith/langsmith-java/) rather than [mvnrepository.com](https://mvnrepository.com/artifact/com.langchain.smith/langsmith-java), which lags behind. + +> **Note:** If lint fixes or other changes are pushed to the release-please branch after a version bump, the publish action can fail. Always ensure CI is green before approving. + +## Development setup + +### Prerequisites + +- Java 8+ (tested against 8 and 21) +- Gradle (uses the included `gradlew` wrapper) + +### Building + +```bash +./scripts/build +``` + +### Formatting + +The project uses [ktfmt](https://github.com/facebook/ktfmt) (`--kotlinlang-style`) for Kotlin and [Palantir Java Format](https://github.com/palantir/palantir-java-format) for Java. + +```bash +# Format all files +./scripts/format + +# Format only Kotlin +./gradlew formatKotlin + +# Format a single module +./gradlew :langsmith-java-core:formatKotlin +``` + +### Linting + +```bash +# Lint all files +./scripts/lint + +# Lint only Kotlin +./gradlew lintKotlin +``` + +CI blocks on lint failures. Always run `./scripts/format` before pushing. + +### Testing + +```bash +# Run all tests +./scripts/test + +# Run specific tests +./gradlew :langsmith-java-core:test --tests "com.langchain.smith.prompts.*" + +# Force re-run (skip Gradle cache) +./gradlew :langsmith-java-core:test --tests "..." --rerun + +# See stdout output +./gradlew :langsmith-java-core:test --tests "..." --rerun --info +``` + +#### Integration tests + +Integration tests require API keys and skip gracefully via `assumeTrue` if they're missing: + +```bash +export LANGSMITH_API_KEY="lsv2_pt_..." +export OPENAI_API_KEY="sk-..." +export ANTHROPIC_API_KEY="sk-ant-..." +``` + +## CI + +CI runs three jobs on every push and PR: + +1. **lint** — `./scripts/lint` +2. **build** — `./scripts/build` +3. **test** — `./scripts/test` + +All three must pass before merging. + +## Code style + +See [AGENTS.md](AGENTS.md) for detailed Kotlin conventions, including: + +- Prefer `buildMap`/`buildList` over mutable collections +- Use `partition` instead of double `filter` +- Use parameterized tests for table-driven cases +- Avoid `@Suppress("UNCHECKED_CAST")` — restructure with safe casts +- `toString()` should follow the `ClassName{field=value}` convention + +## Dependencies + +- **Anthropic SDK** is a `compileOnly` dependency — users must add it themselves. Methods using Anthropic types should catch `NoClassDefFoundError` and throw `IllegalStateException` with a clear message. +- **SLF4J** (`slf4j-api`) is an `api` dependency for logging. Tests use `slf4j-simple`. +- **Jackson** 2.18.2 is the default, but the SDK is compatible with 2.13.4+. Tests compile against 2.14.0. From 11834690d9c27aa93cbf311526174c059db559ad Mon Sep 17 00:00:00 2001 From: John Kennedy <65985482+jkennedyvz@users.noreply.github.com> Date: Wed, 25 Mar 2026 15:59:50 -0700 Subject: [PATCH 05/35] ci: add minimum workflow permissions (#106) - Add top-level `permissions: contents: read` to all 4 workflow files - Change release-doctor.yml trigger from `pull_request` to `pull_request_target` to prevent secret exfiltration via PR-controlled workflow modifications Co-authored-by: Posture Fix --- .github/workflows/ci.yml | 3 +++ .github/workflows/codeql.yml | 4 ++++ .github/workflows/publish-sonatype.yml | 3 +++ .github/workflows/release-doctor.yml | 5 ++++- 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e37c2e99..4e78ca506 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,6 +14,9 @@ on: - 'stl-preview-head/**' - 'stl-preview-base/**' +permissions: + contents: read + jobs: lint: timeout-minutes: 15 diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index ba587fe4f..2de5f5be9 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -7,6 +7,10 @@ on: branches: [main, next] schedule: - cron: "0 0 * * 0" # Weekly scan on Sunday at midnight + +permissions: + contents: read + jobs: analyze: name: Analyze diff --git a/.github/workflows/publish-sonatype.yml b/.github/workflows/publish-sonatype.yml index 609bb6dd0..97f073d2e 100644 --- a/.github/workflows/publish-sonatype.yml +++ b/.github/workflows/publish-sonatype.yml @@ -8,6 +8,9 @@ on: release: types: [published] +permissions: + contents: read + jobs: publish: name: publish diff --git a/.github/workflows/release-doctor.yml b/.github/workflows/release-doctor.yml index edf2435b9..2a2c3baee 100644 --- a/.github/workflows/release-doctor.yml +++ b/.github/workflows/release-doctor.yml @@ -1,10 +1,13 @@ name: Release Doctor on: - pull_request: + pull_request_target: branches: - main workflow_dispatch: +permissions: + contents: read + jobs: release_doctor: name: release doctor From 50075e56409a4061cd6f4503f0d384f6b3e4f6ec Mon Sep 17 00:00:00 2001 From: John Kennedy <65985482+jkennedyvz@users.noreply.github.com> Date: Wed, 25 Mar 2026 16:00:21 -0700 Subject: [PATCH 06/35] ci: SHA-pin third-party Gradle actions (#107) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pin gradle/actions/setup-gradle and gradle/gradle-build-action to full commit SHAs to prevent supply chain attacks via tag hijacking. - gradle/actions/setup-gradle@v6 → @205054a... (ci.yml ×2, codeql.yml) - gradle/gradle-build-action@v3 → @12318b0... (ci.yml, publish-sonatype.yml) Co-authored-by: Posture Fix --- .github/workflows/ci.yml | 6 +++--- .github/workflows/codeql.yml | 2 +- .github/workflows/publish-sonatype.yml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4e78ca506..6e3760469 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,7 +37,7 @@ jobs: cache: gradle - name: Set up Gradle - uses: gradle/actions/setup-gradle@v6 + uses: gradle/actions/setup-gradle@205054a7257716ec64af10a2e2ff1ac5d3b132db # v6 - name: Run lints run: ./scripts/lint @@ -64,7 +64,7 @@ jobs: cache: gradle - name: Set up Gradle - uses: gradle/actions/setup-gradle@v6 + uses: gradle/actions/setup-gradle@205054a7257716ec64af10a2e2ff1ac5d3b132db # v6 - name: Build SDK run: ./scripts/build @@ -106,7 +106,7 @@ jobs: cache: gradle - name: Set up Gradle - uses: gradle/gradle-build-action@v3 + uses: gradle/gradle-build-action@12318b01111bfa6462c00534ffa998f8b397b979 # v3 - name: Run tests run: ./scripts/test diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 2de5f5be9..600cfd1ed 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -32,7 +32,7 @@ jobs: 8 21 - name: Set up Gradle - uses: gradle/actions/setup-gradle@v6 + uses: gradle/actions/setup-gradle@205054a7257716ec64af10a2e2ff1ac5d3b132db # v6 - name: Initialize CodeQL uses: github/codeql-action/init@v4 diff --git a/.github/workflows/publish-sonatype.yml b/.github/workflows/publish-sonatype.yml index 97f073d2e..4cbff3226 100644 --- a/.github/workflows/publish-sonatype.yml +++ b/.github/workflows/publish-sonatype.yml @@ -29,7 +29,7 @@ jobs: cache: gradle - name: Set up Gradle - uses: gradle/gradle-build-action@v3 + uses: gradle/gradle-build-action@12318b01111bfa6462c00534ffa998f8b397b979 # v3 - name: Publish to Sonatype run: |- From a0e544170d0c62e340a6250c32b6b521f818eaa4 Mon Sep 17 00:00:00 2001 From: John Kennedy <65985482+jkennedyvz@users.noreply.github.com> Date: Wed, 25 Mar 2026 16:00:42 -0700 Subject: [PATCH 07/35] chore: fix dependabot.yml posture issues (#105) * chore: update dependabot.yml to comply with posture checks - Change schedule from weekly to monthly for all ecosystems - Add update-types split (major vs minor-and-patch) for gradle and github-actions - Add docker ecosystem entry for .devcontainer/Dockerfile * chore: add target-branch next and fix docker group split for Stainless posture compliance --------- Co-authored-by: Posture Fix --- .github/dependabot.yml | 45 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 7e85bed44..a51eccc7f 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -2,20 +2,57 @@ version: 2 updates: - package-ecosystem: gradle directory: / + target-branch: "next" schedule: - interval: weekly + interval: monthly groups: - all-dependencies: + minor-and-patch: patterns: - "*" + update-types: + - minor + - patch + major: + patterns: + - "*" + update-types: + - major + open-pull-requests-limit: 5 + + - package-ecosystem: docker + directory: /.devcontainer + target-branch: "next" + schedule: + interval: monthly + groups: + minor-and-patch: + patterns: + - "*" + update-types: + - minor + - patch + major: + patterns: + - "*" + update-types: + - major open-pull-requests-limit: 5 - package-ecosystem: github-actions directory: / + target-branch: "next" schedule: - interval: weekly + interval: monthly groups: - all-actions: + minor-and-patch: + patterns: + - "*" + update-types: + - minor + - patch + major: patterns: - "*" + update-types: + - major open-pull-requests-limit: 5 From af93e09dc9dd8597454b2a02b1ed37de4e71fde4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 26 Mar 2026 13:13:44 +0000 Subject: [PATCH 08/35] feat(api): api update --- .stats.yml | 4 +- .../annotationqueues/runs/RunCreateParams.kt | 42 ++++++++++++++++--- 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/.stats.yml b/.stats.yml index 3503c6f83..dabb736ea 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-9b1a87757cd49a12277fb568ad9a86554c1b46ac115f0ca43fd19e8d8025286d.yml -openapi_spec_hash: 76801a4fc381af1c3435db9504a2b382 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-e618b926237d170177f03ab5d24ee6dc0b1557be81d2ea8d1967a3cc041f739b.yml +openapi_spec_hash: ae6d82f6dea4693e9951ab684049ab4e config_hash: 787a12876983a14bce67ed57899e4a94 diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/runs/RunCreateParams.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/runs/RunCreateParams.kt index a7e4fadd9..2d58bec5e 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/runs/RunCreateParams.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/runs/RunCreateParams.kt @@ -432,7 +432,7 @@ private constructor( } } - /** Schema for adding a run to an annotation queue with optional metadata. */ + /** Deprecated: use plain UUID list or AddRunToQueueByKeyRequest instead. */ class AnnotationQueueRunAddSchema @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( @@ -470,36 +470,41 @@ private constructor( * unexpectedly missing or null (e.g. if the server responded with an unexpected * value). */ - fun runId(): String = runId.getRequired("run_id") + @Deprecated("deprecated") fun runId(): String = runId.getRequired("run_id") /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ + @Deprecated("deprecated") fun parentRunId(): Optional = parentRunId.getOptional("parent_run_id") /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ + @Deprecated("deprecated") fun sessionId(): Optional = sessionId.getOptional("session_id") /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ + @Deprecated("deprecated") fun startTime(): Optional = startTime.getOptional("start_time") /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ + @Deprecated("deprecated") fun traceId(): Optional = traceId.getOptional("trace_id") /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. * if the server responded with an unexpected value). */ + @Deprecated("deprecated") fun traceTier(): Optional = traceTier.getOptional("trace_tier") /** @@ -507,7 +512,10 @@ private constructor( * * Unlike [runId], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("run_id") @ExcludeMissing fun _runId(): JsonField = runId + @Deprecated("deprecated") + @JsonProperty("run_id") + @ExcludeMissing + fun _runId(): JsonField = runId /** * Returns the raw JSON value of [parentRunId]. @@ -515,6 +523,7 @@ private constructor( * Unlike [parentRunId], this method doesn't throw if the JSON field has an unexpected * type. */ + @Deprecated("deprecated") @JsonProperty("parent_run_id") @ExcludeMissing fun _parentRunId(): JsonField = parentRunId @@ -525,6 +534,7 @@ private constructor( * Unlike [sessionId], this method doesn't throw if the JSON field has an unexpected * type. */ + @Deprecated("deprecated") @JsonProperty("session_id") @ExcludeMissing fun _sessionId(): JsonField = sessionId @@ -535,6 +545,7 @@ private constructor( * Unlike [startTime], this method doesn't throw if the JSON field has an unexpected * type. */ + @Deprecated("deprecated") @JsonProperty("start_time") @ExcludeMissing fun _startTime(): JsonField = startTime @@ -544,7 +555,10 @@ private constructor( * * Unlike [traceId], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("trace_id") @ExcludeMissing fun _traceId(): JsonField = traceId + @Deprecated("deprecated") + @JsonProperty("trace_id") + @ExcludeMissing + fun _traceId(): JsonField = traceId /** * Returns the raw JSON value of [traceTier]. @@ -552,6 +566,7 @@ private constructor( * Unlike [traceTier], this method doesn't throw if the JSON field has an unexpected * type. */ + @Deprecated("deprecated") @JsonProperty("trace_tier") @ExcludeMissing fun _traceTier(): JsonField = traceTier @@ -606,7 +621,7 @@ private constructor( annotationQueueRunAddSchema.additionalProperties.toMutableMap() } - fun runId(runId: String) = runId(JsonField.of(runId)) + @Deprecated("deprecated") fun runId(runId: String) = runId(JsonField.of(runId)) /** * Sets [Builder.runId] to an arbitrary JSON value. @@ -615,12 +630,15 @@ private constructor( * This method is primarily for setting the field to an undocumented or not yet * supported value. */ + @Deprecated("deprecated") fun runId(runId: JsonField) = apply { this.runId = runId } + @Deprecated("deprecated") fun parentRunId(parentRunId: String?) = parentRunId(JsonField.ofNullable(parentRunId)) /** Alias for calling [Builder.parentRunId] with `parentRunId.orElse(null)`. */ + @Deprecated("deprecated") fun parentRunId(parentRunId: Optional) = parentRunId(parentRunId.getOrNull()) @@ -631,13 +649,16 @@ private constructor( * instead. This method is primarily for setting the field to an undocumented or not * yet supported value. */ + @Deprecated("deprecated") fun parentRunId(parentRunId: JsonField) = apply { this.parentRunId = parentRunId } + @Deprecated("deprecated") fun sessionId(sessionId: String?) = sessionId(JsonField.ofNullable(sessionId)) /** Alias for calling [Builder.sessionId] with `sessionId.orElse(null)`. */ + @Deprecated("deprecated") fun sessionId(sessionId: Optional) = sessionId(sessionId.getOrNull()) /** @@ -647,12 +668,15 @@ private constructor( * instead. This method is primarily for setting the field to an undocumented or not * yet supported value. */ + @Deprecated("deprecated") fun sessionId(sessionId: JsonField) = apply { this.sessionId = sessionId } + @Deprecated("deprecated") fun startTime(startTime: OffsetDateTime?) = startTime(JsonField.ofNullable(startTime)) /** Alias for calling [Builder.startTime] with `startTime.orElse(null)`. */ + @Deprecated("deprecated") fun startTime(startTime: Optional) = startTime(startTime.getOrNull()) @@ -663,13 +687,16 @@ private constructor( * value instead. This method is primarily for setting the field to an undocumented * or not yet supported value. */ + @Deprecated("deprecated") fun startTime(startTime: JsonField) = apply { this.startTime = startTime } + @Deprecated("deprecated") fun traceId(traceId: String?) = traceId(JsonField.ofNullable(traceId)) /** Alias for calling [Builder.traceId] with `traceId.orElse(null)`. */ + @Deprecated("deprecated") fun traceId(traceId: Optional) = traceId(traceId.getOrNull()) /** @@ -679,11 +706,14 @@ private constructor( * instead. This method is primarily for setting the field to an undocumented or not * yet supported value. */ + @Deprecated("deprecated") fun traceId(traceId: JsonField) = apply { this.traceId = traceId } + @Deprecated("deprecated") fun traceTier(traceTier: TraceTier?) = traceTier(JsonField.ofNullable(traceTier)) /** Alias for calling [Builder.traceTier] with `traceTier.orElse(null)`. */ + @Deprecated("deprecated") fun traceTier(traceTier: Optional) = traceTier(traceTier.getOrNull()) /** @@ -693,6 +723,7 @@ private constructor( * instead. This method is primarily for setting the field to an undocumented or not * yet supported value. */ + @Deprecated("deprecated") fun traceTier(traceTier: JsonField) = apply { this.traceTier = traceTier } @@ -782,6 +813,7 @@ private constructor( (if (traceId.asKnown().isPresent) 1 else 0) + (traceTier.asKnown().getOrNull()?.validity() ?: 0) + @Deprecated("deprecated") class TraceTier @JsonCreator private constructor(private val value: JsonField) : Enum { From cd9f555e525172d5ba0bcb0cd033dc045a9026bd Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 26 Mar 2026 19:13:47 +0000 Subject: [PATCH 09/35] feat(api): api update --- .stats.yml | 4 +-- .../models/commits/CommitRetrieveParams.kt | 20 ++++++++++- .../models/commits/CommitRetrieveResponse.kt | 36 +++++++++++++++++-- .../commits/CommitRetrieveParamsTest.kt | 3 ++ .../commits/CommitRetrieveResponseTest.kt | 3 ++ .../services/async/CommitServiceAsyncTest.kt | 1 + .../services/blocking/CommitServiceTest.kt | 1 + 7 files changed, 63 insertions(+), 5 deletions(-) diff --git a/.stats.yml b/.stats.yml index dabb736ea..c0fb79a90 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-e618b926237d170177f03ab5d24ee6dc0b1557be81d2ea8d1967a3cc041f739b.yml -openapi_spec_hash: ae6d82f6dea4693e9951ab684049ab4e +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-d4b2278e9baa17ef476065b3b53a2012bcfd257915aa38991d2ecdfab1595766.yml +openapi_spec_hash: 90898c9254e266bfde382341368d3793 config_hash: 787a12876983a14bce67ed57899e4a94 diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveParams.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveParams.kt index 23a930f1c..41ad01680 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveParams.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveParams.kt @@ -24,6 +24,7 @@ private constructor( private val repo: String, private val commit: String?, private val getExamples: Boolean?, + private val include: String?, private val includeModel: Boolean?, private val isView: Boolean?, private val additionalHeaders: Headers, @@ -38,6 +39,10 @@ private constructor( fun getExamples(): Optional = Optional.ofNullable(getExamples) + /** Comma-separated list of optional fields: "model", "is_draft" */ + fun include(): Optional = Optional.ofNullable(include) + + /** Deprecated: use Include instead */ fun includeModel(): Optional = Optional.ofNullable(includeModel) fun isView(): Optional = Optional.ofNullable(isView) @@ -71,6 +76,7 @@ private constructor( private var repo: String? = null private var commit: String? = null private var getExamples: Boolean? = null + private var include: String? = null private var includeModel: Boolean? = null private var isView: Boolean? = null private var additionalHeaders: Headers.Builder = Headers.builder() @@ -82,6 +88,7 @@ private constructor( repo = commitRetrieveParams.repo commit = commitRetrieveParams.commit getExamples = commitRetrieveParams.getExamples + include = commitRetrieveParams.include includeModel = commitRetrieveParams.includeModel isView = commitRetrieveParams.isView additionalHeaders = commitRetrieveParams.additionalHeaders.toBuilder() @@ -109,6 +116,13 @@ private constructor( /** Alias for calling [Builder.getExamples] with `getExamples.orElse(null)`. */ fun getExamples(getExamples: Optional) = getExamples(getExamples.getOrNull()) + /** Comma-separated list of optional fields: "model", "is_draft" */ + fun include(include: String?) = apply { this.include = include } + + /** Alias for calling [Builder.include] with `include.orElse(null)`. */ + fun include(include: Optional) = include(include.getOrNull()) + + /** Deprecated: use Include instead */ fun includeModel(includeModel: Boolean?) = apply { this.includeModel = includeModel } /** @@ -250,6 +264,7 @@ private constructor( checkRequired("repo", repo), commit, getExamples, + include, includeModel, isView, additionalHeaders.build(), @@ -271,6 +286,7 @@ private constructor( QueryParams.builder() .apply { getExamples?.let { put("get_examples", it.toString()) } + include?.let { put("include", it) } includeModel?.let { put("include_model", it.toString()) } isView?.let { put("is_view", it.toString()) } putAll(additionalQueryParams) @@ -287,6 +303,7 @@ private constructor( repo == other.repo && commit == other.commit && getExamples == other.getExamples && + include == other.include && includeModel == other.includeModel && isView == other.isView && additionalHeaders == other.additionalHeaders && @@ -299,6 +316,7 @@ private constructor( repo, commit, getExamples, + include, includeModel, isView, additionalHeaders, @@ -306,5 +324,5 @@ private constructor( ) override fun toString() = - "CommitRetrieveParams{owner=$owner, repo=$repo, commit=$commit, getExamples=$getExamples, includeModel=$includeModel, isView=$isView, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" + "CommitRetrieveParams{owner=$owner, repo=$repo, commit=$commit, getExamples=$getExamples, include=$include, includeModel=$includeModel, isView=$isView, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" } diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponse.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponse.kt index 6a622a7da..e2fe4eb7b 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponse.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponse.kt @@ -23,6 +23,7 @@ class CommitRetrieveResponse private constructor( private val commitHash: JsonField, private val examples: JsonField>, + private val isDraft: JsonField, private val manifest: JsonValue, private val modelConfig: JsonValue, private val modelProvider: JsonField, @@ -37,12 +38,13 @@ private constructor( @JsonProperty("examples") @ExcludeMissing examples: JsonField> = JsonMissing.of(), + @JsonProperty("is_draft") @ExcludeMissing isDraft: JsonField = JsonMissing.of(), @JsonProperty("manifest") @ExcludeMissing manifest: JsonValue = JsonMissing.of(), @JsonProperty("model_config") @ExcludeMissing modelConfig: JsonValue = JsonMissing.of(), @JsonProperty("model_provider") @ExcludeMissing modelProvider: JsonField = JsonMissing.of(), - ) : this(commitHash, examples, manifest, modelConfig, modelProvider, mutableMapOf()) + ) : this(commitHash, examples, isDraft, manifest, modelConfig, modelProvider, mutableMapOf()) /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -56,6 +58,12 @@ private constructor( */ fun examples(): Optional> = examples.getOptional("examples") + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun isDraft(): Optional = isDraft.getOptional("is_draft") + /** * This arbitrary value can be deserialized into a custom type using the `convert` method: * ```java @@ -92,6 +100,13 @@ private constructor( */ @JsonProperty("examples") @ExcludeMissing fun _examples(): JsonField> = examples + /** + * Returns the raw JSON value of [isDraft]. + * + * Unlike [isDraft], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("is_draft") @ExcludeMissing fun _isDraft(): JsonField = isDraft + /** * Returns the raw JSON value of [modelProvider]. * @@ -124,6 +139,7 @@ private constructor( private var commitHash: JsonField = JsonMissing.of() private var examples: JsonField>? = null + private var isDraft: JsonField = JsonMissing.of() private var manifest: JsonValue = JsonMissing.of() private var modelConfig: JsonValue = JsonMissing.of() private var modelProvider: JsonField = JsonMissing.of() @@ -133,6 +149,7 @@ private constructor( internal fun from(commitRetrieveResponse: CommitRetrieveResponse) = apply { commitHash = commitRetrieveResponse.commitHash examples = commitRetrieveResponse.examples.map { it.toMutableList() } + isDraft = commitRetrieveResponse.isDraft manifest = commitRetrieveResponse.manifest modelConfig = commitRetrieveResponse.modelConfig modelProvider = commitRetrieveResponse.modelProvider @@ -175,6 +192,16 @@ private constructor( } } + fun isDraft(isDraft: Boolean) = isDraft(JsonField.of(isDraft)) + + /** + * Sets [Builder.isDraft] to an arbitrary JSON value. + * + * You should usually call [Builder.isDraft] with a well-typed [Boolean] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun isDraft(isDraft: JsonField) = apply { this.isDraft = isDraft } + fun manifest(manifest: JsonValue) = apply { this.manifest = manifest } fun modelConfig(modelConfig: JsonValue) = apply { this.modelConfig = modelConfig } @@ -220,6 +247,7 @@ private constructor( CommitRetrieveResponse( commitHash, (examples ?: JsonMissing.of()).map { it.toImmutable() }, + isDraft, manifest, modelConfig, modelProvider, @@ -236,6 +264,7 @@ private constructor( commitHash() examples().ifPresent { it.forEach { it.validate() } } + isDraft() modelProvider() validated = true } @@ -257,6 +286,7 @@ private constructor( internal fun validity(): Int = (if (commitHash.asKnown().isPresent) 1 else 0) + (examples.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + (if (isDraft.asKnown().isPresent) 1 else 0) + (if (modelProvider.asKnown().isPresent) 1 else 0) class Example @@ -513,6 +543,7 @@ private constructor( return other is CommitRetrieveResponse && commitHash == other.commitHash && examples == other.examples && + isDraft == other.isDraft && manifest == other.manifest && modelConfig == other.modelConfig && modelProvider == other.modelProvider && @@ -523,6 +554,7 @@ private constructor( Objects.hash( commitHash, examples, + isDraft, manifest, modelConfig, modelProvider, @@ -533,5 +565,5 @@ private constructor( override fun hashCode(): Int = hashCode override fun toString() = - "CommitRetrieveResponse{commitHash=$commitHash, examples=$examples, manifest=$manifest, modelConfig=$modelConfig, modelProvider=$modelProvider, additionalProperties=$additionalProperties}" + "CommitRetrieveResponse{commitHash=$commitHash, examples=$examples, isDraft=$isDraft, manifest=$manifest, modelConfig=$modelConfig, modelProvider=$modelProvider, additionalProperties=$additionalProperties}" } diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveParamsTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveParamsTest.kt index 5936508aa..44c1a7d1e 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveParamsTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveParamsTest.kt @@ -15,6 +15,7 @@ internal class CommitRetrieveParamsTest { .repo("repo") .commit("commit") .getExamples(true) + .include("include") .includeModel(true) .isView(true) .build() @@ -40,6 +41,7 @@ internal class CommitRetrieveParamsTest { .repo("repo") .commit("commit") .getExamples(true) + .include("include") .includeModel(true) .isView(true) .build() @@ -50,6 +52,7 @@ internal class CommitRetrieveParamsTest { .isEqualTo( QueryParams.builder() .put("get_examples", "true") + .put("include", "include") .put("include_model", "true") .put("is_view", "true") .build() diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponseTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponseTest.kt index b1b877fda..1e441a4aa 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponseTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponseTest.kt @@ -25,6 +25,7 @@ internal class CommitRetrieveResponseTest { .startTime("start_time") .build() ) + .isDraft(true) .manifest(JsonValue.from(mapOf())) .modelConfig(JsonValue.from(mapOf())) .modelProvider("model_provider") @@ -41,6 +42,7 @@ internal class CommitRetrieveResponseTest { .startTime("start_time") .build() ) + assertThat(commitRetrieveResponse.isDraft()).contains(true) assertThat(commitRetrieveResponse._manifest()) .isEqualTo(JsonValue.from(mapOf())) assertThat(commitRetrieveResponse._modelConfig()) @@ -63,6 +65,7 @@ internal class CommitRetrieveResponseTest { .startTime("start_time") .build() ) + .isDraft(true) .manifest(JsonValue.from(mapOf())) .modelConfig(JsonValue.from(mapOf())) .modelProvider("model_provider") diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/CommitServiceAsyncTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/CommitServiceAsyncTest.kt index cd517633b..369f0c614 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/CommitServiceAsyncTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/CommitServiceAsyncTest.kt @@ -56,6 +56,7 @@ internal class CommitServiceAsyncTest { .repo("repo") .commit("commit") .getExamples(true) + .include("include") .includeModel(true) .isView(true) .build() diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/CommitServiceTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/CommitServiceTest.kt index fbcf0f0b3..34b77f808 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/CommitServiceTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/CommitServiceTest.kt @@ -55,6 +55,7 @@ internal class CommitServiceTest { .repo("repo") .commit("commit") .getExamples(true) + .include("include") .includeModel(true) .isView(true) .build() From f3bf3404fe56be9801806ea44f283eb586d96ce8 Mon Sep 17 00:00:00 2001 From: Jacob Lee Date: Thu, 26 Mar 2026 13:53:50 -0700 Subject: [PATCH 10/35] feat: Add `traceable` function wrapper for LangSmith tracing (#101) * Adds versioning resource to build * Adds initial version of traceable * Lint * Deflake * Progress * Progress * Fixes * Fixes * More refactor * Small bug * Refactor * Fix * Devin feedback * Tests and feedback * Remove redundant comment * Docstring --- .../okhttp/OkHttpLangsmithClientProvider.kt | 9 + ...hain.smith.tracing.LangsmithClientProvider | 1 + .../smith/tracing/LangsmithClientProvider.kt | 26 + .../com/langchain/smith/tracing/RunContext.kt | 104 +++ .../com/langchain/smith/tracing/RunTree.kt | 375 ++++++++++ .../com/langchain/smith/tracing/Traceable.kt | 643 ++++++++++++++++++ .../langchain/smith/tracing/TriFunction.kt | 22 + .../com/langchain/smith/tracing/Utils.kt | 56 ++ .../smith/tracing/TraceableJavaTest.java | 161 +++++ .../langchain/smith/tracing/TraceableTest.kt | 322 +++++++++ .../smith/tracing/TraceableUnitTest.kt | 362 ++++++++++ .../smith/tracing/TraceableWireTest.kt | 392 +++++++++++ .../com/langchain/smith/tracing/Uuidv7Test.kt | 54 ++ 13 files changed, 2527 insertions(+) create mode 100644 langsmith-java-client-okhttp/src/main/kotlin/com/langchain/smith/client/okhttp/OkHttpLangsmithClientProvider.kt create mode 100644 langsmith-java-client-okhttp/src/main/resources/META-INF/services/com.langchain.smith.tracing.LangsmithClientProvider create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/LangsmithClientProvider.kt create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunContext.kt create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunTree.kt create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TriFunction.kt create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Utils.kt create mode 100644 langsmith-java-core/src/test/java/com/langchain/smith/tracing/TraceableJavaTest.java create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableUnitTest.kt create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableWireTest.kt create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/Uuidv7Test.kt diff --git a/langsmith-java-client-okhttp/src/main/kotlin/com/langchain/smith/client/okhttp/OkHttpLangsmithClientProvider.kt b/langsmith-java-client-okhttp/src/main/kotlin/com/langchain/smith/client/okhttp/OkHttpLangsmithClientProvider.kt new file mode 100644 index 000000000..325791a73 --- /dev/null +++ b/langsmith-java-client-okhttp/src/main/kotlin/com/langchain/smith/client/okhttp/OkHttpLangsmithClientProvider.kt @@ -0,0 +1,9 @@ +package com.langchain.smith.client.okhttp + +import com.langchain.smith.client.LangsmithClient +import com.langchain.smith.tracing.LangsmithClientProvider + +/** [LangsmithClientProvider] backed by [LangsmithOkHttpClient]. */ +class OkHttpLangsmithClientProvider : LangsmithClientProvider { + override fun createClient(): LangsmithClient = LangsmithOkHttpClient.fromEnv() +} diff --git a/langsmith-java-client-okhttp/src/main/resources/META-INF/services/com.langchain.smith.tracing.LangsmithClientProvider b/langsmith-java-client-okhttp/src/main/resources/META-INF/services/com.langchain.smith.tracing.LangsmithClientProvider new file mode 100644 index 000000000..dfe320fdb --- /dev/null +++ b/langsmith-java-client-okhttp/src/main/resources/META-INF/services/com.langchain.smith.tracing.LangsmithClientProvider @@ -0,0 +1 @@ +com.langchain.smith.client.okhttp.OkHttpLangsmithClientProvider diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/LangsmithClientProvider.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/LangsmithClientProvider.kt new file mode 100644 index 000000000..3b1718f5b --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/LangsmithClientProvider.kt @@ -0,0 +1,26 @@ +package com.langchain.smith.tracing + +import com.langchain.smith.client.LangsmithClient + +/** + * Service-provider interface for automatic [LangsmithClient] discovery. + * + * When [traceable] (or [traceFunction], etc.) is called without an explicit client in + * [TraceConfig], the runtime uses [java.util.ServiceLoader] to find an implementation of this + * interface on the classpath and calls [createClient] to obtain a default client. + * + * The `langsmith-java-client-okhttp` module registers a provider automatically. Custom HTTP + * backends can supply their own implementation by adding a + * `META-INF/services/com.langchain.smith.tracing.LangsmithClientProvider` file that lists the + * fully-qualified class name of their provider. + */ +fun interface LangsmithClientProvider { + + /** + * Creates a [LangsmithClient] configured from environment variables and system properties. + * + * Implementations should throw if the environment is not configured (e.g. missing API key) — + * the caller will catch and treat it as "no client available". + */ + fun createClient(): LangsmithClient +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunContext.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunContext.kt new file mode 100644 index 000000000..12a36193a --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunContext.kt @@ -0,0 +1,104 @@ +package com.langchain.smith.tracing + +import java.lang.reflect.InvocationTargetException +import org.slf4j.LoggerFactory + +/** + * Thread-scoped storage for the current [RunTree]. + * + * On Java 21+ this uses `ScopedValue`, which propagates into child tasks forked via + * `StructuredTaskScope`. On older JVMs it falls back to [ThreadLocal]. Neither mechanism + * automatically propagates across unstructured async boundaries like `CompletableFuture` or + * `ExecutorService` — use [withParent] for those cases. + */ +internal interface RunContext { + /** Returns the current [RunTree], or `null` if there is no active run on this thread. */ + fun get(): RunTree? + + /** + * Executes [block] with [value] as the current run. The previous value is restored when [block] + * completes (normally or exceptionally). + */ + fun runWith(value: RunTree?, block: () -> T): T + + companion object { + /** Creates the best available [RunContext] for the current JVM. */ + fun create(): RunContext = scopedValueContext ?: ThreadLocalRunContext() + } +} + +// --------------------------------------------------------------------------- +// ThreadLocal implementation (Java 8+) +// --------------------------------------------------------------------------- + +private class ThreadLocalRunContext : RunContext { + private val threadLocal = ThreadLocal() + + override fun get(): RunTree? = threadLocal.get() + + override fun runWith(value: RunTree?, block: () -> T): T { + val previous = threadLocal.get() + threadLocal.set(value) + try { + return block() + } finally { + threadLocal.set(previous) + } + } +} + +// --------------------------------------------------------------------------- +// ScopedValue implementation (Java 21+, resolved via reflection) +// --------------------------------------------------------------------------- + +private val logger = LoggerFactory.getLogger("com.langchain.smith.tracing.RunContext") + +/** + * Attempts to create a [RunContext] backed by `java.lang.ScopedValue`. Returns `null` on JVMs that + * don't have it. + */ +private val scopedValueContext: RunContext? by lazy { + try { + val svClass = Class.forName("java.lang.ScopedValue") + val newValue = svClass.getMethod("newInstance") + val get = svClass.getMethod("get") + val isBound = svClass.getMethod("isBound") + + // ScopedValue.where(key, value) returns a ScopedValue.Carrier + val where = svClass.getMethod("where", svClass, Any::class.java) + val carrierClass = Class.forName("java.lang.ScopedValue\$Carrier") + // Carrier.call(Callable) returns T + val carrierCall = carrierClass.getMethod("call", java.util.concurrent.Callable::class.java) + + val scopedValue = newValue.invoke(null) // ScopedValue + + object : RunContext { + override fun get(): RunTree? = + try { + if (isBound.invoke(scopedValue) == true) { + get.invoke(scopedValue) as? RunTree + } else { + null + } + } catch (_: InvocationTargetException) { + null + } + + override fun runWith(value: RunTree?, block: () -> T): T { + val carrier = where.invoke(null, scopedValue, value) + try { + // Unavoidable: Method.invoke returns Object; the Callable guarantees the + // actual runtime type matches T. + @Suppress("UNCHECKED_CAST") + return carrierCall.invoke(carrier, java.util.concurrent.Callable { block() }) + as T + } catch (e: InvocationTargetException) { + throw e.cause ?: e + } + } + } + } catch (_: ReflectiveOperationException) { + logger.debug("ScopedValue not available; using ThreadLocal for run context") + null + } +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunTree.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunTree.kt new file mode 100644 index 000000000..e0130f368 --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunTree.kt @@ -0,0 +1,375 @@ +package com.langchain.smith.tracing + +import com.langchain.smith.client.LangsmithClient +import com.langchain.smith.core.JsonValue +import com.langchain.smith.core.getJavaVersion +import com.langchain.smith.core.getPackageVersion +import com.langchain.smith.models.runs.Run +import com.langchain.smith.models.runs.RunIngestBatchParams +import java.time.Instant +import java.util.concurrent.ExecutorService +import org.slf4j.LoggerFactory + +private val logger = LoggerFactory.getLogger(RunTree::class.java) + +/** + * Represents a run in the trace tree. + * + * Can be created manually, via [traceable], or via [createChild]: + * ```kotlin + * // Via traceable (most common) + * val traced = traceable({ input: String -> + * val run = getCurrentRunTree()!! + * run.metadata["my_key"] = "my_value" + * "result" + * }, TraceConfig("my-run")) + * + * // Manual creation + * val run = RunTree(name = "my-run", runType = RunType.LLM, client = myClient) + * ``` + * ```java + * // Java — via builder + * RunTree run = RunTree.builder() + * .name("my-run") + * .runType(RunType.LLM) + * .client(client) + * .build(); + * ``` + */ +class RunTree +constructor( + /** The display name of this run. */ + val name: String = "", + /** The type of run (chain, llm, tool, retriever). */ + val runType: RunType = RunType.CHAIN, + /** The run's input data. */ + var inputs: Map? = null, + /** The run's output data. */ + var outputs: Map? = null, + /** Error string if the run failed. */ + var error: String? = null, + /** Mutable metadata attached to this run. */ + val metadata: MutableMap = mutableMapOf(), + /** Mutable tags for filtering in LangSmith. */ + val tags: MutableList = mutableListOf(), + /** Mutable extra data attached to this run. */ + val extra: MutableMap = mutableMapOf(), + /** The LangSmith project name, or `null` for the server default. */ + val projectName: String? = null, + /** The client used to post this run. Inherited by child runs. */ + @get:JvmSynthetic internal val client: LangsmithClient? = null, + /** The executor used for background posting. Inherited by child runs. */ + @get:JvmSynthetic internal val executor: ExecutorService? = null, + /** Whether tracing is enabled. Inherited by child runs. */ + @get:JvmSynthetic internal val tracingEnabled: Boolean = true, + /** The unique identifier of this run. Auto-generated UUIDv7 if not provided. */ + val id: String = defaultId(), + /** The trace ID shared by all runs in the same trace tree. Defaults to [id] for root runs. */ + val traceId: String = id, + /** ISO-8601 start time of this run. Auto-generated if not provided. */ + val startTime: String = defaultStartTime(), + /** + * The dotted order string that encodes the full path from the root run to this run. Defaults to + * a segment derived from [startTime] and [id]. + */ + val dottedOrder: String = dottedOrderSegment(startTime, id), + /** The run ID of the parent, or `null` if this is a root run. */ + val parentRunId: String? = null, + /** ISO-8601 end time. Set when the run completes. */ + var endTime: String? = null, +) { + + /** + * Creates a child [RunTree] under this run. The child inherits [client], [projectName], + * [executor], and [tracingEnabled] from this run. Per-run fields from [config] (name, runType, + * metadata, tags) are applied to the child, and parent metadata is propagated — child metadata + * takes precedence. + * + * @param config per-run configuration for the child + * @return a new [RunTree] that is a child of this run + */ + fun createChild(config: TraceConfig): RunTree { + val now = Instant.now() + val childId = uuidv7(now) + val childStartTime = ISO_FORMAT.format(now) + val childDottedOrder = "$dottedOrder.${dottedOrderSegment(childStartTime, childId)}" + + // Merge metadata: parent metadata first, child config metadata on top. + val mergedMetadata = mutableMapOf() + mergedMetadata.putAll(metadata) + config.metadata?.let { mergedMetadata.putAll(it) } + + // Merge tags: start with parent tags, add child config tags. + val mergedTags = tags.toMutableList() + config.tags?.let { mergedTags.addAll(it) } + + return RunTree( + id = childId, + traceId = traceId, + dottedOrder = childDottedOrder, + parentRunId = id, + name = config.name ?: "", + runType = config.runType, + startTime = childStartTime, + projectName = config.projectName ?: projectName, + metadata = mergedMetadata, + tags = mergedTags, + client = config.client ?: client, + executor = config.executor ?: executor, + tracingEnabled = config.tracingEnabled ?: tracingEnabled, + ) + } + + // TODO: Delegate background posting to the client's own executor/queue once background run + // processing is implemented there. Currently we manage our own executor and submit individual + // ingestBatch calls per run, which means no batching and no client-level flush/shutdown. + + /** Posts this run to LangSmith in the background (creates the run with inputs + start time). */ + fun postRun() { + val c = client ?: return + val e = executor ?: DEFAULT_EXECUTOR + val runData = buildRunData() + submitSafely(e, name) { + c.runs().ingestBatch(RunIngestBatchParams.builder().addPost(runData).build()) + } + } + + /** Patches this run in LangSmith in the background (updates with outputs, end time, error). */ + fun patchRun() { + val c = client ?: return + val e = executor ?: DEFAULT_EXECUTOR + val runData = buildRunData() + submitSafely(e, name) { + c.runs().ingestBatch(RunIngestBatchParams.builder().addPatch(runData).build()) + } + } + + /** Builds the [Run] data object for posting/patching to the LangSmith API. */ + fun buildRunData(): Run { + val builder = + Run.builder() + .id(id) + .traceId(traceId) + .dottedOrder(dottedOrder) + .name(name) + .runType(Run.RunType.of(runType.value)) + .startTime(startTime) + .apply { this@RunTree.projectName?.let { sessionName(it) } } + .tags(tags) + .inputs( + Run.Inputs.builder().putAllAdditionalProperties(toJsonValueMap(inputs)).build() + ) + .extra( + Run.Extra.builder() + .apply { + this@RunTree.extra.forEach { (k, v) -> + putAdditionalProperty(k, JsonValue.from(v)) + } + } + .putAdditionalProperty( + "metadata", + JsonValue.from(buildRuntimeMetadata(metadata)), + ) + .build() + ) + + endTime?.let { builder.endTime(it) } + error?.let { builder.error(it) } + parentRunId?.let { builder.parentRunId(it) } + outputs?.let { + builder.outputs( + Run.Outputs.builder().putAllAdditionalProperties(toJsonValueMap(it)).build() + ) + } + + return builder.build() + } + + override fun toString(): String = + buildList { + add("id=$id") + add("traceId=$traceId") + add("name=$name") + add("runType=$runType") + add("startTime=$startTime") + projectName?.let { add("projectName=$it") } + parentRunId?.let { add("parentRunId=$it") } + add("dottedOrder=$dottedOrder") + inputs?.let { add("inputs=$it") } + outputs?.let { add("outputs=$it") } + error?.let { add("error=$it") } + endTime?.let { add("endTime=$it") } + if (metadata.isNotEmpty()) add("metadata=$metadata") + if (tags.isNotEmpty()) add("tags=$tags") + if (extra.isNotEmpty()) add("extra=$extra") + } + .joinToString(", ", "RunTree{", "}") + + companion object { + /** Creates a new [Builder] for constructing a [RunTree]. */ + @JvmStatic fun builder() = Builder() + + private fun defaultId(): String = uuidv7(Instant.now()) + + private fun defaultStartTime(): String = ISO_FORMAT.format(Instant.now()) + } + + /** Returns a new [Builder] pre-populated with the values from this run. */ + fun toBuilder() = Builder().from(this) + + /** + * A builder for [RunTree]. + * + * ```java + * RunTree run = RunTree.builder() + * .name("my-run") + * .runType(RunType.LLM) + * .client(client) + * .inputs(Map.of("question", "hello")) + * .build(); + * ``` + */ + class Builder internal constructor() { + private var name: String = "" + private var runType: RunType = RunType.CHAIN + private var inputs: Map? = null + private var outputs: Map? = null + private var error: String? = null + private var metadata: MutableMap = mutableMapOf() + private var tags: MutableList = mutableListOf() + private var extra: MutableMap = mutableMapOf() + private var projectName: String? = null + private var client: LangsmithClient? = null + private var executor: ExecutorService? = null + private var tracingEnabled: Boolean = true + private var id: String? = null + private var traceId: String? = null + private var startTime: String? = null + private var dottedOrder: String? = null + private var parentRunId: String? = null + private var endTime: String? = null + + @JvmSynthetic + internal fun from(run: RunTree) = apply { + name = run.name + runType = run.runType + inputs = run.inputs + outputs = run.outputs + error = run.error + metadata = run.metadata.toMutableMap() + tags = run.tags.toMutableList() + extra = run.extra.toMutableMap() + projectName = run.projectName + client = run.client + executor = run.executor + tracingEnabled = run.tracingEnabled + id = run.id + traceId = run.traceId + startTime = run.startTime + dottedOrder = run.dottedOrder + parentRunId = run.parentRunId + endTime = run.endTime + } + + fun name(name: String) = apply { this.name = name } + + fun runType(runType: RunType) = apply { this.runType = runType } + + fun inputs(inputs: Map) = apply { this.inputs = inputs } + + fun outputs(outputs: Map) = apply { this.outputs = outputs } + + fun error(error: String) = apply { this.error = error } + + fun metadata(metadata: Map) = apply { this.metadata = metadata.toMutableMap() } + + fun tags(tags: List) = apply { this.tags = tags.toMutableList() } + + fun extra(extra: Map) = apply { this.extra = extra.toMutableMap() } + + fun projectName(projectName: String) = apply { this.projectName = projectName } + + fun client(client: LangsmithClient) = apply { this.client = client } + + fun executor(executor: ExecutorService) = apply { this.executor = executor } + + fun tracingEnabled(tracingEnabled: Boolean) = apply { this.tracingEnabled = tracingEnabled } + + fun id(id: String) = apply { this.id = id } + + fun traceId(traceId: String) = apply { this.traceId = traceId } + + fun startTime(startTime: String) = apply { this.startTime = startTime } + + fun dottedOrder(dottedOrder: String) = apply { this.dottedOrder = dottedOrder } + + fun parentRunId(parentRunId: String) = apply { this.parentRunId = parentRunId } + + fun endTime(endTime: String) = apply { this.endTime = endTime } + + fun build(): RunTree { + val resolvedId = id ?: defaultId() + val resolvedStartTime = startTime ?: defaultStartTime() + return RunTree( + name = name, + runType = runType, + inputs = inputs, + outputs = outputs, + error = error, + metadata = metadata, + tags = tags, + extra = extra, + projectName = projectName, + client = client, + executor = executor, + tracingEnabled = tracingEnabled, + id = resolvedId, + traceId = traceId ?: resolvedId, + startTime = resolvedStartTime, + dottedOrder = dottedOrder ?: dottedOrderSegment(resolvedStartTime, resolvedId), + parentRunId = parentRunId, + endTime = endTime, + ) + } + } +} + +// --------------------------------------------------------------------------- +// Private helpers for RunTree posting +// --------------------------------------------------------------------------- + +private fun submitSafely(executor: ExecutorService, runName: String, block: () -> Unit) { + try { + executor.submit { + try { + block() + } catch (e: Exception) { + logger.warn("Failed to send run '$runName'", e) + } + } + } catch (e: java.util.concurrent.RejectedExecutionException) { + logger.warn("Executor is shut down; dropping run '$runName'") + } +} + +private fun toJsonValueMap(data: Map?): Map = + data?.mapValues { (_, v) -> JsonValue.from(v) } ?: emptyMap() + +private val runtimeMetadata: Map by lazy { + mapOf( + "runtime" to JsonValue.from("java"), + "runtime_version" to JsonValue.from(getJavaVersion()), + "sdk" to JsonValue.from("langsmith-java"), + "sdk_version" to JsonValue.from(getPackageVersion()), + ) +} + +private fun buildRuntimeMetadata(userMetadata: Map?): Map = + if (userMetadata.isNullOrEmpty()) { + runtimeMetadata + } else { + buildMap { + putAll(runtimeMetadata) + userMetadata.forEach { (k, v) -> put(k, JsonValue.from(v)) } + } + } diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt new file mode 100644 index 000000000..60fc505b7 --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt @@ -0,0 +1,643 @@ +@file:JvmName("Tracing") + +package com.langchain.smith.tracing + +import com.langchain.smith.client.LangsmithClient +import java.time.Instant +import java.util.ServiceLoader +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.function.BiFunction +import java.util.function.Function +import java.util.function.Supplier +import kotlin.reflect.KFunction +import org.slf4j.LoggerFactory + +private val logger = LoggerFactory.getLogger("com.langchain.smith.tracing.Traceable") + +/** + * The type of run being traced, which maps to `run_type` in LangSmith. + * + * Use the predefined constants ([CHAIN], [LLM], [TOOL], [RETRIEVER]) or create a custom type with + * [of]: + * ```kotlin + * val custom = RunType.of("embedding") + * ``` + */ +class RunType private constructor(internal val value: String) { + companion object { + /** A chain/pipeline/workflow step. */ + @JvmField val CHAIN = RunType("chain") + + /** An LLM call. */ + @JvmField val LLM = RunType("llm") + + /** A tool/function invocation. */ + @JvmField val TOOL = RunType("tool") + + /** A retrieval operation. */ + @JvmField val RETRIEVER = RunType("retriever") + + /** Creates a [RunType] from an arbitrary string value. */ + @JvmStatic fun of(value: String) = RunType(value) + } + + override fun equals(other: Any?): Boolean = + this === other || (other is RunType && value == other.value) + + override fun hashCode(): Int = value.hashCode() + + override fun toString(): String = "RunType{$value}" +} + +internal val CURRENT_RUN = RunContext.create() + +@Volatile private var userDefaultClient: LangsmithClient? = null + +private val autoClient: LangsmithClient? by lazy { createClientFromEnv() } + +private fun createClientFromEnv(): LangsmithClient? = + try { + ServiceLoader.load(LangsmithClientProvider::class.java).firstOrNull()?.createClient() + } catch (e: Exception) { + logger.debug("Could not create default LangSmith client from environment", e) + null + } + +/** + * Returns the [RunTree] for the currently-executing traced function on this thread, or `null` if + * there is no active run (e.g. called outside a [traceable] wrapper, or tracing is disabled). + * + * The returned [RunTree] is mutable — you can add entries to [RunTree.metadata] or [RunTree.extra] + * and they will be included when the run is posted to LangSmith. + * + * To propagate context across async boundaries, pass the returned [RunTree] to [withParent] on the + * new thread. + * + * @see withParent + * @see traceable + */ +fun getCurrentRunTree(): RunTree? = CURRENT_RUN.get() + +/** + * Sets the default [LangsmithClient] used by [traceable] when no client is provided in + * [TraceConfig] and there is no parent run to inherit from. + * + * This is typically called once at application startup: + * ```kotlin + * setDefaultClient(LangsmithOkHttpClient.fromEnv()) + * ``` + * + * If not set explicitly, a default client is created automatically via reflection when tracing is + * enabled and `LangsmithOkHttpClient` is on the classpath. + * + * @see TraceConfig.client + */ +fun setDefaultClient(client: LangsmithClient) { + userDefaultClient = client +} + +/** + * Executes [block] with [parent] as the current run on this thread. Traced functions called inside + * [block] will become children of [parent]. + * + * Use this to propagate context across async boundaries where the run context is not automatically + * inherited (e.g. `CompletableFuture`, `ExecutorService`, coroutines). + * + * On Java 21+, `ScopedValue` is used for context storage, which also propagates into child tasks + * forked via `StructuredTaskScope`. On older JVMs a `ThreadLocal` is used as a fallback. **Neither + * mechanism automatically propagates context across unstructured async boundaries** — use this + * method for those cases. + * + * ```kotlin + * val parent = getCurrentRunTree() + * CompletableFuture.supplyAsync { + * withParent(parent) { + * tracedChild("input") + * } + * } + * ``` + * + * @param parent the run to set as the current parent, or `null` to clear the context + * @param block the code to execute with the given parent context + * @return the result of [block] + * @see getCurrentRunTree + */ +@JvmSynthetic +fun withParent(parent: RunTree?, block: () -> T): T = CURRENT_RUN.runWith(parent, block) + +/** + * Executes [block] with [parent] as the current run on this thread (Java-friendly overload). + * + * ```java + * RunTree parent = Tracing.getCurrentRunTree(); + * CompletableFuture.supplyAsync(() -> + * Tracing.withParent(parent, () -> tracedChild.apply("input"))); + * ``` + * + * @see withParent + */ +fun withParent(parent: RunTree?, block: java.util.concurrent.Callable): T = + CURRENT_RUN.runWith(parent) { block.call() } + +/** + * Executes [block] with [parent] as the current run on this thread (fire-and-forget overload). + * + * Use this for void-returning tasks where [Callable] would require an awkward `return null`: + * ```java + * RunTree parent = Tracing.getCurrentRunTree(); + * executor.execute(() -> Tracing.withParent(parent, () -> tracedChild.apply("input"))); + * ``` + * + * @see withParent + */ +fun withParent(parent: RunTree?, block: Runnable): Unit = + CURRENT_RUN.runWith(parent) { block.run() } + +/** + * Returns the default [LangsmithClient], resolving in order: user-set default, then auto-created + * from environment via reflection. Returns `null` if neither is available. + */ +internal fun resolveDefaultClient(): LangsmithClient? = userDefaultClient ?: autoClient + +/** + * Checks whether LangSmith tracing is enabled. + * + * Returns `true` when any of the following environment variables is set to `"true"` ( + * case-insensitive): + * - `LANGSMITH_TRACING_V2` + * - `LANGSMITH_TRACING` + * - `LANGCHAIN_TRACING_V2` + * - `LANGCHAIN_TRACING` + * + * The corresponding Java system properties (`langsmith.tracing`, `langsmith.tracingV2`, etc.) are + * also checked and take precedence. + */ +fun isTracingEnabled(): Boolean { + val envVars = + listOf( + "LANGSMITH_TRACING_V2" to "langsmith.tracingV2", + "LANGSMITH_TRACING" to "langsmith.tracing", + "LANGCHAIN_TRACING_V2" to "langchain.tracingV2", + "LANGCHAIN_TRACING" to "langchain.tracing", + ) + return envVars.any { (env, prop) -> + System.getProperty(prop)?.equals("true", ignoreCase = true) == true || + System.getenv(env)?.equals("true", ignoreCase = true) == true + } +} + +internal val DEFAULT_PROJECT_NAME: String? by lazy { + System.getenv("LANGSMITH_PROJECT")?.takeIf { it.isNotBlank() } +} + +internal val DEFAULT_EXECUTOR: ExecutorService by lazy { Executors.newCachedThreadPool() } + +/** + * Configuration for a traced run. + * + * At the root of a trace, [client] must be provided (or set via [setDefaultClient]). Child runs + * inherit [client], [projectName], [executor], and [tracingEnabled] from their parent automatically + * — you only need to specify per-run fields like [name], [runType], [metadata], and [tags]. + * + * `TraceConfig` is immutable and safe to reuse. Create a base config and derive per-run configs + * with [toBuilder]: + * ```kotlin + * val base = TraceConfig.builder().client(client).projectName("my-project").build() + * val step1 = traceable({ ... }, base.toBuilder().name("step-1").build()) + * val step2 = traceable({ ... }, base.toBuilder().name("step-2").runType(RunType.LLM).build()) + * ``` + * ```java + * TraceConfig base = TraceConfig.builder() + * .client(client) + * .projectName("my-project") + * .build(); + * var step1 = Tracing.traceFunction(..., base.toBuilder().name("step-1").build()); + * var step2 = Tracing.traceFunction(..., base.toBuilder().name("step-2").runType(RunType.LLM).build()); + * ``` + */ +class TraceConfig( + /** The name of the run, displayed in LangSmith. */ + val name: String? = null, + /** The LangSmith client used to post runs. Required at the root; inherited by children. */ + val client: LangsmithClient? = null, + /** The type of run (defaults to [RunType.CHAIN]). */ + val runType: RunType = RunType.CHAIN, + /** Optional metadata to attach to the run. */ + val metadata: Map? = null, + /** Optional tags for filtering in LangSmith. */ + val tags: List? = null, + /** The LangSmith project name. Inherited by children. */ + val projectName: String? = null, + /** The [ExecutorService] for background run posting. Inherited by children. */ + val executor: ExecutorService? = null, + /** Whether tracing is active. Inherited by children. */ + val tracingEnabled: Boolean? = null, +) { + companion object { + /** Creates a new [Builder] for constructing a [TraceConfig]. */ + @JvmStatic fun builder() = Builder() + } + + /** Returns a new [Builder] pre-populated with the values from this config. */ + fun toBuilder() = Builder().from(this) + + /** + * A builder for [TraceConfig]. + * + * ```java + * TraceConfig config = TraceConfig.builder() + * .name("my-run") + * .client(LangsmithOkHttpClient.fromEnv()) + * .runType(RunType.LLM) + * .metadata(Map.of("version", "1.0")) + * .tags(List.of("prod")) + * .projectName("my-project") + * .build(); + * ``` + */ + class Builder internal constructor() { + private var name: String? = null + private var client: LangsmithClient? = null + private var runType: RunType = RunType.CHAIN + private var metadata: Map? = null + private var tags: List? = null + private var projectName: String? = null + private var executor: ExecutorService? = null + private var tracingEnabled: Boolean? = null + + @JvmSynthetic + internal fun from(config: TraceConfig) = apply { + name = config.name + client = config.client + runType = config.runType + metadata = config.metadata + tags = config.tags + projectName = config.projectName + executor = config.executor + tracingEnabled = config.tracingEnabled + } + + /** The name of the run, displayed in LangSmith. */ + fun name(name: String) = apply { this.name = name } + + /** The LangSmith client used to post runs. Required at the root of a trace. */ + fun client(client: LangsmithClient) = apply { this.client = client } + + /** The type of run (defaults to [RunType.CHAIN]). */ + fun runType(runType: RunType) = apply { this.runType = runType } + + /** Metadata to attach to the run. */ + fun metadata(metadata: Map) = apply { this.metadata = metadata } + + /** Tags for filtering in LangSmith. */ + fun tags(tags: List) = apply { this.tags = tags } + + /** The LangSmith project name. Inherited by children if not set. */ + fun projectName(projectName: String) = apply { this.projectName = projectName } + + /** The [ExecutorService] for background run posting. Inherited by children if not set. */ + fun executor(executor: ExecutorService) = apply { this.executor = executor } + + /** Whether tracing is active. Inherited by children if not set. */ + fun tracingEnabled(tracingEnabled: Boolean) = apply { this.tracingEnabled = tracingEnabled } + + /** Builds the [TraceConfig]. */ + fun build() = + TraceConfig( + name = name, + client = client, + runType = runType, + metadata = metadata, + tags = tags, + projectName = projectName, + executor = executor, + tracingEnabled = tracingEnabled, + ) + } +} + +private const val DEFAULT_RUN_NAME = "" + +/** Resolves the run name from the config and the function being wrapped. */ +private fun resolveName(config: TraceConfig, block: Any?): String { + config.name?.let { + return it + } + if (block is KFunction<*>) return block.name + return DEFAULT_RUN_NAME +} + +/** + * Wraps a no-arg function with LangSmith tracing (Kotlin). + * + * ```kotlin + * val client = LangsmithOkHttpClient.fromEnv() + * val traced = traceable({ "hello" }, TraceConfig("greet", client = client)) + * val result = traced() + * ``` + */ +@JvmSynthetic +fun traceable(block: () -> O, config: TraceConfig): () -> O { + val resolvedConfig = config.toBuilder().name(resolveName(config, block)).build() + return { executeTraced(resolvedConfig, emptyMap()) { block() } } +} + +/** Wraps a no-arg function with LangSmith tracing (Java [Supplier]). */ +fun traceable(block: Supplier, config: TraceConfig): Supplier { + val resolvedConfig = config.toBuilder().name(resolveName(config, block)).build() + return Supplier { executeTraced(resolvedConfig, emptyMap()) { block.get() } } +} + +/** + * Wraps a 1-arg function with LangSmith tracing. + * + * Returns a new function with the same signature that, when called, creates a traced run, records + * the input, executes the original function, and records the output. + * + * Runs nest automatically — calling a traced function inside another traced function creates a + * parent-child relationship in LangSmith. + * + * The input to the returned function is automatically serialized as the run's inputs. If the input + * is a [Map] with string keys, its entries are used directly; otherwise it is recorded as + * `{"inputs": ...}`. + * + * ## Example (Kotlin) + * + * ```kotlin + * val client = LangsmithOkHttpClient.fromEnv() + * + * fun answerQuestion(question: String): String = "42" + * val traced = traceable(::answerQuestion, TraceConfig(client = client)) + * val result = traced("What is the meaning of life?") + * ``` + * + * ## Example (Java) + * + * Java users should prefer [traceFunction] to avoid overload-resolution ambiguity: + * ```java + * LangsmithClient client = LangsmithOkHttpClient.fromEnv(); + * Function traced = Tracing.traceFunction( + * q -> "42", + * TraceConfig.builder().name("answer-question").client(client).build()); + * String result = traced.apply("What is the meaning of life?"); + * ``` + * + * @param block the function to wrap + * @param config tracing configuration (client, run name, type, metadata, tags, project) + * @return a traced wrapper around [block] + * @see traceFunction + * @see TraceConfig + * @see RunTree.getCurrent + * @see withParent + */ +@JvmSynthetic +fun traceable(block: (I) -> O, config: TraceConfig): (I) -> O { + val resolvedConfig = config.toBuilder().name(resolveName(config, block)).build() + return { input -> + val inputs = toInputMap(input) + executeTraced(resolvedConfig, inputs) { block(input) } + } +} + +/** Wraps a 1-arg function with LangSmith tracing (Java [Function]). */ +fun traceable(block: Function, config: TraceConfig): Function { + val traced = traceable({ i: I -> block.apply(i) }, config) + return Function { traced(it) } +} + +/** Wraps a 2-arg function with LangSmith tracing (Kotlin). */ +@JvmSynthetic +fun traceable(block: (I1, I2) -> O, config: TraceConfig): (I1, I2) -> O { + val resolvedConfig = config.toBuilder().name(resolveName(config, block)).build() + return { i1, i2 -> + val inputs = mapOf("args" to listOf(i1, i2)) + executeTraced(resolvedConfig, inputs) { block(i1, i2) } + } +} + +/** Wraps a 2-arg function with LangSmith tracing (Java [BiFunction]). */ +fun traceable( + block: BiFunction, + config: TraceConfig, +): BiFunction { + val traced = traceable({ i1: I1, i2: I2 -> block.apply(i1, i2) }, config) + return BiFunction { i1, i2 -> traced(i1, i2) } +} + +/** Wraps a 3-arg function with LangSmith tracing (Kotlin). */ +@JvmSynthetic +fun traceable(block: (I1, I2, I3) -> O, config: TraceConfig): (I1, I2, I3) -> O { + val resolvedConfig = config.toBuilder().name(resolveName(config, block)).build() + return { i1, i2, i3 -> + val inputs = mapOf("args" to listOf(i1, i2, i3)) + executeTraced(resolvedConfig, inputs) { block(i1, i2, i3) } + } +} + +/** Wraps a 3-arg function with LangSmith tracing (Java [TriFunction]). */ +fun traceable( + block: TriFunction, + config: TraceConfig, +): TriFunction { + val traced = traceable({ i1: I1, i2: I2, i3: I3 -> block.apply(i1, i2, i3) }, config) + return TriFunction { i1, i2, i3 -> traced(i1, i2, i3) } +} + +/** + * Wraps a no-arg [Supplier] with LangSmith tracing. + * + * This is the recommended entry point for Java callers (0-arg). It avoids the overload-resolution + * ambiguity that can occur with [traceable] when Kotlin function types are on the classpath. Kotlin + * callers should prefer [traceable] directly. + * + * ```java + * TraceConfig config = TraceConfig.builder() + * .name("fetch-answer") + * .client(LangsmithOkHttpClient.fromEnv()) + * .build(); + * Supplier traced = Tracing.traceSupplier(() -> "42", config); + * String result = traced.get(); + * ``` + * + * @see traceable + */ +fun traceSupplier(block: Supplier, config: TraceConfig): Supplier = + traceable(block, config) + +/** + * Wraps a 1-arg [Function] with LangSmith tracing. + * + * This is the recommended entry point for Java callers (1-arg). It avoids the overload-resolution + * ambiguity that can occur with [traceable] when Kotlin function types are on the classpath. Kotlin + * callers should prefer [traceable] directly. + * + * ```java + * TraceConfig config = TraceConfig.builder() + * .name("answer-question") + * .client(LangsmithOkHttpClient.fromEnv()) + * .build(); + * Function traced = Tracing.traceFunction(q -> "42", config); + * String result = traced.apply("What is the meaning of life?"); + * ``` + * + * @see traceable + */ +fun traceFunction(block: Function, config: TraceConfig): Function = + traceable(block, config) + +/** + * Wraps a 2-arg [BiFunction] with LangSmith tracing. + * + * This is the recommended entry point for Java callers (2-arg). It avoids the overload-resolution + * ambiguity that can occur with [traceable] when Kotlin function types are on the classpath. Kotlin + * callers should prefer [traceable] directly. + * + * ```java + * TraceConfig config = TraceConfig.builder() + * .name("combine") + * .client(LangsmithOkHttpClient.fromEnv()) + * .build(); + * BiFunction traced = + * Tracing.traceBiFunction((a, b) -> a + " " + b, config); + * String result = traced.apply("hello", "world"); + * ``` + * + * @see traceable + */ +fun traceBiFunction( + block: BiFunction, + config: TraceConfig, +): BiFunction = traceable(block, config) + +/** + * Wraps a 3-arg [TriFunction] with LangSmith tracing. + * + * This is the recommended entry point for Java callers (3-arg). It avoids the overload-resolution + * ambiguity that can occur with [traceable] when Kotlin function types are on the classpath. Kotlin + * callers should prefer [traceable] directly. + * + * ```java + * TraceConfig config = TraceConfig.builder() + * .name("combine3") + * .client(LangsmithOkHttpClient.fromEnv()) + * .build(); + * TriFunction traced = + * Tracing.traceTriFunction((a, b, c) -> a + " " + b + " " + c, config); + * String result = traced.apply("a", "b", "c"); + * ``` + * + * @see traceable + */ +fun traceTriFunction( + block: TriFunction, + config: TraceConfig, +): TriFunction = traceable(block, config) + +/** + * Converts a value to a JSON-safe representation. Primitives, maps, and lists pass through. Other + * objects fall back to [toString]. + * + * For best tracing results, pass [Map] inputs/outputs to [traceable]. Typed SDK objects (e.g. + * `ChatCompletionCreateParams`) should be converted to maps by the caller — use + * `processInputs`/`processOutputs` callbacks (when available) or manual conversion. + */ +private fun serializeValue(value: Any?): Any? = + when (value) { + null, + is String, + is Number, + is Boolean -> value + + is Map<*, *>, + is List<*> -> value + + else -> value.toString() + } + +private fun toInputMap(input: Any?): Map = + toStringKeyedMap(input) ?: mapOf("inputs" to serializeValue(input)) + +private fun toOutputMap(output: Any?): Map = + when (output) { + null -> mapOf("outputs" to null) + else -> toStringKeyedMap(output) ?: mapOf("outputs" to serializeValue(output)) + } + +private fun toStringKeyedMap(value: Any?): Map? { + if (value !is Map<*, *>) return null + val result = mutableMapOf() + for ((k, v) in value) { + if (k !is String) return null + result[k] = v + } + return result +} + +private fun executeTraced(config: TraceConfig, inputs: Map?, block: () -> T): T { + val parentRun = CURRENT_RUN.get() + + // Merge config: child config wins, then parent, then defaults. + val tracingEnabled = config.tracingEnabled ?: parentRun?.tracingEnabled ?: isTracingEnabled() + if (!tracingEnabled) { + return block() + } + + val run = + if (parentRun != null) { + parentRun.createChild(config).also { it.inputs = inputs } + } else { + // Root run — resolve client and create the tree. + val client = + config.client + ?: resolveDefaultClient() + ?: throw IllegalStateException( + "No LangSmith client available. Either pass a client in TraceConfig, " + + "call Tracing.setDefaultClient(), or ensure LangsmithOkHttpClient " + + "is on the classpath with LANGSMITH_API_KEY set." + ) + val now = Instant.now() + val runId = uuidv7(now) + val startTime = ISO_FORMAT.format(now) + + val mergedMetadata = mutableMapOf() + config.metadata?.let { mergedMetadata.putAll(it) } + + RunTree( + id = runId, + traceId = runId, + dottedOrder = dottedOrderSegment(startTime, runId), + parentRunId = null, + name = config.name ?: DEFAULT_RUN_NAME, + runType = config.runType, + startTime = startTime, + projectName = config.projectName ?: DEFAULT_PROJECT_NAME, + inputs = inputs, + outputs = null, + error = null, + endTime = null, + metadata = mergedMetadata, + tags = config.tags?.toMutableList() ?: mutableListOf(), + extra = mutableMapOf(), + client = client, + executor = config.executor ?: DEFAULT_EXECUTOR, + tracingEnabled = tracingEnabled, + ) + } + + run.postRun() + return CURRENT_RUN.runWith(run) { + try { + val result = block() + run.endTime = nowIso() + run.outputs = toOutputMap(result) + run.patchRun() + result + } catch (e: Throwable) { + run.endTime = nowIso() + run.error = e.stackTraceToString() + run.patchRun() + throw e + } + } +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TriFunction.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TriFunction.kt new file mode 100644 index 000000000..3a10c29c7 --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TriFunction.kt @@ -0,0 +1,22 @@ +package com.langchain.smith.tracing + +/** + * A function that accepts three arguments and produces a result. + * + * This is the three-argument equivalent of [java.util.function.Function] and + * [java.util.function.BiFunction]. Use it with [traceTriFunction] to trace a 3-arg function: + * ```java + * TriFunction traced = + * Tracing.traceTriFunction((a, b, c) -> a + " " + b + " " + c, config); + * String result = traced.apply("a", "b", "c"); + * ``` + * + * @param I1 the type of the first argument + * @param I2 the type of the second argument + * @param I3 the type of the third argument + * @param O the type of the result + */ +@FunctionalInterface +fun interface TriFunction { + fun apply(i1: I1, i2: I2, i3: I3): O +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Utils.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Utils.kt new file mode 100644 index 000000000..0e71cafe1 --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Utils.kt @@ -0,0 +1,56 @@ +package com.langchain.smith.tracing + +import java.security.SecureRandom +import java.time.Instant +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter +import java.util.UUID + +internal val ISO_FORMAT: DateTimeFormatter = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'").withZone(ZoneOffset.UTC) + +private val DOTTED_ORDER_STRIP = Regex("[-:.]") + +private val secureRandom = SecureRandom() + +/** + * Generates a UUIDv7 from the given [Instant] — time-ordered with millisecond precision and random + * lower bits. + * + * Layout (RFC 9562): + * - bits 0-47: Unix timestamp in milliseconds (48 bits) + * - bits 48-51: version `0111` (4 bits) + * - bits 52-63: rand_a (12 random bits) + * - bits 64-65: variant `10` (2 bits) + * - bits 66-127: rand_b (62 random bits) + */ +internal fun uuidv7(time: Instant): String { + val timestamp = time.toEpochMilli() + val randomBytes = ByteArray(10) // 80 bits; we use 74 (12 + 62) + secureRandom.nextBytes(randomBytes) + + val msb = + ((timestamp and 0xFFFFFFFFFFFFL) shl 16) or // bits 0-47: timestamp + 0x7000L or // bits 48-51: version 7 + ((randomBytes[0].toLong() and 0x0F) shl 8) or // bits 52-55: rand_a high + (randomBytes[1].toLong() and 0xFF) // bits 56-63: rand_a low + + val lsb = + (0x2L shl 62) or // bits 64-65: variant 10 + ((randomBytes[2].toLong() and 0x3F) shl 56) or // bits 66-71: rand_b + ((randomBytes[3].toLong() and 0xFF) shl 48) or + ((randomBytes[4].toLong() and 0xFF) shl 40) or + ((randomBytes[5].toLong() and 0xFF) shl 32) or + ((randomBytes[6].toLong() and 0xFF) shl 24) or + ((randomBytes[7].toLong() and 0xFF) shl 16) or + ((randomBytes[8].toLong() and 0xFF) shl 8) or + (randomBytes[9].toLong() and 0xFF) + + return UUID(msb, lsb).toString() +} + +/** Creates a dotted order segment from an ISO timestamp and a run ID. */ +internal fun dottedOrderSegment(time: String, id: String): String = + time.replace(DOTTED_ORDER_STRIP, "") + id + +internal fun nowIso(): String = ISO_FORMAT.format(Instant.now()) diff --git a/langsmith-java-core/src/test/java/com/langchain/smith/tracing/TraceableJavaTest.java b/langsmith-java-core/src/test/java/com/langchain/smith/tracing/TraceableJavaTest.java new file mode 100644 index 000000000..8a9b92753 --- /dev/null +++ b/langsmith-java-core/src/test/java/com/langchain/smith/tracing/TraceableJavaTest.java @@ -0,0 +1,161 @@ +package com.langchain.smith.tracing; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.langchain.smith.client.LangsmithClient; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +/** Verifies that the traceable API is ergonomic from Java using the builder. */ +class TraceableJavaTest { + + private final LangsmithClient client = Mockito.mock(LangsmithClient.class); + + private TraceConfig config(String name) { + return TraceConfig.builder() + .name(name) + .client(client) + .tracingEnabled(true) + .build(); + } + + private String greet(String input) { + return "hello " + input; + } + + private String combine(String a, String b) { + return a + " " + b; + } + + private String combine3(String a, String b, String c) { + return a + " " + b + " " + c; + } + + // ---- 0-arg ---- + + @Test + void zeroArgSupplier() { + Supplier traced = Tracing.traceSupplier(() -> "constant", config("zero-arg")); + assertThat(traced.get()).isEqualTo("constant"); + } + + // ---- 1-arg ---- + + @Test + void oneArgWithConfig() { + Function traced = Tracing.traceFunction(this::greet, config("custom-name")); + assertThat(traced.apply("world")).isEqualTo("hello world"); + } + + @Test + void oneArgInlineLambda() { + Function traced = Tracing.traceFunction(input -> "hello " + input, config("my-lambda")); + assertThat(traced.apply("world")).isEqualTo("hello world"); + } + + // ---- 2-arg ---- + + @Test + void twoArgMethodReference() { + BiFunction traced = Tracing.traceBiFunction(this::combine, config("two-arg")); + assertThat(traced.apply("hello", "world")).isEqualTo("hello world"); + } + + @Test + void twoArgLambda() { + BiFunction traced = + Tracing.traceBiFunction((a, b) -> a + " " + b, config("two-arg-lambda")); + assertThat(traced.apply("hello", "world")).isEqualTo("hello world"); + } + + // ---- 3-arg ---- + + @Test + void threeArgMethodReference() { + TriFunction traced = + Tracing.traceTriFunction(this::combine3, config("three-arg")); + assertThat(traced.apply("a", "b", "c")).isEqualTo("a b c"); + } + + @Test + void threeArgLambda() { + TriFunction traced = + Tracing.traceTriFunction((a, b, c) -> a + " " + b + " " + c, config("three-arg-lambda")); + assertThat(traced.apply("a", "b", "c")).isEqualTo("a b c"); + } + + // ---- getCurrentRun ---- + + @Test + void getCurrentRun_insideTracedFunction() { + Function traced = + Tracing.traceFunction(input -> Tracing.getCurrentRunTree(), config("get-run-test")); + RunTree run = traced.apply("hello"); + assertThat(run).isNotNull(); + assertThat(run.getId()).isNotBlank(); + assertThat(run.getTraceId()).isNotBlank(); + assertThat(run.getName()).isEqualTo("get-run-test"); + assertThat(run.getParentRunId()).isNull(); + } + + @Test + void getCurrentRun_canMutateMetadata() { + Function traced = Tracing.traceFunction( + input -> { + RunTree run = Tracing.getCurrentRunTree(); + run.getMetadata().put("java_key", "java_value"); + return "done"; + }, + config("metadata-test")); + assertThat(traced.apply("hello")).isEqualTo("done"); + } + + @Test + void getCurrentRun_outsideTracedFunction() { + assertThat(Tracing.getCurrentRunTree()).isNull(); + } + + // ---- tracingEnabled ---- + + @Test + void tracingDisabled_stillExecutesFunction() { + TraceConfig disabled = TraceConfig.builder() + .name("disabled-test") + .client(client) + .tracingEnabled(false) + .build(); + Function traced = Tracing.traceFunction(input -> "hello " + input, disabled); + assertThat(traced.apply("world")).isEqualTo("hello world"); + } + + // ---- withParent (Runnable) ---- + + @Test + void withParent_runnableOverload() { + Function outer = Tracing.traceFunction( + input -> { + RunTree parent = Tracing.getCurrentRunTree(); + // Fire-and-forget: no "return null" needed + Tracing.withParent(parent, () -> { + assertThat(Tracing.getCurrentRunTree()).isSameAs(parent); + }); + return "ok"; + }, + config("runnable-parent-test")); + assertThat(outer.apply("hello")).isEqualTo("ok"); + } + + @Test + void tracingDisabled_getCurrentRunReturnsNull() { + TraceConfig disabled = TraceConfig.builder() + .name("disabled-run-test") + .client(client) + .tracingEnabled(false) + .build(); + Function traced = Tracing.traceFunction(input -> Tracing.getCurrentRunTree(), disabled); + assertThat(traced.apply("hello")).isNull(); + } +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt new file mode 100644 index 000000000..9f8dffc1a --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt @@ -0,0 +1,322 @@ +package com.langchain.smith.tracing + +import com.langchain.smith.client.okhttp.LangsmithOkHttpClient +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatThrownBy +import org.junit.jupiter.api.Assumptions.assumeTrue +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance + +/** + * Integration tests for [traceable] that post real runs to LangSmith. + * + * Requires `LANGSMITH_API_KEY` to be set. Tests are skipped if the key is missing. + * + * Run with: + * ```bash + * ./gradlew :langsmith-java-core:test --tests "com.langchain.smith.tracing.TraceableTest" + * ``` + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +internal class TraceableTest { + + private lateinit var client: com.langchain.smith.client.LangsmithClient + + /** Gives background threads time to post runs. Temporary until flush moves to the client. */ + private fun awaitPendingRuns() = Thread.sleep(2000) + + private fun config( + name: String, + runType: RunType = RunType.CHAIN, + metadata: Map? = null, + tags: List? = null, + ) = + TraceConfig( + name = name, + client = client, + runType = runType, + metadata = metadata, + tags = tags, + projectName = "traceable-java-tests", + tracingEnabled = true, + ) + + @BeforeAll + fun setUp() { + assumeTrue( + !System.getenv("LANGSMITH_API_KEY").isNullOrBlank(), + "Skipping: LANGSMITH_API_KEY must be set", + ) + client = LangsmithOkHttpClient.fromEnv() + } + + @Test + fun basicTrace() { + val traced = traceable({ _: Map -> "hello" }, config("basic-trace-test")) + assertThat(traced(emptyMap())).isEqualTo("hello") + } + + @Test + fun traceWithInputsAndOutputs() { + val traced = traceable({ _: Map -> "positive" }, config("trace-with-io")) + assertThat(traced(mapOf("text" to "hello world"))).isEqualTo("positive") + } + + @Test + fun traceWithRunType() { + val traced = + traceable( + { _: Map -> "tool result" }, + config("tool-trace", runType = RunType.TOOL), + ) + assertThat(traced(emptyMap())).isEqualTo("tool result") + } + + @Test + fun traceWithMetadataAndTags() { + val traced = + traceable( + { _: Map -> "tagged" }, + config( + "tagged-trace", + metadata = mapOf("version" to "1.0"), + tags = listOf("test", "integration"), + ), + ) + assertThat(traced(emptyMap())).isEqualTo("tagged") + } + + @Test + fun traceRecordsError() { + val failing = + traceable( + { _: Unit -> throw RuntimeException("something broke") }, + config("failing-trace"), + ) + assertThatThrownBy { failing(Unit) } + .isInstanceOf(RuntimeException::class.java) + .hasMessage("something broke") + } + + @Test + fun nestedTraces() { + val child1 = traceable({ _: Unit -> "from child 1" }, config("child-1")) + val child2 = traceable({ _: Unit -> "from child 2" }, config("child-2")) + val parent = + traceable( + { _: Unit -> + val a = child1(Unit) + val b = child2(Unit) + "$a + $b" + }, + config("parent-trace"), + ) + val result = parent(Unit) + assertThat(result).isEqualTo("from child 1 + from child 2") + } + + @Test + fun deeplyNestedTrace() { + val level3 = + traceable({ _: Unit -> "deep result" }, config("level-3", runType = RunType.LLM)) + val level2 = traceable({ _: Unit -> level3(Unit) }, config("level-2")) + val level1 = traceable({ _: Unit -> level2(Unit) }, config("level-1")) + val result = level1(Unit) + assertThat(result).isEqualTo("deep result") + } + + @Test + fun traceableWithOpenAiCall() { + assumeTrue( + !System.getenv("OPENAI_API_KEY").isNullOrBlank(), + "Skipping: OPENAI_API_KEY must be set", + ) + + val openai = com.openai.client.okhttp.OpenAIOkHttpClient.fromEnv() + + val callOpenAi = + traceable( + { question: String -> + val completion = + openai + .chat() + .completions() + .create( + com.openai.models.chat.completions.ChatCompletionCreateParams + .builder() + .model(com.openai.models.ChatModel.GPT_4_1_MINI) + .addUserMessage("$question Answer in one word.") + .maxCompletionTokens(10) + .build() + ) + completion.choices()[0].message().content().orElse("") + }, + config("call-openai", runType = RunType.LLM), + ) + + val formatAnswer = + traceable({ answer: String -> "The answer is: $answer" }, config("format-answer")) + + val agent = + traceable( + { input: Map -> + val answer = callOpenAi(input["question"] as String) + formatAnswer(answer) + }, + config("openai-agent"), + ) + + val result = agent(mapOf("question" to "What is 2+2?")) + println("[Traceable+OpenAI] Result: $result") + + awaitPendingRuns() + } + + @Test + fun traceableWithOpenAiResponsesCall() { + assumeTrue( + !System.getenv("OPENAI_API_KEY").isNullOrBlank(), + "Skipping: OPENAI_API_KEY must be set", + ) + + val openai = com.openai.client.okhttp.OpenAIOkHttpClient.fromEnv() + + val callOpenAiResponses = + traceable( + { question: String -> + val response = + openai + .responses() + .create( + com.openai.models.responses.ResponseCreateParams.builder() + .model(com.openai.models.ChatModel.GPT_4_1_MINI) + .input("$question Answer in one word.") + .build() + ) + response.output().firstNotNullOfOrNull { item -> + item.message().getOrNull()?.content()?.firstNotNullOfOrNull { block -> + block.outputText().getOrNull()?.text() + } + } ?: "" + }, + config("call-openai-responses", runType = RunType.LLM), + ) + + val agent = + traceable( + { input: Map -> callOpenAiResponses(input["question"] as String) }, + config("openai-responses-agent"), + ) + + val result = agent(mapOf("question" to "What is the capital of France?")) + + assertThat(result).containsIgnoringCase("Paris") + println("[Traceable+OpenAI Responses] Result: $result") + + awaitPendingRuns() + } + + @Test + fun getCurrentRun_returnsRunTree() { + var capturedRun: RunTree? = null + val traced = + traceable( + { _: Unit -> + capturedRun = getCurrentRunTree() + "done" + }, + config("get-run-test"), + ) + traced(Unit) + assertThat(capturedRun).isNotNull + assertThat(capturedRun!!.id).isNotBlank() + assertThat(capturedRun!!.traceId).isNotBlank() + assertThat(capturedRun!!.name).isEqualTo("get-run-test") + assertThat(capturedRun!!.parentRunId).isNull() + awaitPendingRuns() + } + + @Test + fun getCurrentRun_nestedRunHasParent() { + var parentRun: RunTree? = null + var childRun: RunTree? = null + val child = + traceable( + { _: Unit -> + childRun = getCurrentRunTree() + "child" + }, + config("child"), + ) + val parent = + traceable( + { _: Unit -> + parentRun = getCurrentRunTree() + child(Unit) + }, + config("parent"), + ) + parent(Unit) + assertThat(parentRun).isNotNull + assertThat(childRun).isNotNull + assertThat(childRun!!.parentRunId).isEqualTo(parentRun!!.id) + assertThat(childRun!!.traceId).isEqualTo(parentRun!!.traceId) + awaitPendingRuns() + } + + @Test + fun getCurrentRun_canMutateMetadata() { + var capturedRun: RunTree? = null + val traced = + traceable( + { _: Unit -> + val run = getCurrentRunTree()!! + run.metadata["custom_key"] = "custom_value" + run.metadata["numeric"] = 42 + capturedRun = run + "done" + }, + config("metadata-mutation-test", metadata = mapOf("initial" to "value")), + ) + traced(Unit) + assertThat(capturedRun).isNotNull + assertThat(capturedRun!!.metadata) + .containsEntry("initial", "value") + .containsEntry("custom_key", "custom_value") + .containsEntry("numeric", 42) + awaitPendingRuns() + } + + @Test + fun getCurrentRun_canMutateExtra() { + var capturedRun: RunTree? = null + val traced = + traceable( + { _: Unit -> + val run = getCurrentRunTree()!! + run.extra["custom_data"] = mapOf("nested" to true) + capturedRun = run + "done" + }, + config("extra-mutation-test"), + ) + traced(Unit) + assertThat(capturedRun).isNotNull + @Suppress("UNCHECKED_CAST") + val customData = capturedRun!!.extra["custom_data"] as Map + assertThat(customData).containsEntry("nested", true) + awaitPendingRuns() + } + + @Test + fun getCurrentRun_outsideTracedFunction() { + assertThat(getCurrentRunTree()).isNull() + } + + // TODO: Add agent loop with OpenAI tool calling integration test once + // the OpenAI SDK dependency is bumped (requires updating OTel wrappers + // for new abstract members). The tool calling API (`addTool`, `arguments()`, + // `contentAsJson`) requires OpenAI Java SDK 4.10+. +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableUnitTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableUnitTest.kt new file mode 100644 index 000000000..8fb209eb6 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableUnitTest.kt @@ -0,0 +1,362 @@ +package com.langchain.smith.tracing + +import com.langchain.smith.client.LangsmithClient +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test +import org.mockito.kotlin.mock + +/** + * Unit tests for [traceable] input/output serialization, config inheritance, and [createChild]. + * Uses a mock client so no API key is required. + */ +internal class TraceableUnitTest { + + private val client: LangsmithClient = mock() + + private fun config(name: String) = + TraceConfig(name = name, client = client, tracingEnabled = true) + + // ---- Helpers ---- + + /** Traces a 1-arg function, invokes it, and returns the captured [RunTree]. */ + private fun traceAndCapture(input: I, name: String = "test"): RunTree { + var run: RunTree? = null + val traced = + traceable( + { _: I -> + run = getCurrentRunTree() + "result" + }, + config(name), + ) + traced(input) + return run!! + } + + /** Traces a function returning [output], invokes it, and returns the captured [RunTree]. */ + private fun traceWithOutput(output: O, name: String = "test"): RunTree { + var run: RunTree? = null + val traced = + traceable( + { _: Unit -> + run = getCurrentRunTree() + output + }, + config(name), + ) + traced(Unit) + return run!! + } + + /** + * Runs a parent→child nesting where the child uses [childConfig] and returns the child's + * captured [RunTree]. + */ + private fun traceChild(childConfig: TraceConfig): RunTree { + var childRun: RunTree? = null + val child = + traceable( + { _: Unit -> + childRun = getCurrentRunTree() + "child" + }, + childConfig, + ) + val parent = traceable({ _: Unit -> child(Unit) }, config("parent")) + parent(Unit) + return childRun!! + } + + private fun rootRun( + name: String = "parent", + metadata: Map = emptyMap(), + tags: List = emptyList(), + projectName: String = "test-project", + ) = + RunTree( + name = name, + metadata = metadata.toMutableMap(), + tags = tags.toMutableList(), + projectName = projectName, + client = client, + ) + + // ---- Input serialization ---- + + @Test + fun stringInput_wrappedAsInputsKey() { + assertThat(traceAndCapture("hello").inputs).isEqualTo(mapOf("inputs" to "hello")) + } + + @Test + fun intInput_wrappedAsInputsKey() { + assertThat(traceAndCapture(42).inputs).isEqualTo(mapOf("inputs" to 42)) + } + + @Test + fun listInput_wrappedAsInputsKey() { + assertThat(traceAndCapture(listOf("a", "b")).inputs) + .isEqualTo(mapOf("inputs" to listOf("a", "b"))) + } + + @Test + fun mapInput_usedDirectly() { + val input = mapOf("question" to "hello", "context" to "world") + assertThat(traceAndCapture(input).inputs).isEqualTo(input) + } + + @Test + fun mapWithNonStringKeys_wrappedAsInputsKey() { + assertThat(traceAndCapture(mapOf(1 to "a", 2 to "b")).inputs).containsKey("inputs") + } + + @Test + fun zeroArgInput_emptyMap() { + var capturedInputs: Map? = null + val block: () -> String = { + capturedInputs = getCurrentRunTree()?.inputs + "result" + } + traceable(block, config("zero-arg"))() + assertThat(capturedInputs).isEqualTo(emptyMap()) + } + + @Test + fun twoArgInput_wrappedAsArgs() { + var capturedInputs: Map? = null + traceable( + { a: String, b: Int -> + capturedInputs = getCurrentRunTree()?.inputs + "result" + }, + config("two-arg"), + )("hello", 42) + assertThat(capturedInputs).isEqualTo(mapOf("args" to listOf("hello", 42))) + } + + @Test + fun threeArgInput_wrappedAsArgs() { + var capturedInputs: Map? = null + traceable( + { a: String, b: Int, c: Boolean -> + capturedInputs = getCurrentRunTree()?.inputs + "result" + }, + config("three-arg"), + )("hello", 42, true) + assertThat(capturedInputs).isEqualTo(mapOf("args" to listOf("hello", 42, true))) + } + + // ---- Output serialization ---- + + @Test + fun stringOutput_wrappedAsOutputsKey() { + assertThat(traceWithOutput("hello world").outputs) + .isEqualTo(mapOf("outputs" to "hello world")) + } + + @Test + fun intOutput_wrappedAsOutputsKey() { + assertThat(traceWithOutput(42).outputs).isEqualTo(mapOf("outputs" to 42)) + } + + @Test + fun nullOutput_wrappedAsOutputsKey() { + assertThat(traceWithOutput(null).outputs).isEqualTo(mapOf("outputs" to null)) + } + + @Test + fun mapOutput_usedDirectly() { + val output = mapOf("answer" to "42", "confidence" to 0.95) + assertThat(traceWithOutput(output).outputs).isEqualTo(output) + } + + @Test + fun listOutput_wrappedAsOutputsKey() { + assertThat(traceWithOutput(listOf("a", "b", "c")).outputs) + .isEqualTo(mapOf("outputs" to listOf("a", "b", "c"))) + } + + // ---- Config inheritance via traceable ---- + + @Test + fun childInheritsClientFromParent() { + val childRun = traceChild(TraceConfig("child")) + assertThat(childRun.name).isEqualTo("child") + } + + @Test + fun childInheritsProjectNameFromParent() { + var childRun: RunTree? = null + val child = + traceable( + { _: Unit -> + childRun = getCurrentRunTree() + "child" + }, + TraceConfig("child"), + ) + val parent = + traceable( + { _: Unit -> child(Unit) }, + TraceConfig( + name = "parent", + client = client, + projectName = "inherited-project", + tracingEnabled = true, + ), + ) + parent(Unit) + assertThat(childRun!!.projectName).isEqualTo("inherited-project") + } + + @Test + fun childOverridesProjectName() { + var childRun: RunTree? = null + val child = + traceable( + { _: Unit -> + childRun = getCurrentRunTree() + "child" + }, + TraceConfig("child", projectName = "child-project"), + ) + val parent = + traceable( + { _: Unit -> child(Unit) }, + TraceConfig( + name = "parent", + client = client, + projectName = "parent-project", + tracingEnabled = true, + ), + ) + parent(Unit) + assertThat(childRun!!.projectName).isEqualTo("child-project") + } + + @Test + fun childInheritsTracingEnabledFromParent() { + val childRun = traceChild(TraceConfig("child")) + assertThat(childRun.name).isEqualTo("child") + } + + @Test + fun childCanDisableTracing() { + val childRun = traceChild(TraceConfig("child", tracingEnabled = false)) + // Child disabled tracing — no new run is created, so getCurrentRunTree() returns parent. + assertThat(childRun.name).isEqualTo("parent") + } + + // ---- createChild ---- + + @Test + fun createChild_inheritsTraceId() { + val parent = rootRun() + val child = parent.createChild(TraceConfig("child")) + assertThat(child.traceId).isEqualTo(parent.traceId) + } + + @Test + fun createChild_setsParentRunId() { + val parent = rootRun() + assertThat(parent.createChild(TraceConfig("child")).parentRunId).isEqualTo(parent.id) + } + + @Test + fun createChild_extendsDottedOrder() { + val parent = rootRun() + assertThat(parent.createChild(TraceConfig("child")).dottedOrder) + .startsWith(parent.dottedOrder + ".") + } + + @Test + fun createChild_inheritsProjectName() { + val parent = rootRun(projectName = "inherited-project") + assertThat(parent.createChild(TraceConfig("child")).projectName) + .isEqualTo("inherited-project") + } + + @Test + fun createChild_overridesProjectName() { + val parent = rootRun(projectName = "parent-project") + assertThat( + parent.createChild(TraceConfig("child", projectName = "child-project")).projectName + ) + .isEqualTo("child-project") + } + + @Test + fun createChild_inheritsClient() { + val parent = rootRun() + assertThat(parent.createChild(TraceConfig("child")).client).isSameAs(parent.client) + } + + @Test + fun createChild_overridesClient() { + val otherClient: LangsmithClient = mock() + val child = rootRun().createChild(TraceConfig("child", client = otherClient)) + assertThat(child.client).isSameAs(otherClient) + } + + @Test + fun createChild_mergesMetadata_parentFirst_childOverrides() { + val parent = rootRun(metadata = mapOf("shared" to "parent", "parent_only" to "yes")) + val child = + parent.createChild( + TraceConfig("child", metadata = mapOf("shared" to "child", "child_only" to "yes")) + ) + assertThat(child.metadata) + .containsEntry("shared", "child") + .containsEntry("parent_only", "yes") + .containsEntry("child_only", "yes") + } + + @Test + fun createChild_inheritsMetadata_whenChildHasNone() { + val parent = rootRun(metadata = mapOf("key" to "value")) + assertThat(parent.createChild(TraceConfig("child")).metadata).containsEntry("key", "value") + } + + @Test + fun createChild_mergesTags() { + val parent = rootRun(tags = listOf("parent-tag")) + assertThat(parent.createChild(TraceConfig("child", tags = listOf("child-tag"))).tags) + .containsExactly("parent-tag", "child-tag") + } + + @Test + fun createChild_inheritsTags_whenChildHasNone() { + val parent = rootRun(tags = listOf("parent-tag")) + assertThat(parent.createChild(TraceConfig("child")).tags).containsExactly("parent-tag") + } + + @Test + fun createChild_defaultsInputsToNull() { + assertThat(rootRun().createChild(TraceConfig("child")).inputs).isNull() + } + + @Test + fun createChild_setsNameAndRunType() { + val child = rootRun().createChild(TraceConfig("my-tool", runType = RunType.TOOL)) + assertThat(child.name).isEqualTo("my-tool") + assertThat(child.runType).isEqualTo(RunType.TOOL) + } + + @Test + fun createChild_generatesUniqueIds() { + val parent = rootRun() + val child1 = parent.createChild(TraceConfig("child-1")) + val child2 = parent.createChild(TraceConfig("child-2")) + assertThat(child1.id).isNotEqualTo(child2.id) + assertThat(child1.dottedOrder).isNotEqualTo(child2.dottedOrder) + } + + @Test + fun createChild_startsWithEmptyOutputsAndNoError() { + val child = rootRun().createChild(TraceConfig("child")) + assertThat(child.outputs).isNull() + assertThat(child.error).isNull() + assertThat(child.endTime).isNull() + } +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableWireTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableWireTest.kt new file mode 100644 index 000000000..851ad3d07 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableWireTest.kt @@ -0,0 +1,392 @@ +package com.langchain.smith.tracing + +import com.langchain.smith.client.LangsmithClient +import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatThrownBy +import org.junit.jupiter.api.Test +import org.mockito.kotlin.any +import org.mockito.kotlin.doReturn +import org.mockito.kotlin.doThrow +import org.mockito.kotlin.mock + +/** + * Tests that verify the [RunTree] state produced by [traceable], including tree structure, inputs, + * outputs, errors, metadata, and [RunTree.buildRunData] serialization. + */ +internal class TraceableWireTest { + + private val client: LangsmithClient = mock() + + private fun config(name: String) = + TraceConfig(name = name, client = client, tracingEnabled = true) + + // ---- Basic tracing ---- + + @Test + fun singleRun_hasCorrectState() { + var run: RunTree? = null + val traced = + traceable( + { input: String -> + run = getCurrentRunTree() + "echo: $input" + }, + config("echo"), + ) + traced("hello") + + assertThat(run).isNotNull + assertThat(run!!.name).isEqualTo("echo") + assertThat(run!!.inputs).isEqualTo(mapOf("inputs" to "hello")) + assertThat(run!!.outputs).isEqualTo(mapOf("outputs" to "echo: hello")) + assertThat(run!!.endTime).isNotNull() + assertThat(run!!.error).isNull() + } + + @Test + fun singleRun_buildRunData_containsAllFields() { + var run: RunTree? = null + val traced = + traceable( + { _: Unit -> + run = getCurrentRunTree() + "result" + }, + TraceConfig( + "wire-test", + client = client, + tracingEnabled = true, + metadata = mapOf("custom" to "value"), + tags = listOf("prod", "v2"), + projectName = "my-project", + ), + ) + traced(Unit) + + val data = run!!.buildRunData() + assertThat(data.name().orElse(null)).isEqualTo("wire-test") + assertThat(data.id().orElse(null)).isEqualTo(run!!.id) + assertThat(data.traceId().orElse(null)).isEqualTo(run!!.traceId) + assertThat(data.dottedOrder().orElse(null)).isEqualTo(run!!.dottedOrder) + assertThat(data.startTime().orElse(null)).isEqualTo(run!!.startTime) + assertThat(data.sessionName().orElse(null)).isEqualTo("my-project") + assertThat(data.tags().orElse(emptyList())).containsExactly("prod", "v2") + assertThat(data.outputs().isPresent).isTrue() + assertThat(data.endTime().isPresent).isTrue() + assertThat(data.error().isPresent).isFalse() + val extra = data.extra().orElse(null) + assertThat(extra).isNotNull + // Verify metadata exists in extra (contains user + runtime metadata) + assertThat(run!!.metadata).containsEntry("custom", "value") + assertThat(extra!!._additionalProperties()).containsKey("metadata") + } + + // ---- Nested tracing / tree structure ---- + + @Test + fun nestedRuns_correctParentChild() { + var parentRun: RunTree? = null + var child1Run: RunTree? = null + var child2Run: RunTree? = null + val child1 = + traceable( + { _: Unit -> + child1Run = getCurrentRunTree() + "c1" + }, + TraceConfig("child-1"), + ) + val child2 = + traceable( + { _: Unit -> + child2Run = getCurrentRunTree() + "c2" + }, + TraceConfig("child-2"), + ) + val parent = + traceable( + { _: Unit -> + parentRun = getCurrentRunTree() + child1(Unit) + child2(Unit) + "parent-result" + }, + config("parent"), + ) + parent(Unit) + + assertThat(parentRun!!.parentRunId).isNull() + assertThat(child1Run!!.parentRunId).isEqualTo(parentRun!!.id) + assertThat(child2Run!!.parentRunId).isEqualTo(parentRun!!.id) + assertThat(child1Run!!.traceId).isEqualTo(parentRun!!.traceId) + assertThat(child2Run!!.traceId).isEqualTo(parentRun!!.traceId) + assertThat(child1Run!!.dottedOrder).startsWith(parentRun!!.dottedOrder + ".") + assertThat(child2Run!!.dottedOrder).startsWith(parentRun!!.dottedOrder + ".") + } + + @Test + fun deeplyNestedRuns_correctChain() { + var l1: RunTree? = null + var l2: RunTree? = null + var l3: RunTree? = null + val level3 = + traceable( + { _: Unit -> + l3 = getCurrentRunTree() + "deep" + }, + TraceConfig("level-3"), + ) + val level2 = + traceable( + { _: Unit -> + l2 = getCurrentRunTree() + level3(Unit) + }, + TraceConfig("level-2"), + ) + val level1 = + traceable( + { _: Unit -> + l1 = getCurrentRunTree() + level2(Unit) + }, + config("level-1"), + ) + level1(Unit) + + assertThat(l1!!.parentRunId).isNull() + assertThat(l2!!.parentRunId).isEqualTo(l1!!.id) + assertThat(l3!!.parentRunId).isEqualTo(l2!!.id) + assertThat(l3!!.traceId).isEqualTo(l1!!.traceId) + } + + @Test + fun nestedRuns_buildRunData_parentRunIdSet() { + var childRun: RunTree? = null + val child = + traceable( + { _: Unit -> + childRun = getCurrentRunTree() + "child" + }, + TraceConfig("child"), + ) + val parent = traceable({ _: Unit -> child(Unit) }, config("parent")) + parent(Unit) + + val data = childRun!!.buildRunData() + assertThat(data.parentRunId().isPresent).isTrue() + } + + // ---- Error handling ---- + + @Test + fun errorRun_capturesErrorInRunTree() { + var run: RunTree? = null + val traced = + traceable( + { _: Unit -> + run = getCurrentRunTree() + throw RuntimeException("boom") + }, + config("failing"), + ) + assertThatThrownBy { traced(Unit) }.hasMessage("boom") + + assertThat(run!!.error).contains("boom") + assertThat(run!!.endTime).isNotNull() + + val data = run!!.buildRunData() + assertThat(data.error().orElse(null)).contains("boom") + assertThat(data.endTime().isPresent).isTrue() + } + + @Test + fun clientError_doesNotBreakWrappedFunction() { + val errorRunService = + mock { + on { ingestBatch(any(), any()) } doThrow RuntimeException("client broke") + } + val errorClient = mock { on { runs() } doReturn errorRunService } + val traced = + traceable( + { input: Int -> input * 2 }, + TraceConfig("error-test", client = errorClient, tracingEnabled = true), + ) + + val result = traced(5) + // Give background thread time to fail + Thread.sleep(200) + assertThat(result).isEqualTo(10) + } + + // ---- Null input ---- + + @Test + fun nullInput_doesNotThrow() { + var run: RunTree? = null + val traced = + traceable( + { input: String? -> + run = getCurrentRunTree() + input + }, + config("null-test"), + ) + val result = traced(null) + + assertThat(result).isNull() + assertThat(run).isNotNull + assertThat(run!!.inputs).isEqualTo(mapOf("inputs" to null)) + assertThat(run!!.outputs).isEqualTo(mapOf("outputs" to null)) + } + + // ---- withParent ---- + + @Test + fun withParent_correctTreeStructure() { + var parentRun: RunTree? = null + var childRun: RunTree? = null + val child = + traceable( + { _: Unit -> + childRun = getCurrentRunTree() + "child-result" + }, + TraceConfig("child"), + ) + val parent = + traceable( + { _: Unit -> + parentRun = getCurrentRunTree() + withParent(parentRun) { child(Unit) } + }, + config("parent"), + ) + parent(Unit) + + assertThat(childRun!!.parentRunId).isEqualTo(parentRun!!.id) + assertThat(childRun!!.traceId).isEqualTo(parentRun!!.traceId) + } + + // ---- Metadata and tags in buildRunData ---- + + @Test + fun metadata_includedInBuildRunData() { + var run: RunTree? = null + val traced = + traceable( + { _: Unit -> + run = getCurrentRunTree() + run!!.metadata["dynamic"] = "added" + "ok" + }, + TraceConfig( + "meta-test", + client = client, + tracingEnabled = true, + metadata = mapOf("static" to "config"), + ), + ) + traced(Unit) + + // Verify metadata on the RunTree itself (which buildRunData reads from) + assertThat(run!!.metadata).containsEntry("static", "config") + assertThat(run!!.metadata).containsEntry("dynamic", "added") + // Verify buildRunData includes metadata in extra + val data = run!!.buildRunData() + assertThat(data.extra().orElse(null)!!._additionalProperties()).containsKey("metadata") + } + + @Test + fun tags_includedInBuildRunData() { + var run: RunTree? = null + val traced = + traceable( + { _: Unit -> + run = getCurrentRunTree() + run!!.tags.add("dynamic-tag") + "ok" + }, + TraceConfig( + "tag-test", + client = client, + tracingEnabled = true, + tags = listOf("static-tag"), + ), + ) + traced(Unit) + + val data = run!!.buildRunData() + assertThat(data.tags().orElse(emptyList())).containsExactly("static-tag", "dynamic-tag") + } + + // ---- tracingEnabled: false ---- + + @Test + fun tracingDisabled_noRunTreeCreated() { + var run: RunTree? = null + val traced = + traceable( + { _: Unit -> + run = getCurrentRunTree() + "ok" + }, + TraceConfig("disabled", client = client, tracingEnabled = false), + ) + val result = traced(Unit) + + assertThat(result).isEqualTo("ok") + assertThat(run).isNull() + } + + // ---- Multi-arg ---- + + @Test + fun twoArgs_inputsContainArgs() { + var run: RunTree? = null + val traced = + traceable( + { a: String, b: Int -> + run = getCurrentRunTree() + "$a$b" + }, + config("two-arg"), + ) + traced("hello", 42) + + assertThat(run!!.inputs).isEqualTo(mapOf("args" to listOf("hello", 42))) + } + + // ---- Config inheritance ---- + + @Test + fun childInheritsProjectName_inBuildRunData() { + var childRun: RunTree? = null + val child = + traceable( + { _: Unit -> + childRun = getCurrentRunTree() + "child" + }, + TraceConfig("child"), + ) + val parent = + traceable( + { _: Unit -> child(Unit) }, + TraceConfig( + "parent", + client = client, + tracingEnabled = true, + projectName = "my-project", + ), + ) + parent(Unit) + + assertThat(childRun!!.projectName).isEqualTo("my-project") + val data = childRun!!.buildRunData() + assertThat(data.sessionName().orElse(null)).isEqualTo("my-project") + } +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/Uuidv7Test.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/Uuidv7Test.kt new file mode 100644 index 000000000..0292fbc89 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/Uuidv7Test.kt @@ -0,0 +1,54 @@ +package com.langchain.smith.tracing + +import java.time.Instant +import java.util.UUID +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class Uuidv7Test { + + @Test + fun embeds_timestamp_in_high_bits() { + val time = Instant.parse("2026-03-26T20:11:20.557Z") + val id = UUID.fromString(uuidv7(time)) + + // Top 48 bits of the most-significant long encode the Unix epoch millis. + val embeddedMillis = id.mostSignificantBits ushr 16 + assertThat(embeddedMillis).isEqualTo(time.toEpochMilli()) + } + + @Test + fun sets_version_7() { + val id = UUID.fromString(uuidv7(Instant.now())) + assertThat(id.version()).isEqualTo(7) + } + + @Test + fun sets_rfc_variant() { + val id = UUID.fromString(uuidv7(Instant.now())) + // UUID.variant() returns 2 for the RFC 4122 / 9562 variant (bits 10xx). + assertThat(id.variant()).isEqualTo(2) + } + + @Test + fun matches_known_prefix_for_fixed_time() { + // The JS reference implementation produces "019d2bc5-dc6d-7..." for this instant. + // The first 13 hex chars (timestamp + version nibble) are deterministic. + val id = uuidv7(Instant.parse("2026-03-26T20:11:20.557Z")) + assertThat(id).startsWith("019d2bc5-dc6d-7") + } + + @Test + fun produces_unique_ids_for_same_instant() { + val time = Instant.now() + val ids = (1..100).map { uuidv7(time) }.toSet() + assertThat(ids).hasSize(100) + } + + @Test + fun ids_for_increasing_times_sort_lexicographically() { + val base = Instant.parse("2025-01-01T00:00:00Z") + val ids = (0L..9L).map { uuidv7(base.plusMillis(it * 100)) } + assertThat(ids).isSorted() + } +} From 620a6de022da681a6740e71560ec364e0fea0b7a Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Thu, 26 Mar 2026 21:13:47 +0000 Subject: [PATCH 11/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index c0fb79a90..c701afc70 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-d4b2278e9baa17ef476065b3b53a2012bcfd257915aa38991d2ecdfab1595766.yml -openapi_spec_hash: 90898c9254e266bfde382341368d3793 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-e76d945c51e9b67cd99415618f38be1e9c9d11a39a46930004dd635d03fc7943.yml +openapi_spec_hash: c72eecf808795182316ae7cb65da5218 config_hash: 787a12876983a14bce67ed57899e4a94 From 66b5f277d797a6a0f16fe580ba61d3bb7e0feb16 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 27 Mar 2026 06:13:42 +0000 Subject: [PATCH 12/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index c701afc70..724c7353b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-e76d945c51e9b67cd99415618f38be1e9c9d11a39a46930004dd635d03fc7943.yml -openapi_spec_hash: c72eecf808795182316ae7cb65da5218 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-3dc7535bcdd9c57fee8362d4866efd19f75e182cf57a10e475049b4c92af56ff.yml +openapi_spec_hash: 781bbf1531d6cdfb7371b4594e9f809d config_hash: 787a12876983a14bce67ed57899e4a94 From ee2991f830703f29b3d0eddfd621109362a465e5 Mon Sep 17 00:00:00 2001 From: Jacob Lee Date: Fri, 27 Mar 2026 09:16:49 -0700 Subject: [PATCH 13/35] feat: Adds processInputs and processOutputs to traceable (#113) * Adds processInputs and processOutputs to traceable * Move generics into TraceProcessIO to avoid having them top level * Fix docstring, nit --- .../com/langchain/smith/tracing/RunTree.kt | 9 +- .../langchain/smith/tracing/TraceProcessIO.kt | 97 ++++++++ .../com/langchain/smith/tracing/Traceable.kt | 91 ++++++-- .../smith/tracing/TraceableJavaTest.java | 47 ++++ .../langchain/smith/tracing/TraceableTest.kt | 210 +++++++++++++++--- .../smith/tracing/TraceableUnitTest.kt | 184 ++++++++++++--- .../smith/tracing/TraceableWireTest.kt | 57 +++-- 7 files changed, 597 insertions(+), 98 deletions(-) create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunTree.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunTree.kt index e0130f368..647fb60c4 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunTree.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/RunTree.kt @@ -15,6 +15,12 @@ private val logger = LoggerFactory.getLogger(RunTree::class.java) /** * Represents a run in the trace tree. * + * **Thread safety:** `RunTree` is mutable — [inputs], [outputs], [error], [endTime], [metadata], + * [tags], and [extra] can be modified after construction. A single `RunTree` instance should only + * be accessed from one thread at a time. Within a [traceable] wrapper this is guaranteed by the + * run-context scoping, but if you hold a reference to a `RunTree` and access it from multiple + * threads, external synchronization is required. + * * Can be created manually, via [traceable], or via [createChild]: * ```kotlin * // Via traceable (most common) @@ -36,8 +42,7 @@ private val logger = LoggerFactory.getLogger(RunTree::class.java) * .build(); * ``` */ -class RunTree -constructor( +class RunTree( /** The display name of this run. */ val name: String = "", /** The type of run (chain, llm, tool, retriever). */ diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt new file mode 100644 index 000000000..15fb26162 --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt @@ -0,0 +1,97 @@ +@file:JvmName("TraceProcessIOHelper") + +package com.langchain.smith.tracing + +import java.util.function.Function + +/** + * Typed processors for transforming inputs and outputs before they are recorded on a traced run. + * + * The type parameters describe what the processors receive: + * - [PI] — the type passed to [inputs]. For 1-arg traced functions this is the raw input type; for + * 0/2/3-arg functions this is `Map` (the packed representation). + * - [PO] — the type passed to [outputs]. This is always the raw output type of the traced function. + * + * When [inputs] is set, it replaces the default input serialization entirely. Same for [outputs]. + * + * ## Example (Kotlin) + * + * ```kotlin + * val process = TraceProcessIO( + * processInputs = Function { input -> mapOf("query" to input) }, + * processOutputs = Function { resp -> mapOf("answer" to resp.text) }, + * ) + * val config = TraceConfig(name = "my-run", client = client, processTracedIO = process) + * ``` + * + * ## Example (Java) + * + * ```java + * TraceProcessIO process = TraceProcessIO.builder() + * .processInputs(input -> Map.of("query", input)) + * .processOutputs(resp -> Map.of("answer", resp.getText())) + * .build(); + * TraceConfig config = TraceConfig.builder() + * .name("my-run") + * .client(client) + * .processTracedIO(process) + * .build(); + * ``` + * + * @see TraceConfig.processTracedIO + */ +class TraceProcessIO( + processInputs: Function>? = null, + processOutputs: Function>? = null, +) { + // Store erased wrappers so traceable overloads can call these without casts. + // erase() converts Function to Function — safe because T erases to Object. + internal val inputsFn: Function>? = processInputs?.erase() + internal val outputsFn: Function>? = processOutputs?.erase() + + companion object { + /** Creates a new [Builder]. */ + @JvmStatic fun builder() = Builder() + + /** + * Converts a typed [Function] to an erased `Function`. + * + * Safe because generic type parameters erase to `Object` at runtime — the JVM never + * actually checks the input type on `Function.apply`. + */ + @JvmSynthetic + @JvmStatic + @Suppress("UNCHECKED_CAST") + private fun Function.erase(): Function = this as Function + } + + /** + * A builder for [TraceProcessIO]. + * + * ```java + * TraceProcessIO process = TraceProcessIO.builder() + * .processInputs(input -> Map.of("query", input)) + * .processOutputs(output -> Map.of("answer", output)) + * .build(); + * ``` + */ + class Builder internal constructor() { + private var processInputs: Function>? = null + private var processOutputs: Function>? = null + + /** Callback to transform the input before it is recorded on the run. */ + fun processInputs(processInputs: Function>) = apply { + this.processInputs = processInputs + } + + /** Callback to transform the output before it is recorded on the run. */ + fun processOutputs(processOutputs: Function>) = apply { + this.processOutputs = processOutputs + } + + /** Builds the [TraceProcessIO]. */ + fun build() = TraceProcessIO(processInputs = processInputs, processOutputs = processOutputs) + } + + override fun toString(): String = "TraceProcessIO{inputs=$inputsFn, outputs=$outputsFn}" +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt index 60fc505b7..2d00d0cac 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt @@ -233,6 +233,27 @@ class TraceConfig( val executor: ExecutorService? = null, /** Whether tracing is active. Inherited by children. */ val tracingEnabled: Boolean? = null, + /** + * Optional typed processors for transforming inputs/outputs before they are recorded on a run. + * + * When set, the processors in [TraceProcessIO] replace the default input/output serialization. + * The generic type parameters on [TraceProcessIO] control what the processor callbacks receive + * — see [TraceProcessIO] for details. + * + * ```java + * TraceProcessIO process = TraceProcessIO.builder() + * .processInputs(input -> Map.of("query", input)) + * .processOutputs(resp -> Map.of("answer", resp.getText())) + * .build(); + * TraceConfig config = TraceConfig.builder() + * .name("my-run") + * .processTracedIO(process) + * .build(); + * ``` + * + * @see TraceProcessIO + */ + val processTracedIO: TraceProcessIO<*, *>? = null, ) { companion object { /** Creates a new [Builder] for constructing a [TraceConfig]. */ @@ -250,9 +271,6 @@ class TraceConfig( * .name("my-run") * .client(LangsmithOkHttpClient.fromEnv()) * .runType(RunType.LLM) - * .metadata(Map.of("version", "1.0")) - * .tags(List.of("prod")) - * .projectName("my-project") * .build(); * ``` */ @@ -265,6 +283,7 @@ class TraceConfig( private var projectName: String? = null private var executor: ExecutorService? = null private var tracingEnabled: Boolean? = null + private var processTracedIO: TraceProcessIO<*, *>? = null @JvmSynthetic internal fun from(config: TraceConfig) = apply { @@ -276,6 +295,7 @@ class TraceConfig( projectName = config.projectName executor = config.executor tracingEnabled = config.tracingEnabled + processTracedIO = config.processTracedIO } /** The name of the run, displayed in LangSmith. */ @@ -302,6 +322,16 @@ class TraceConfig( /** Whether tracing is active. Inherited by children if not set. */ fun tracingEnabled(tracingEnabled: Boolean) = apply { this.tracingEnabled = tracingEnabled } + /** + * Typed processors for transforming inputs/outputs before they are recorded. + * + * @see TraceConfig.processTracedIO + * @see TraceProcessIO + */ + fun processTracedIO(processTracedIO: TraceProcessIO<*, *>) = apply { + this.processTracedIO = processTracedIO + } + /** Builds the [TraceConfig]. */ fun build() = TraceConfig( @@ -313,12 +343,21 @@ class TraceConfig( projectName = projectName, executor = executor, tracingEnabled = tracingEnabled, + processTracedIO = processTracedIO, ) } } private const val DEFAULT_RUN_NAME = "" +/** Applies processInputs from the config, or returns null if not set. */ +private fun applyProcessInputs(config: TraceConfig, value: Any?): Map? = + config.processTracedIO?.inputsFn?.apply(value) + +/** Applies processOutputs from the config, or returns null if not set. */ +private fun applyProcessOutputs(config: TraceConfig, value: Any?): Map? = + config.processTracedIO?.outputsFn?.apply(value) + /** Resolves the run name from the config and the function being wrapped. */ private fun resolveName(config: TraceConfig, block: Any?): String { config.name?.let { @@ -328,6 +367,12 @@ private fun resolveName(config: TraceConfig, block: Any?): String { return DEFAULT_RUN_NAME } +/** Creates a copy of [config] with the resolved name set. */ +private fun resolveConfig(config: TraceConfig, block: Any?): TraceConfig { + val name = resolveName(config, block) + return if (name == config.name) config else config.toBuilder().name(name).build() +} + /** * Wraps a no-arg function with LangSmith tracing (Kotlin). * @@ -339,14 +384,22 @@ private fun resolveName(config: TraceConfig, block: Any?): String { */ @JvmSynthetic fun traceable(block: () -> O, config: TraceConfig): () -> O { - val resolvedConfig = config.toBuilder().name(resolveName(config, block)).build() - return { executeTraced(resolvedConfig, emptyMap()) { block() } } + val resolvedConfig = resolveConfig(config, block) + return { + val packed = emptyMap() + val serializedInputs = applyProcessInputs(resolvedConfig, packed) ?: packed + executeTraced(resolvedConfig, serializedInputs) { block() } + } } /** Wraps a no-arg function with LangSmith tracing (Java [Supplier]). */ fun traceable(block: Supplier, config: TraceConfig): Supplier { - val resolvedConfig = config.toBuilder().name(resolveName(config, block)).build() - return Supplier { executeTraced(resolvedConfig, emptyMap()) { block.get() } } + val resolvedConfig = resolveConfig(config, block) + return Supplier { + val packed = emptyMap() + val serializedInputs = applyProcessInputs(resolvedConfig, packed) ?: packed + executeTraced(resolvedConfig, serializedInputs) { block.get() } + } } /** @@ -393,10 +446,10 @@ fun traceable(block: Supplier, config: TraceConfig): Supplier { */ @JvmSynthetic fun traceable(block: (I) -> O, config: TraceConfig): (I) -> O { - val resolvedConfig = config.toBuilder().name(resolveName(config, block)).build() + val resolvedConfig = resolveConfig(config, block) return { input -> - val inputs = toInputMap(input) - executeTraced(resolvedConfig, inputs) { block(input) } + val serializedInputs = applyProcessInputs(resolvedConfig, input) ?: toInputMap(input) + executeTraced(resolvedConfig, serializedInputs) { block(input) } } } @@ -409,10 +462,11 @@ fun traceable(block: Function, config: TraceConfig): Function /** Wraps a 2-arg function with LangSmith tracing (Kotlin). */ @JvmSynthetic fun traceable(block: (I1, I2) -> O, config: TraceConfig): (I1, I2) -> O { - val resolvedConfig = config.toBuilder().name(resolveName(config, block)).build() + val resolvedConfig = resolveConfig(config, block) return { i1, i2 -> - val inputs = mapOf("args" to listOf(i1, i2)) - executeTraced(resolvedConfig, inputs) { block(i1, i2) } + val packed = mapOf("args" to listOf(i1, i2)) + val serializedInputs = applyProcessInputs(resolvedConfig, packed) ?: packed + executeTraced(resolvedConfig, serializedInputs) { block(i1, i2) } } } @@ -428,10 +482,11 @@ fun traceable( /** Wraps a 3-arg function with LangSmith tracing (Kotlin). */ @JvmSynthetic fun traceable(block: (I1, I2, I3) -> O, config: TraceConfig): (I1, I2, I3) -> O { - val resolvedConfig = config.toBuilder().name(resolveName(config, block)).build() + val resolvedConfig = resolveConfig(config, block) return { i1, i2, i3 -> - val inputs = mapOf("args" to listOf(i1, i2, i3)) - executeTraced(resolvedConfig, inputs) { block(i1, i2, i3) } + val packed = mapOf("args" to listOf(i1, i2, i3)) + val serializedInputs = applyProcessInputs(resolvedConfig, packed) ?: packed + executeTraced(resolvedConfig, serializedInputs) { block(i1, i2, i3) } } } @@ -540,7 +595,7 @@ fun traceTriFunction( * * For best tracing results, pass [Map] inputs/outputs to [traceable]. Typed SDK objects (e.g. * `ChatCompletionCreateParams`) should be converted to maps by the caller — use - * `processInputs`/`processOutputs` callbacks (when available) or manual conversion. + * [TraceConfig.processTracedIO] callbacks or manual conversion. */ private fun serializeValue(value: Any?): Any? = when (value) { @@ -630,7 +685,7 @@ private fun executeTraced(config: TraceConfig, inputs: Map?, b try { val result = block() run.endTime = nowIso() - run.outputs = toOutputMap(result) + run.outputs = applyProcessOutputs(config, result) ?: toOutputMap(result) run.patchRun() result } catch (e: Throwable) { diff --git a/langsmith-java-core/src/test/java/com/langchain/smith/tracing/TraceableJavaTest.java b/langsmith-java-core/src/test/java/com/langchain/smith/tracing/TraceableJavaTest.java index 8a9b92753..b1fb55fe9 100644 --- a/langsmith-java-core/src/test/java/com/langchain/smith/tracing/TraceableJavaTest.java +++ b/langsmith-java-core/src/test/java/com/langchain/smith/tracing/TraceableJavaTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import com.langchain.smith.client.LangsmithClient; +import java.util.Collections; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; @@ -158,4 +159,50 @@ void tracingDisabled_getCurrentRunReturnsNull() { Function traced = Tracing.traceFunction(input -> Tracing.getCurrentRunTree(), disabled); assertThat(traced.apply("hello")).isNull(); } + + // ---- processInputs / processOutputs ---- + + @Test + void processInputs_viaProcessTracedIO() { + TraceConfig cfg = TraceConfig.builder() + .name("process-inputs-test") + .client(client) + .tracingEnabled(true) + .processTracedIO(TraceProcessIO.builder() + .processInputs(input -> Collections.singletonMap("query", input)) + .build()) + .build(); + Function traced = Tracing.traceFunction(input -> Tracing.getCurrentRunTree(), cfg); + RunTree run = traced.apply("hello"); + assertThat(run.getInputs()).containsEntry("query", "hello"); + } + + @Test + void processOutputs_viaProcessTracedIO() { + TraceConfig cfg = TraceConfig.builder() + .name("process-outputs-test") + .client(client) + .tracingEnabled(true) + .processTracedIO(TraceProcessIO.builder() + .processOutputs(output -> Collections.singletonMap("answer", output)) + .build()) + .build(); + Function traced = Tracing.traceFunction(input -> "result", cfg); + traced.apply("hello"); + } + + @Test + void processInputsAndOutputs_together() { + TraceConfig cfg = TraceConfig.builder() + .name("both-processors") + .client(client) + .tracingEnabled(true) + .processTracedIO(TraceProcessIO.builder() + .processInputs(input -> Collections.singletonMap("q", input)) + .processOutputs(output -> Collections.singletonMap("a", output)) + .build()) + .build(); + Function traced = Tracing.traceFunction(input -> "answer", cfg); + assertThat(traced.apply("question")).isEqualTo("answer"); + } } diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt index 9f8dffc1a..197095e86 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt @@ -1,6 +1,20 @@ package com.langchain.smith.tracing +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.langchain.smith.client.okhttp.LangsmithOkHttpClient +import com.openai.client.okhttp.OpenAIOkHttpClient +import com.openai.core.JsonValue +import com.openai.models.ChatModel +import com.openai.models.FunctionDefinition +import com.openai.models.FunctionParameters +import com.openai.models.chat.completions.ChatCompletion +import com.openai.models.chat.completions.ChatCompletionCreateParams +import com.openai.models.chat.completions.ChatCompletionFunctionTool +import com.openai.models.chat.completions.ChatCompletionMessage +import com.openai.models.chat.completions.ChatCompletionMessageParam +import com.openai.models.chat.completions.ChatCompletionToolMessageParam +import java.util.function.Function as JFunction import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy @@ -9,6 +23,100 @@ import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance +private val testJsonMapper = jacksonObjectMapper() + +private fun toJsonMap(value: Any): Map = + testJsonMapper.convertValue(value, object : TypeReference>() {}) + +private fun weatherTool(): ChatCompletionFunctionTool = + ChatCompletionFunctionTool.builder() + .function( + FunctionDefinition.builder() + .name("get_weather") + .description("Get the weather for a location") + .parameters( + FunctionParameters.builder() + .putAdditionalProperty("type", JsonValue.from("object")) + .putAdditionalProperty( + "properties", + JsonValue.from( + mapOf( + "location" to + mapOf( + "type" to "string", + "description" to + "City and state, e.g. San Francisco, CA", + ) + ) + ), + ) + .putAdditionalProperty("required", JsonValue.from(listOf("location"))) + .build() + ) + .build() + ) + .build() + +private fun buildToolLoopParams( + messages: List +): ChatCompletionCreateParams = + ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .messages(messages) + .addTool(weatherTool()) + .maxCompletionTokens(150) + .build() + +private fun toolLoopInputMap(params: ChatCompletionCreateParams): Map = + mapOf( + "model" to params.model().toString(), + "messages" to params.messages().map { toJsonMap(it) }, + "tools" to params.tools().getOrNull()?.map { toJsonMap(it) }, + ) + +private fun toolLoopOutputMap(completion: ChatCompletion): Map = + mapOf( + "id" to completion.id(), + "model" to completion.model().toString(), + "choices" to + completion.choices().map { choice -> + mapOf( + "finish_reason" to choice.finishReason().toString(), + "message" to toJsonMap(choice.message()), + ) + }, + ) + +private fun userMessage(content: String): ChatCompletionMessageParam = + ChatCompletionMessageParam.ofUser( + com.openai.models.chat.completions.ChatCompletionUserMessageParam.builder() + .content(content) + .build() + ) + +private fun assistantMessage(message: ChatCompletionMessage): ChatCompletionMessageParam = + ChatCompletionMessageParam.ofAssistant(message.toParam()) + +private fun toolMessage(toolCallId: String, result: Map): ChatCompletionMessageParam = + ChatCompletionMessageParam.ofTool( + ChatCompletionToolMessageParam.builder() + .toolCallId(toolCallId) + .contentAsJson(result) + .build() + ) + +private fun toolResult(argumentsJson: String): Map = + mapOf( + "tool" to "get_weather", + "arguments_json" to argumentsJson, + "location" to "San Francisco, CA", + "forecast" to "sunny", + "temperature_f" to 72, + ) + +private fun finalContent(message: ChatCompletionMessage): String = + message.content().getOrNull() ?: "" + /** * Integration tests for [traceable] that post real runs to LangSmith. * @@ -32,7 +140,7 @@ internal class TraceableTest { runType: RunType = RunType.CHAIN, metadata: Map? = null, tags: List? = null, - ) = + ): TraceConfig = TraceConfig( name = name, client = client, @@ -128,49 +236,97 @@ internal class TraceableTest { } @Test - fun traceableWithOpenAiCall() { + fun traceableWithOpenAiToolLoop_usesProcessInputsAndOutputs() { assumeTrue( !System.getenv("OPENAI_API_KEY").isNullOrBlank(), "Skipping: OPENAI_API_KEY must be set", ) - val openai = com.openai.client.okhttp.OpenAIOkHttpClient.fromEnv() + val openai = OpenAIOkHttpClient.fromEnv() + var capturedLlmRun: RunTree? = null + var capturedAgentRun: RunTree? = null val callOpenAi = traceable( - { question: String -> - val completion = - openai - .chat() - .completions() - .create( - com.openai.models.chat.completions.ChatCompletionCreateParams - .builder() - .model(com.openai.models.ChatModel.GPT_4_1_MINI) - .addUserMessage("$question Answer in one word.") - .maxCompletionTokens(10) - .build() - ) - completion.choices()[0].message().content().orElse("") + { params: ChatCompletionCreateParams -> + capturedLlmRun = getCurrentRunTree() + openai.chat().completions().create(params) }, - config("call-openai", runType = RunType.LLM), + TraceConfig( + name = "call-openai-tool-loop", + client = client, + runType = RunType.LLM, + projectName = "traceable-java-tests", + tracingEnabled = true, + processTracedIO = + TraceProcessIO( + processInputs = JFunction(::toolLoopInputMap), + processOutputs = JFunction(::toolLoopOutputMap), + ), + ), ) - val formatAnswer = - traceable({ answer: String -> "The answer is: $answer" }, config("format-answer")) + val executeTool = + traceable( + { argumentsJson: String -> toolResult(argumentsJson) }, + config("get_weather", runType = RunType.TOOL), + ) val agent = traceable( - { input: Map -> - val answer = callOpenAi(input["question"] as String) - formatAnswer(answer) + { question: String -> + capturedAgentRun = getCurrentRunTree() + val messages = mutableListOf() + messages += + userMessage( + "$question Use the get_weather tool and then answer succinctly." + ) + + repeat(3) { + val completion = callOpenAi(buildToolLoopParams(messages)) + val message = completion.choices()[0].message() + val toolCalls = message.toolCalls().getOrNull().orEmpty() + + if (toolCalls.isEmpty()) { + return@traceable finalContent(message) + } + + messages += assistantMessage(message) + toolCalls.forEach { toolCall -> + val fn = toolCall.asFunction() + val result = executeTool(fn.function().arguments()) + messages += toolMessage(fn.id(), result) + } + } + + error("Model did not finish tool loop in time") }, - config("openai-agent"), + TraceConfig( + name = "openai-tool-loop-agent", + client = client, + projectName = "traceable-java-tests", + tracingEnabled = true, + processTracedIO = + TraceProcessIO( + processInputs = + JFunction { question: String -> mapOf("question" to question) }, + processOutputs = + JFunction { answer: String -> mapOf("answer" to answer) }, + ), + ), ) - val result = agent(mapOf("question" to "What is 2+2?")) - println("[Traceable+OpenAI] Result: $result") - + val result = agent("What is the weather in San Francisco?") + assertThat(result).isNotBlank() + assertThat(capturedAgentRun).isNotNull + assertThat(capturedAgentRun!!.inputs) + .isEqualTo(mapOf("question" to "What is the weather in San Francisco?")) + assertThat(capturedAgentRun!!.outputs).isEqualTo(mapOf("answer" to result)) + assertThat(capturedLlmRun).isNotNull + assertThat(capturedLlmRun!!.inputs).containsKeys("model", "messages", "tools") + assertThat(capturedLlmRun!!.outputs).containsKeys("id", "model", "choices") + + println("[Traceable+OpenAI Tool Loop] Result: $result") awaitPendingRuns() } diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableUnitTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableUnitTest.kt index 8fb209eb6..80d2e6e47 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableUnitTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableUnitTest.kt @@ -1,6 +1,7 @@ package com.langchain.smith.tracing import com.langchain.smith.client.LangsmithClient +import java.util.function.Function import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.mockito.kotlin.mock @@ -13,9 +14,29 @@ internal class TraceableUnitTest { private val client: LangsmithClient = mock() - private fun config(name: String) = + private fun config(name: String): TraceConfig = TraceConfig(name = name, client = client, tracingEnabled = true) + /** Shorthand for creating a [TraceConfig] without processors in tests. */ + private fun cfg( + name: String, + client: LangsmithClient? = null, + runType: RunType = RunType.CHAIN, + metadata: Map? = null, + tags: List? = null, + projectName: String? = null, + tracingEnabled: Boolean? = null, + ): TraceConfig = + TraceConfig( + name = name, + client = client, + runType = runType, + metadata = metadata, + tags = tags, + projectName = projectName, + tracingEnabled = tracingEnabled, + ) + // ---- Helpers ---- /** Traces a 1-arg function, invokes it, and returns the captured [RunTree]. */ @@ -181,7 +202,7 @@ internal class TraceableUnitTest { @Test fun childInheritsClientFromParent() { - val childRun = traceChild(TraceConfig("child")) + val childRun = traceChild(cfg("child")) assertThat(childRun.name).isEqualTo("child") } @@ -194,12 +215,12 @@ internal class TraceableUnitTest { childRun = getCurrentRunTree() "child" }, - TraceConfig("child"), + cfg("child"), ) val parent = traceable( { _: Unit -> child(Unit) }, - TraceConfig( + cfg( name = "parent", client = client, projectName = "inherited-project", @@ -219,12 +240,12 @@ internal class TraceableUnitTest { childRun = getCurrentRunTree() "child" }, - TraceConfig("child", projectName = "child-project"), + cfg("child", projectName = "child-project"), ) val parent = traceable( { _: Unit -> child(Unit) }, - TraceConfig( + cfg( name = "parent", client = client, projectName = "parent-project", @@ -237,13 +258,13 @@ internal class TraceableUnitTest { @Test fun childInheritsTracingEnabledFromParent() { - val childRun = traceChild(TraceConfig("child")) + val childRun = traceChild(cfg("child")) assertThat(childRun.name).isEqualTo("child") } @Test fun childCanDisableTracing() { - val childRun = traceChild(TraceConfig("child", tracingEnabled = false)) + val childRun = traceChild(cfg("child", tracingEnabled = false)) // Child disabled tracing — no new run is created, so getCurrentRunTree() returns parent. assertThat(childRun.name).isEqualTo("parent") } @@ -253,49 +274,46 @@ internal class TraceableUnitTest { @Test fun createChild_inheritsTraceId() { val parent = rootRun() - val child = parent.createChild(TraceConfig("child")) + val child = parent.createChild(cfg("child")) assertThat(child.traceId).isEqualTo(parent.traceId) } @Test fun createChild_setsParentRunId() { val parent = rootRun() - assertThat(parent.createChild(TraceConfig("child")).parentRunId).isEqualTo(parent.id) + assertThat(parent.createChild(cfg("child")).parentRunId).isEqualTo(parent.id) } @Test fun createChild_extendsDottedOrder() { val parent = rootRun() - assertThat(parent.createChild(TraceConfig("child")).dottedOrder) + assertThat(parent.createChild(cfg("child")).dottedOrder) .startsWith(parent.dottedOrder + ".") } @Test fun createChild_inheritsProjectName() { val parent = rootRun(projectName = "inherited-project") - assertThat(parent.createChild(TraceConfig("child")).projectName) - .isEqualTo("inherited-project") + assertThat(parent.createChild(cfg("child")).projectName).isEqualTo("inherited-project") } @Test fun createChild_overridesProjectName() { val parent = rootRun(projectName = "parent-project") - assertThat( - parent.createChild(TraceConfig("child", projectName = "child-project")).projectName - ) + assertThat(parent.createChild(cfg("child", projectName = "child-project")).projectName) .isEqualTo("child-project") } @Test fun createChild_inheritsClient() { val parent = rootRun() - assertThat(parent.createChild(TraceConfig("child")).client).isSameAs(parent.client) + assertThat(parent.createChild(cfg("child")).client).isSameAs(parent.client) } @Test fun createChild_overridesClient() { val otherClient: LangsmithClient = mock() - val child = rootRun().createChild(TraceConfig("child", client = otherClient)) + val child = rootRun().createChild(cfg("child", client = otherClient)) assertThat(child.client).isSameAs(otherClient) } @@ -304,7 +322,7 @@ internal class TraceableUnitTest { val parent = rootRun(metadata = mapOf("shared" to "parent", "parent_only" to "yes")) val child = parent.createChild( - TraceConfig("child", metadata = mapOf("shared" to "child", "child_only" to "yes")) + cfg("child", metadata = mapOf("shared" to "child", "child_only" to "yes")) ) assertThat(child.metadata) .containsEntry("shared", "child") @@ -315,30 +333,30 @@ internal class TraceableUnitTest { @Test fun createChild_inheritsMetadata_whenChildHasNone() { val parent = rootRun(metadata = mapOf("key" to "value")) - assertThat(parent.createChild(TraceConfig("child")).metadata).containsEntry("key", "value") + assertThat(parent.createChild(cfg("child")).metadata).containsEntry("key", "value") } @Test fun createChild_mergesTags() { val parent = rootRun(tags = listOf("parent-tag")) - assertThat(parent.createChild(TraceConfig("child", tags = listOf("child-tag"))).tags) + assertThat(parent.createChild(cfg("child", tags = listOf("child-tag"))).tags) .containsExactly("parent-tag", "child-tag") } @Test fun createChild_inheritsTags_whenChildHasNone() { val parent = rootRun(tags = listOf("parent-tag")) - assertThat(parent.createChild(TraceConfig("child")).tags).containsExactly("parent-tag") + assertThat(parent.createChild(cfg("child")).tags).containsExactly("parent-tag") } @Test fun createChild_defaultsInputsToNull() { - assertThat(rootRun().createChild(TraceConfig("child")).inputs).isNull() + assertThat(rootRun().createChild(cfg("child")).inputs).isNull() } @Test fun createChild_setsNameAndRunType() { - val child = rootRun().createChild(TraceConfig("my-tool", runType = RunType.TOOL)) + val child = rootRun().createChild(cfg("my-tool", runType = RunType.TOOL)) assertThat(child.name).isEqualTo("my-tool") assertThat(child.runType).isEqualTo(RunType.TOOL) } @@ -346,17 +364,129 @@ internal class TraceableUnitTest { @Test fun createChild_generatesUniqueIds() { val parent = rootRun() - val child1 = parent.createChild(TraceConfig("child-1")) - val child2 = parent.createChild(TraceConfig("child-2")) + val child1 = parent.createChild(cfg("child-1")) + val child2 = parent.createChild(cfg("child-2")) assertThat(child1.id).isNotEqualTo(child2.id) assertThat(child1.dottedOrder).isNotEqualTo(child2.dottedOrder) } @Test fun createChild_startsWithEmptyOutputsAndNoError() { - val child = rootRun().createChild(TraceConfig("child")) + val child = rootRun().createChild(cfg("child")) assertThat(child.outputs).isNull() assertThat(child.error).isNull() assertThat(child.endTime).isNull() } + + // ---- processInputs / processOutputs ---- + + @Test + fun processInputs_receivesRawTypedInput() { + var run: RunTree? = null + val cfg = + TraceConfig( + name = "test", + client = client, + tracingEnabled = true, + processTracedIO = + TraceProcessIO( + processInputs = Function { input -> mapOf("query" to input) } + ), + ) + val traced = + traceable( + { _: String -> + run = getCurrentRunTree() + "ok" + }, + cfg, + ) + traced("hello") + assertThat(run!!.inputs).isEqualTo(mapOf("query" to "hello")) + } + + @Test + fun processOutputs_receivesRawTypedOutput() { + var run: RunTree? = null + val cfg = + TraceConfig( + name = "test", + client = client, + tracingEnabled = true, + processTracedIO = + TraceProcessIO( + processOutputs = Function { output -> mapOf("answer" to output) } + ), + ) + val traced = + traceable( + { _: String -> + run = getCurrentRunTree() + "result" + }, + cfg, + ) + traced("hello") + assertThat(run!!.outputs).isEqualTo(mapOf("answer" to "result")) + } + + @Test + fun processInputs_bypassesDefaultSerialization() { + var run: RunTree? = null + val cfg = + TraceConfig( + name = "test", + client = client, + tracingEnabled = true, + processTracedIO = + TraceProcessIO( + processInputs = Function { input -> mapOf("custom_key" to input) } + ), + ) + val traced = + traceable( + { _: String -> + run = getCurrentRunTree() + "ok" + }, + cfg, + ) + traced("hello") + // Without processTracedIO, this would be {"inputs": "hello"}. + assertThat(run!!.inputs).isEqualTo(mapOf("custom_key" to "hello")) + } + + @Test + fun processInputs_andProcessOutputs_bothApplied() { + var run: RunTree? = null + val cfg = + TraceConfig( + name = "test", + client = client, + tracingEnabled = true, + processTracedIO = + TraceProcessIO( + processInputs = Function { mapOf("q" to it) }, + processOutputs = Function { mapOf("a" to it) }, + ), + ) + val traced = + traceable( + { _: String -> + run = getCurrentRunTree() + "answer" + }, + cfg, + ) + traced("question") + assertThat(run!!.inputs).isEqualTo(mapOf("q" to "question")) + assertThat(run!!.outputs).isEqualTo(mapOf("a" to "answer")) + } + + @Test + fun noProcessors_defaultSerializationUnchanged() { + // Sanity check: without processors, behavior is identical to before. + assertThat(traceAndCapture("hello").inputs).isEqualTo(mapOf("inputs" to "hello")) + assertThat(traceWithOutput("world").outputs).isEqualTo(mapOf("outputs" to "world")) + } } diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableWireTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableWireTest.kt index 851ad3d07..a5db78158 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableWireTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableWireTest.kt @@ -17,9 +17,28 @@ internal class TraceableWireTest { private val client: LangsmithClient = mock() - private fun config(name: String) = + private fun config(name: String): TraceConfig = TraceConfig(name = name, client = client, tracingEnabled = true) + private fun cfg( + name: String, + client: LangsmithClient? = null, + runType: RunType = RunType.CHAIN, + metadata: Map? = null, + tags: List? = null, + projectName: String? = null, + tracingEnabled: Boolean? = null, + ): TraceConfig = + TraceConfig( + name = name, + client = client, + runType = runType, + metadata = metadata, + tags = tags, + projectName = projectName, + tracingEnabled = tracingEnabled, + ) + // ---- Basic tracing ---- @Test @@ -52,7 +71,7 @@ internal class TraceableWireTest { run = getCurrentRunTree() "result" }, - TraceConfig( + cfg( "wire-test", client = client, tracingEnabled = true, @@ -94,7 +113,7 @@ internal class TraceableWireTest { child1Run = getCurrentRunTree() "c1" }, - TraceConfig("child-1"), + cfg("child-1"), ) val child2 = traceable( @@ -102,7 +121,7 @@ internal class TraceableWireTest { child2Run = getCurrentRunTree() "c2" }, - TraceConfig("child-2"), + cfg("child-2"), ) val parent = traceable( @@ -136,7 +155,7 @@ internal class TraceableWireTest { l3 = getCurrentRunTree() "deep" }, - TraceConfig("level-3"), + cfg("level-3"), ) val level2 = traceable( @@ -144,7 +163,7 @@ internal class TraceableWireTest { l2 = getCurrentRunTree() level3(Unit) }, - TraceConfig("level-2"), + cfg("level-2"), ) val level1 = traceable( @@ -171,7 +190,7 @@ internal class TraceableWireTest { childRun = getCurrentRunTree() "child" }, - TraceConfig("child"), + cfg("child"), ) val parent = traceable({ _: Unit -> child(Unit) }, config("parent")) parent(Unit) @@ -213,7 +232,7 @@ internal class TraceableWireTest { val traced = traceable( { input: Int -> input * 2 }, - TraceConfig("error-test", client = errorClient, tracingEnabled = true), + cfg("error-test", client = errorClient, tracingEnabled = true), ) val result = traced(5) @@ -255,7 +274,7 @@ internal class TraceableWireTest { childRun = getCurrentRunTree() "child-result" }, - TraceConfig("child"), + cfg("child"), ) val parent = traceable( @@ -283,7 +302,7 @@ internal class TraceableWireTest { run!!.metadata["dynamic"] = "added" "ok" }, - TraceConfig( + cfg( "meta-test", client = client, tracingEnabled = true, @@ -310,12 +329,7 @@ internal class TraceableWireTest { run!!.tags.add("dynamic-tag") "ok" }, - TraceConfig( - "tag-test", - client = client, - tracingEnabled = true, - tags = listOf("static-tag"), - ), + cfg("tag-test", client = client, tracingEnabled = true, tags = listOf("static-tag")), ) traced(Unit) @@ -334,7 +348,7 @@ internal class TraceableWireTest { run = getCurrentRunTree() "ok" }, - TraceConfig("disabled", client = client, tracingEnabled = false), + cfg("disabled", client = client, tracingEnabled = false), ) val result = traced(Unit) @@ -371,17 +385,12 @@ internal class TraceableWireTest { childRun = getCurrentRunTree() "child" }, - TraceConfig("child"), + cfg("child"), ) val parent = traceable( { _: Unit -> child(Unit) }, - TraceConfig( - "parent", - client = client, - tracingEnabled = true, - projectName = "my-project", - ), + cfg("parent", client = client, tracingEnabled = true, projectName = "my-project"), ) parent(Unit) From cf75a21c3803cdb6b3f7939f926813ac3789ca1f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 27 Mar 2026 19:13:44 +0000 Subject: [PATCH 14/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index 724c7353b..8757055ce 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-3dc7535bcdd9c57fee8362d4866efd19f75e182cf57a10e475049b4c92af56ff.yml -openapi_spec_hash: 781bbf1531d6cdfb7371b4594e9f809d +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-9c89dd3a580be0b2119fb717ee4ee3fbb43a2077ba8541bc8588f7f3c4abe2b7.yml +openapi_spec_hash: 46a0e048a6adc27c4ebc2fd03b070c0a config_hash: 787a12876983a14bce67ed57899e4a94 From 49bc0202dddb954d5f1ee3683c0c8fcd1497ba58 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 27 Mar 2026 20:13:47 +0000 Subject: [PATCH 15/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index 8757055ce..15eebca5a 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-9c89dd3a580be0b2119fb717ee4ee3fbb43a2077ba8541bc8588f7f3c4abe2b7.yml -openapi_spec_hash: 46a0e048a6adc27c4ebc2fd03b070c0a +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-3baf0b5b3249e3e46c4b933ff62824a9096b4b6ead7b45f1779d96670bdd68b9.yml +openapi_spec_hash: 6621ca9c214ce3afdd12917a3d9ae7c0 config_hash: 787a12876983a14bce67ed57899e4a94 From 979e8af2b6f01444bcea33e1e09d1acbc986a6be Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 27 Mar 2026 21:13:37 +0000 Subject: [PATCH 16/35] feat(api): api update --- .stats.yml | 4 +- .../RunSchemaWithAnnotationQueueInfo.kt | 84 ++++++++++++++++++- .../RunSchemaWithAnnotationQueueInfoTest.kt | 6 ++ 3 files changed, 91 insertions(+), 3 deletions(-) diff --git a/.stats.yml b/.stats.yml index 15eebca5a..2676ddc84 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-3baf0b5b3249e3e46c4b933ff62824a9096b4b6ead7b45f1779d96670bdd68b9.yml -openapi_spec_hash: 6621ca9c214ce3afdd12917a3d9ae7c0 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-923e5b272457a65d68f7e43030dd0db3a9abfa79bded7832a0e54771c8757671.yml +openapi_spec_hash: c0d627562d35dcf4b5823c4f5a2d4fba config_hash: 787a12876983a14bce67ed57899e4a94 diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfo.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfo.kt index df3073419..d1d7f66ce 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfo.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfo.kt @@ -37,6 +37,7 @@ private constructor( private val traceId: JsonField, private val addedAt: JsonField, private val childRunIds: JsonField>, + private val completedCount: JsonField, private val completionCost: JsonField, private val completionCostDetails: JsonField, private val completionTokenDetails: JsonField, @@ -71,6 +72,7 @@ private constructor( private val promptTokens: JsonField, private val referenceDatasetId: JsonField, private val referenceExampleId: JsonField, + private val reservationCount: JsonField, private val s3Urls: JsonField, private val serialized: JsonField, private val shareToken: JsonField, @@ -111,6 +113,9 @@ private constructor( @JsonProperty("child_run_ids") @ExcludeMissing childRunIds: JsonField> = JsonMissing.of(), + @JsonProperty("completed_count") + @ExcludeMissing + completedCount: JsonField = JsonMissing.of(), @JsonProperty("completion_cost") @ExcludeMissing completionCost: JsonField = JsonMissing.of(), @@ -203,6 +208,9 @@ private constructor( @JsonProperty("reference_example_id") @ExcludeMissing referenceExampleId: JsonField = JsonMissing.of(), + @JsonProperty("reservation_count") + @ExcludeMissing + reservationCount: JsonField = JsonMissing.of(), @JsonProperty("s3_urls") @ExcludeMissing s3Urls: JsonField = JsonMissing.of(), @JsonProperty("serialized") @ExcludeMissing @@ -247,6 +255,7 @@ private constructor( traceId, addedAt, childRunIds, + completedCount, completionCost, completionCostDetails, completionTokenDetails, @@ -281,6 +290,7 @@ private constructor( promptTokens, referenceDatasetId, referenceExampleId, + reservationCount, s3Urls, serialized, shareToken, @@ -366,6 +376,12 @@ private constructor( */ fun childRunIds(): Optional> = childRunIds.getOptional("child_run_ids") + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun completedCount(): Optional = completedCount.getOptional("completed_count") + /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). @@ -579,6 +595,12 @@ private constructor( fun referenceExampleId(): Optional = referenceExampleId.getOptional("reference_example_id") + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun reservationCount(): Optional = reservationCount.getOptional("reservation_count") + /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). @@ -747,6 +769,15 @@ private constructor( @ExcludeMissing fun _childRunIds(): JsonField> = childRunIds + /** + * Returns the raw JSON value of [completedCount]. + * + * Unlike [completedCount], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("completed_count") + @ExcludeMissing + fun _completedCount(): JsonField = completedCount + /** * Returns the raw JSON value of [completionCost]. * @@ -1043,6 +1074,16 @@ private constructor( @ExcludeMissing fun _referenceExampleId(): JsonField = referenceExampleId + /** + * Returns the raw JSON value of [reservationCount]. + * + * Unlike [reservationCount], this method doesn't throw if the JSON field has an unexpected + * type. + */ + @JsonProperty("reservation_count") + @ExcludeMissing + fun _reservationCount(): JsonField = reservationCount + /** * Returns the raw JSON value of [s3Urls]. * @@ -1204,6 +1245,7 @@ private constructor( private var traceId: JsonField? = null private var addedAt: JsonField = JsonMissing.of() private var childRunIds: JsonField>? = null + private var completedCount: JsonField = JsonMissing.of() private var completionCost: JsonField = JsonMissing.of() private var completionCostDetails: JsonField = JsonMissing.of() private var completionTokenDetails: JsonField = JsonMissing.of() @@ -1238,6 +1280,7 @@ private constructor( private var promptTokens: JsonField = JsonMissing.of() private var referenceDatasetId: JsonField = JsonMissing.of() private var referenceExampleId: JsonField = JsonMissing.of() + private var reservationCount: JsonField = JsonMissing.of() private var s3Urls: JsonField = JsonMissing.of() private var serialized: JsonField = JsonMissing.of() private var shareToken: JsonField = JsonMissing.of() @@ -1269,6 +1312,7 @@ private constructor( addedAt = runSchemaWithAnnotationQueueInfo.addedAt childRunIds = runSchemaWithAnnotationQueueInfo.childRunIds.map { it.toMutableList() } + completedCount = runSchemaWithAnnotationQueueInfo.completedCount completionCost = runSchemaWithAnnotationQueueInfo.completionCost completionCostDetails = runSchemaWithAnnotationQueueInfo.completionCostDetails completionTokenDetails = runSchemaWithAnnotationQueueInfo.completionTokenDetails @@ -1305,6 +1349,7 @@ private constructor( promptTokens = runSchemaWithAnnotationQueueInfo.promptTokens referenceDatasetId = runSchemaWithAnnotationQueueInfo.referenceDatasetId referenceExampleId = runSchemaWithAnnotationQueueInfo.referenceExampleId + reservationCount = runSchemaWithAnnotationQueueInfo.reservationCount s3Urls = runSchemaWithAnnotationQueueInfo.s3Urls serialized = runSchemaWithAnnotationQueueInfo.serialized shareToken = runSchemaWithAnnotationQueueInfo.shareToken @@ -1460,6 +1505,19 @@ private constructor( } } + fun completedCount(completedCount: Long) = completedCount(JsonField.of(completedCount)) + + /** + * Sets [Builder.completedCount] to an arbitrary JSON value. + * + * You should usually call [Builder.completedCount] with a well-typed [Long] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun completedCount(completedCount: JsonField) = apply { + this.completedCount = completedCount + } + fun completionCost(completionCost: String?) = completionCost(JsonField.ofNullable(completionCost)) @@ -2076,6 +2134,20 @@ private constructor( this.referenceExampleId = referenceExampleId } + fun reservationCount(reservationCount: Long) = + reservationCount(JsonField.of(reservationCount)) + + /** + * Sets [Builder.reservationCount] to an arbitrary JSON value. + * + * You should usually call [Builder.reservationCount] with a well-typed [Long] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun reservationCount(reservationCount: JsonField) = apply { + this.reservationCount = reservationCount + } + fun s3Urls(s3Urls: S3Urls?) = s3Urls(JsonField.ofNullable(s3Urls)) /** Alias for calling [Builder.s3Urls] with `s3Urls.orElse(null)`. */ @@ -2347,6 +2419,7 @@ private constructor( checkRequired("traceId", traceId), addedAt, (childRunIds ?: JsonMissing.of()).map { it.toImmutable() }, + completedCount, completionCost, completionCostDetails, completionTokenDetails, @@ -2381,6 +2454,7 @@ private constructor( promptTokens, referenceDatasetId, referenceExampleId, + reservationCount, s3Urls, serialized, shareToken, @@ -2417,6 +2491,7 @@ private constructor( traceId() addedAt() childRunIds() + completedCount() completionCost() completionCostDetails().ifPresent { it.validate() } completionTokenDetails().ifPresent { it.validate() } @@ -2451,6 +2526,7 @@ private constructor( promptTokens() referenceDatasetId() referenceExampleId() + reservationCount() s3Urls().ifPresent { it.validate() } serialized().ifPresent { it.validate() } shareToken() @@ -2494,6 +2570,7 @@ private constructor( (if (traceId.asKnown().isPresent) 1 else 0) + (if (addedAt.asKnown().isPresent) 1 else 0) + (childRunIds.asKnown().getOrNull()?.size ?: 0) + + (if (completedCount.asKnown().isPresent) 1 else 0) + (if (completionCost.asKnown().isPresent) 1 else 0) + (completionCostDetails.asKnown().getOrNull()?.validity() ?: 0) + (completionTokenDetails.asKnown().getOrNull()?.validity() ?: 0) + @@ -2528,6 +2605,7 @@ private constructor( (if (promptTokens.asKnown().isPresent) 1 else 0) + (if (referenceDatasetId.asKnown().isPresent) 1 else 0) + (if (referenceExampleId.asKnown().isPresent) 1 else 0) + + (if (reservationCount.asKnown().isPresent) 1 else 0) + (s3Urls.asKnown().getOrNull()?.validity() ?: 0) + (serialized.asKnown().getOrNull()?.validity() ?: 0) + (if (shareToken.asKnown().isPresent) 1 else 0) + @@ -4085,6 +4163,7 @@ private constructor( traceId == other.traceId && addedAt == other.addedAt && childRunIds == other.childRunIds && + completedCount == other.completedCount && completionCost == other.completionCost && completionCostDetails == other.completionCostDetails && completionTokenDetails == other.completionTokenDetails && @@ -4119,6 +4198,7 @@ private constructor( promptTokens == other.promptTokens && referenceDatasetId == other.referenceDatasetId && referenceExampleId == other.referenceExampleId && + reservationCount == other.reservationCount && s3Urls == other.s3Urls && serialized == other.serialized && shareToken == other.shareToken && @@ -4149,6 +4229,7 @@ private constructor( traceId, addedAt, childRunIds, + completedCount, completionCost, completionCostDetails, completionTokenDetails, @@ -4183,6 +4264,7 @@ private constructor( promptTokens, referenceDatasetId, referenceExampleId, + reservationCount, s3Urls, serialized, shareToken, @@ -4204,5 +4286,5 @@ private constructor( override fun hashCode(): Int = hashCode override fun toString() = - "RunSchemaWithAnnotationQueueInfo{id=$id, appPath=$appPath, dottedOrder=$dottedOrder, name=$name, queueRunId=$queueRunId, runType=$runType, sessionId=$sessionId, status=$status, traceId=$traceId, addedAt=$addedAt, childRunIds=$childRunIds, completionCost=$completionCost, completionCostDetails=$completionCostDetails, completionTokenDetails=$completionTokenDetails, completionTokens=$completionTokens, directChildRunIds=$directChildRunIds, effectiveAddedAt=$effectiveAddedAt, endTime=$endTime, error=$error, events=$events, executionOrder=$executionOrder, extra=$extra, feedbackStats=$feedbackStats, firstTokenTime=$firstTokenTime, inDataset=$inDataset, inputs=$inputs, inputsPreview=$inputsPreview, inputsS3Urls=$inputsS3Urls, lastQueuedAt=$lastQueuedAt, lastReviewedTime=$lastReviewedTime, manifestId=$manifestId, manifestS3Id=$manifestS3Id, messages=$messages, outputs=$outputs, outputsPreview=$outputsPreview, outputsS3Urls=$outputsS3Urls, parentRunId=$parentRunId, parentRunIds=$parentRunIds, priceModelId=$priceModelId, promptCost=$promptCost, promptCostDetails=$promptCostDetails, promptTokenDetails=$promptTokenDetails, promptTokens=$promptTokens, referenceDatasetId=$referenceDatasetId, referenceExampleId=$referenceExampleId, s3Urls=$s3Urls, serialized=$serialized, shareToken=$shareToken, startTime=$startTime, tags=$tags, threadId=$threadId, totalCost=$totalCost, totalTokens=$totalTokens, traceFirstReceivedAt=$traceFirstReceivedAt, traceMaxStartTime=$traceMaxStartTime, traceMinStartTime=$traceMinStartTime, traceTier=$traceTier, traceUpgrade=$traceUpgrade, ttlSeconds=$ttlSeconds, additionalProperties=$additionalProperties}" + "RunSchemaWithAnnotationQueueInfo{id=$id, appPath=$appPath, dottedOrder=$dottedOrder, name=$name, queueRunId=$queueRunId, runType=$runType, sessionId=$sessionId, status=$status, traceId=$traceId, addedAt=$addedAt, childRunIds=$childRunIds, completedCount=$completedCount, completionCost=$completionCost, completionCostDetails=$completionCostDetails, completionTokenDetails=$completionTokenDetails, completionTokens=$completionTokens, directChildRunIds=$directChildRunIds, effectiveAddedAt=$effectiveAddedAt, endTime=$endTime, error=$error, events=$events, executionOrder=$executionOrder, extra=$extra, feedbackStats=$feedbackStats, firstTokenTime=$firstTokenTime, inDataset=$inDataset, inputs=$inputs, inputsPreview=$inputsPreview, inputsS3Urls=$inputsS3Urls, lastQueuedAt=$lastQueuedAt, lastReviewedTime=$lastReviewedTime, manifestId=$manifestId, manifestS3Id=$manifestS3Id, messages=$messages, outputs=$outputs, outputsPreview=$outputsPreview, outputsS3Urls=$outputsS3Urls, parentRunId=$parentRunId, parentRunIds=$parentRunIds, priceModelId=$priceModelId, promptCost=$promptCost, promptCostDetails=$promptCostDetails, promptTokenDetails=$promptTokenDetails, promptTokens=$promptTokens, referenceDatasetId=$referenceDatasetId, referenceExampleId=$referenceExampleId, reservationCount=$reservationCount, s3Urls=$s3Urls, serialized=$serialized, shareToken=$shareToken, startTime=$startTime, tags=$tags, threadId=$threadId, totalCost=$totalCost, totalTokens=$totalTokens, traceFirstReceivedAt=$traceFirstReceivedAt, traceMaxStartTime=$traceMaxStartTime, traceMinStartTime=$traceMinStartTime, traceTier=$traceTier, traceUpgrade=$traceUpgrade, ttlSeconds=$ttlSeconds, additionalProperties=$additionalProperties}" } diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfoTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfoTest.kt index d0fad5894..6137258f1 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfoTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfoTest.kt @@ -28,6 +28,7 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .traceId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .addedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .addChildRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .completedCount(0L) .completionCost("completion_cost") .completionCostDetails( RunSchemaWithAnnotationQueueInfo.CompletionCostDetails.builder() @@ -110,6 +111,7 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .promptTokens(0L) .referenceDatasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .referenceExampleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .reservationCount(0L) .s3Urls( RunSchemaWithAnnotationQueueInfo.S3Urls.builder() .putAdditionalProperty("foo", JsonValue.from("bar")) @@ -151,6 +153,7 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(runSchemaWithAnnotationQueueInfo.childRunIds().getOrNull()) .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(runSchemaWithAnnotationQueueInfo.completedCount()).contains(0L) assertThat(runSchemaWithAnnotationQueueInfo.completionCost()).contains("completion_cost") assertThat(runSchemaWithAnnotationQueueInfo.completionCostDetails()) .contains( @@ -258,6 +261,7 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(runSchemaWithAnnotationQueueInfo.referenceExampleId()) .contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(runSchemaWithAnnotationQueueInfo.reservationCount()).contains(0L) assertThat(runSchemaWithAnnotationQueueInfo.s3Urls()) .contains( RunSchemaWithAnnotationQueueInfo.S3Urls.builder() @@ -306,6 +310,7 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .traceId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .addedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .addChildRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .completedCount(0L) .completionCost("completion_cost") .completionCostDetails( RunSchemaWithAnnotationQueueInfo.CompletionCostDetails.builder() @@ -388,6 +393,7 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .promptTokens(0L) .referenceDatasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .referenceExampleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .reservationCount(0L) .s3Urls( RunSchemaWithAnnotationQueueInfo.S3Urls.builder() .putAdditionalProperty("foo", JsonValue.from("bar")) From 7178ace772419f336bfac62d1c7b8ebbdf98a2d9 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 27 Mar 2026 22:13:42 +0000 Subject: [PATCH 17/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index 2676ddc84..ed5bc5a42 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-923e5b272457a65d68f7e43030dd0db3a9abfa79bded7832a0e54771c8757671.yml -openapi_spec_hash: c0d627562d35dcf4b5823c4f5a2d4fba +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-0a17ad16076f0fdead43274eb292b822323d6c3e6afdd13d21a5d68f2577db6a.yml +openapi_spec_hash: 6acd9fe27e369ad60e6e8f608d93d52d config_hash: 787a12876983a14bce67ed57899e4a94 From ccfb0554c543b98d126218847488140584f14b43 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Fri, 27 Mar 2026 23:13:41 +0000 Subject: [PATCH 18/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index ed5bc5a42..45f9c74e6 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-0a17ad16076f0fdead43274eb292b822323d6c3e6afdd13d21a5d68f2577db6a.yml -openapi_spec_hash: 6acd9fe27e369ad60e6e8f608d93d52d +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-39f28a07954ec79ecd783ce34c2be00b63e496a378f08d2942596073dfc5766c.yml +openapi_spec_hash: 6f395c6ffa632a2da6b2e84a837b3b67 config_hash: 787a12876983a14bce67ed57899e4a94 From b9930c0bd540795c70ae4720b5a83913669284d1 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 28 Mar 2026 00:13:42 +0000 Subject: [PATCH 19/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index 45f9c74e6..cdc668873 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-39f28a07954ec79ecd783ce34c2be00b63e496a378f08d2942596073dfc5766c.yml -openapi_spec_hash: 6f395c6ffa632a2da6b2e84a837b3b67 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-1815d3a4812fa16da87df1f00c5dc46cccd16ae5c02b2f18a2c3f23e645b4778.yml +openapi_spec_hash: baf430d175236aec0bc00eb2986f3c11 config_hash: 787a12876983a14bce67ed57899e4a94 From 2765332e4041c3d80c0d97eb40c8fed9a7b0cfe0 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Sat, 28 Mar 2026 01:13:41 +0000 Subject: [PATCH 20/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index cdc668873..6b52b8721 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-1815d3a4812fa16da87df1f00c5dc46cccd16ae5c02b2f18a2c3f23e645b4778.yml -openapi_spec_hash: baf430d175236aec0bc00eb2986f3c11 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-5b9b97875a31856a4cc9cb65f53f8c39b85a7247f4ae2570e1ff0529f8a7df1a.yml +openapi_spec_hash: a86d557f44cf6d89867c536f6b85cd6e config_hash: 787a12876983a14bce67ed57899e4a94 From efa16fcb5974fbd5500714936cb52a6e930a6181 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 30 Mar 2026 08:30:17 +0000 Subject: [PATCH 21/35] feat(api): api update --- .stats.yml | 4 ++-- buildSrc/src/main/kotlin/langchain.publish.gradle.kts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.stats.yml b/.stats.yml index 6b52b8721..241b37462 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-5b9b97875a31856a4cc9cb65f53f8c39b85a7247f4ae2570e1ff0529f8a7df1a.yml -openapi_spec_hash: a86d557f44cf6d89867c536f6b85cd6e +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-bc1f302915c4d87fd6fc962d3789ae714d63b9f2164e3ef512a7be94cf0a2643.yml +openapi_spec_hash: 02460db53e7a9603d3d9b554e3589fa4 config_hash: 787a12876983a14bce67ed57899e4a94 diff --git a/buildSrc/src/main/kotlin/langchain.publish.gradle.kts b/buildSrc/src/main/kotlin/langchain.publish.gradle.kts index e4ddc09ba..a435d9109 100644 --- a/buildSrc/src/main/kotlin/langchain.publish.gradle.kts +++ b/buildSrc/src/main/kotlin/langchain.publish.gradle.kts @@ -43,7 +43,7 @@ configure { pom { name.set("LangSmith") - description.set("The LangSmith API is used to programmatically create and manage LangSmith\nresources.\n\n## Host\n\nhttps://dev.api.smith.langchain.com\n\n## Authentication\n\nTo authenticate with the LangSmith API, set the `X-Api-Key` header to a valid\n[LangSmith API key](https://docs.langchain.com/langsmith/create-account-api-key#create-an-api-key).") + description.set("The LangSmith API is used to programmatically create and manage LangSmith\nresources.\n\n## Host\n\nhttps://api.smith.langchain.com\n\n## Authentication\n\nTo authenticate with the LangSmith API, set the `X-Api-Key` header to a valid\n[LangSmith API key](https://docs.langchain.com/langsmith/create-account-api-key#create-an-api-key).") url.set("https://www.github.com/langchain-ai/langsmith-java") licenses { From cd6397908d7b28a9ed4e047d48e9c95a73f058a1 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 30 Mar 2026 08:43:10 +0000 Subject: [PATCH 22/35] codegen metadata --- .stats.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.stats.yml b/.stats.yml index 241b37462..9d5f1030e 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 102 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-bc1f302915c4d87fd6fc962d3789ae714d63b9f2164e3ef512a7be94cf0a2643.yml openapi_spec_hash: 02460db53e7a9603d3d9b554e3589fa4 -config_hash: 787a12876983a14bce67ed57899e4a94 +config_hash: 8e34bc27e4a132caa784cf9ec62cc4d0 From 493d5e9b2844ff160598b87602c9f91733722fe4 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 30 Mar 2026 09:00:14 +0000 Subject: [PATCH 23/35] feat(api): manual updates --- .stats.yml | 4 +- .../sessions/insights/InsightListPage.kt | 124 +++ .../sessions/insights/InsightListPageAsync.kt | 139 ++++ .../insights/InsightListPageResponse.kt | 196 +++++ .../sessions/insights/InsightListParams.kt | 280 +++++++ .../sessions/insights/InsightListResponse.kt | 718 ++++++++++++++++++ .../async/sessions/InsightServiceAsync.kt | 78 ++ .../async/sessions/InsightServiceAsyncImpl.kt | 51 ++ .../blocking/sessions/InsightService.kt | 75 ++ .../blocking/sessions/InsightServiceImpl.kt | 44 ++ .../insights/InsightListPageResponseTest.kt | 104 +++ .../insights/InsightListParamsTest.kt | 65 ++ .../insights/InsightListResponseTest.kt | 96 +++ .../async/sessions/InsightServiceAsyncTest.kt | 17 + .../blocking/sessions/InsightServiceTest.kt | 16 + 15 files changed, 2005 insertions(+), 2 deletions(-) create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPage.kt create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageAsync.kt create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageResponse.kt create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListParams.kt create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListResponse.kt create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageResponseTest.kt create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListParamsTest.kt create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListResponseTest.kt diff --git a/.stats.yml b/.stats.yml index 9d5f1030e..157303fd6 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ -configured_endpoints: 102 +configured_endpoints: 103 openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-bc1f302915c4d87fd6fc962d3789ae714d63b9f2164e3ef512a7be94cf0a2643.yml openapi_spec_hash: 02460db53e7a9603d3d9b554e3589fa4 -config_hash: 8e34bc27e4a132caa784cf9ec62cc4d0 +config_hash: c217b34d458f1b65f260715693d447f9 diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPage.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPage.kt new file mode 100644 index 000000000..7f43a0fde --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPage.kt @@ -0,0 +1,124 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.langchain.smith.models.sessions.insights + +import com.langchain.smith.core.AutoPager +import com.langchain.smith.core.Page +import com.langchain.smith.core.checkRequired +import com.langchain.smith.services.blocking.sessions.InsightService +import java.util.Objects +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see InsightService.list */ +class InsightListPage +private constructor( + private val service: InsightService, + private val params: InsightListParams, + private val response: InsightListPageResponse, +) : Page { + + /** + * Delegates to [InsightListPageResponse], but gracefully handles missing data. + * + * @see InsightListPageResponse.clusteringJobs + */ + fun clusteringJobs(): List = + response._clusteringJobs().getOptional("clustering_jobs").getOrNull() ?: emptyList() + + override fun items(): List = clusteringJobs() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): InsightListParams { + val offset = params.offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): InsightListPage = service.list(nextPageParams()) + + fun autoPager(): AutoPager = AutoPager.from(this) + + /** The parameters that were used to request this page. */ + fun params(): InsightListParams = params + + /** The response that this page was parsed from. */ + fun response(): InsightListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InsightListPage]. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InsightListPage]. */ + class Builder internal constructor() { + + private var service: InsightService? = null + private var params: InsightListParams? = null + private var response: InsightListPageResponse? = null + + @JvmSynthetic + internal fun from(insightListPage: InsightListPage) = apply { + service = insightListPage.service + params = insightListPage.params + response = insightListPage.response + } + + fun service(service: InsightService) = apply { this.service = service } + + /** The parameters that were used to request this page. */ + fun params(params: InsightListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: InsightListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [InsightListPage]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InsightListPage = + InsightListPage( + checkRequired("service", service), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InsightListPage && + service == other.service && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, params, response) + + override fun toString() = + "InsightListPage{service=$service, params=$params, response=$response}" +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageAsync.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageAsync.kt new file mode 100644 index 000000000..384167a77 --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageAsync.kt @@ -0,0 +1,139 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.langchain.smith.models.sessions.insights + +import com.langchain.smith.core.AutoPagerAsync +import com.langchain.smith.core.PageAsync +import com.langchain.smith.core.checkRequired +import com.langchain.smith.services.async.sessions.InsightServiceAsync +import java.util.Objects +import java.util.concurrent.CompletableFuture +import java.util.concurrent.Executor +import kotlin.jvm.optionals.getOrDefault +import kotlin.jvm.optionals.getOrNull + +/** @see InsightServiceAsync.list */ +class InsightListPageAsync +private constructor( + private val service: InsightServiceAsync, + private val streamHandlerExecutor: Executor, + private val params: InsightListParams, + private val response: InsightListPageResponse, +) : PageAsync { + + /** + * Delegates to [InsightListPageResponse], but gracefully handles missing data. + * + * @see InsightListPageResponse.clusteringJobs + */ + fun clusteringJobs(): List = + response._clusteringJobs().getOptional("clustering_jobs").getOrNull() ?: emptyList() + + override fun items(): List = clusteringJobs() + + override fun hasNextPage(): Boolean = items().isNotEmpty() + + fun nextPageParams(): InsightListParams { + val offset = params.offset().getOrDefault(0) + return params.toBuilder().offset(offset + items().size).build() + } + + override fun nextPage(): CompletableFuture = + service.list(nextPageParams()) + + fun autoPager(): AutoPagerAsync = + AutoPagerAsync.from(this, streamHandlerExecutor) + + /** The parameters that were used to request this page. */ + fun params(): InsightListParams = params + + /** The response that this page was parsed from. */ + fun response(): InsightListPageResponse = response + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InsightListPageAsync]. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InsightListPageAsync]. */ + class Builder internal constructor() { + + private var service: InsightServiceAsync? = null + private var streamHandlerExecutor: Executor? = null + private var params: InsightListParams? = null + private var response: InsightListPageResponse? = null + + @JvmSynthetic + internal fun from(insightListPageAsync: InsightListPageAsync) = apply { + service = insightListPageAsync.service + streamHandlerExecutor = insightListPageAsync.streamHandlerExecutor + params = insightListPageAsync.params + response = insightListPageAsync.response + } + + fun service(service: InsightServiceAsync) = apply { this.service = service } + + fun streamHandlerExecutor(streamHandlerExecutor: Executor) = apply { + this.streamHandlerExecutor = streamHandlerExecutor + } + + /** The parameters that were used to request this page. */ + fun params(params: InsightListParams) = apply { this.params = params } + + /** The response that this page was parsed from. */ + fun response(response: InsightListPageResponse) = apply { this.response = response } + + /** + * Returns an immutable instance of [InsightListPageAsync]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .service() + * .streamHandlerExecutor() + * .params() + * .response() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InsightListPageAsync = + InsightListPageAsync( + checkRequired("service", service), + checkRequired("streamHandlerExecutor", streamHandlerExecutor), + checkRequired("params", params), + checkRequired("response", response), + ) + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InsightListPageAsync && + service == other.service && + streamHandlerExecutor == other.streamHandlerExecutor && + params == other.params && + response == other.response + } + + override fun hashCode(): Int = Objects.hash(service, streamHandlerExecutor, params, response) + + override fun toString() = + "InsightListPageAsync{service=$service, streamHandlerExecutor=$streamHandlerExecutor, params=$params, response=$response}" +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageResponse.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageResponse.kt new file mode 100644 index 000000000..d61d7d227 --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageResponse.kt @@ -0,0 +1,196 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.langchain.smith.models.sessions.insights + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.langchain.smith.core.ExcludeMissing +import com.langchain.smith.core.JsonField +import com.langchain.smith.core.JsonMissing +import com.langchain.smith.core.JsonValue +import com.langchain.smith.core.checkKnown +import com.langchain.smith.core.checkRequired +import com.langchain.smith.core.toImmutable +import com.langchain.smith.errors.LangChainInvalidDataException +import java.util.Collections +import java.util.Objects +import kotlin.jvm.optionals.getOrNull + +/** Response to get all cluster jobs for a session. */ +class InsightListPageResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val clusteringJobs: JsonField>, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("clustering_jobs") + @ExcludeMissing + clusteringJobs: JsonField> = JsonMissing.of() + ) : this(clusteringJobs, mutableMapOf()) + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun clusteringJobs(): List = clusteringJobs.getRequired("clustering_jobs") + + /** + * Returns the raw JSON value of [clusteringJobs]. + * + * Unlike [clusteringJobs], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("clustering_jobs") + @ExcludeMissing + fun _clusteringJobs(): JsonField> = clusteringJobs + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InsightListPageResponse]. + * + * The following fields are required: + * ```java + * .clusteringJobs() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InsightListPageResponse]. */ + class Builder internal constructor() { + + private var clusteringJobs: JsonField>? = null + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(insightListPageResponse: InsightListPageResponse) = apply { + clusteringJobs = insightListPageResponse.clusteringJobs.map { it.toMutableList() } + additionalProperties = insightListPageResponse.additionalProperties.toMutableMap() + } + + fun clusteringJobs(clusteringJobs: List) = + clusteringJobs(JsonField.of(clusteringJobs)) + + /** + * Sets [Builder.clusteringJobs] to an arbitrary JSON value. + * + * You should usually call [Builder.clusteringJobs] with a well-typed + * `List` value instead. This method is primarily for setting the field + * to an undocumented or not yet supported value. + */ + fun clusteringJobs(clusteringJobs: JsonField>) = apply { + this.clusteringJobs = clusteringJobs.map { it.toMutableList() } + } + + /** + * Adds a single [InsightListResponse] to [clusteringJobs]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addClusteringJob(clusteringJob: InsightListResponse) = apply { + clusteringJobs = + (clusteringJobs ?: JsonField.of(mutableListOf())).also { + checkKnown("clusteringJobs", it).add(clusteringJob) + } + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InsightListPageResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .clusteringJobs() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InsightListPageResponse = + InsightListPageResponse( + checkRequired("clusteringJobs", clusteringJobs).map { it.toImmutable() }, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): InsightListPageResponse = apply { + if (validated) { + return@apply + } + + clusteringJobs().forEach { it.validate() } + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: LangChainInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (clusteringJobs.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InsightListPageResponse && + clusteringJobs == other.clusteringJobs && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(clusteringJobs, additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InsightListPageResponse{clusteringJobs=$clusteringJobs, additionalProperties=$additionalProperties}" +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListParams.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListParams.kt new file mode 100644 index 000000000..a97e973f0 --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListParams.kt @@ -0,0 +1,280 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.langchain.smith.models.sessions.insights + +import com.langchain.smith.core.Params +import com.langchain.smith.core.http.Headers +import com.langchain.smith.core.http.QueryParams +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Get all clusters for a session. */ +class InsightListParams +private constructor( + private val sessionId: String?, + private val configId: String?, + private val legacy: Boolean?, + private val limit: Long?, + private val offset: Long?, + private val additionalHeaders: Headers, + private val additionalQueryParams: QueryParams, +) : Params { + + fun sessionId(): Optional = Optional.ofNullable(sessionId) + + fun configId(): Optional = Optional.ofNullable(configId) + + fun legacy(): Optional = Optional.ofNullable(legacy) + + fun limit(): Optional = Optional.ofNullable(limit) + + fun offset(): Optional = Optional.ofNullable(offset) + + /** Additional headers to send with the request. */ + fun _additionalHeaders(): Headers = additionalHeaders + + /** Additional query param to send with the request. */ + fun _additionalQueryParams(): QueryParams = additionalQueryParams + + fun toBuilder() = Builder().from(this) + + companion object { + + @JvmStatic fun none(): InsightListParams = builder().build() + + /** Returns a mutable builder for constructing an instance of [InsightListParams]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InsightListParams]. */ + class Builder internal constructor() { + + private var sessionId: String? = null + private var configId: String? = null + private var legacy: Boolean? = null + private var limit: Long? = null + private var offset: Long? = null + private var additionalHeaders: Headers.Builder = Headers.builder() + private var additionalQueryParams: QueryParams.Builder = QueryParams.builder() + + @JvmSynthetic + internal fun from(insightListParams: InsightListParams) = apply { + sessionId = insightListParams.sessionId + configId = insightListParams.configId + legacy = insightListParams.legacy + limit = insightListParams.limit + offset = insightListParams.offset + additionalHeaders = insightListParams.additionalHeaders.toBuilder() + additionalQueryParams = insightListParams.additionalQueryParams.toBuilder() + } + + fun sessionId(sessionId: String?) = apply { this.sessionId = sessionId } + + /** Alias for calling [Builder.sessionId] with `sessionId.orElse(null)`. */ + fun sessionId(sessionId: Optional) = sessionId(sessionId.getOrNull()) + + fun configId(configId: String?) = apply { this.configId = configId } + + /** Alias for calling [Builder.configId] with `configId.orElse(null)`. */ + fun configId(configId: Optional) = configId(configId.getOrNull()) + + fun legacy(legacy: Boolean?) = apply { this.legacy = legacy } + + /** + * Alias for [Builder.legacy]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun legacy(legacy: Boolean) = legacy(legacy as Boolean?) + + /** Alias for calling [Builder.legacy] with `legacy.orElse(null)`. */ + fun legacy(legacy: Optional) = legacy(legacy.getOrNull()) + + fun limit(limit: Long?) = apply { this.limit = limit } + + /** + * Alias for [Builder.limit]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun limit(limit: Long) = limit(limit as Long?) + + /** Alias for calling [Builder.limit] with `limit.orElse(null)`. */ + fun limit(limit: Optional) = limit(limit.getOrNull()) + + fun offset(offset: Long?) = apply { this.offset = offset } + + /** + * Alias for [Builder.offset]. + * + * This unboxed primitive overload exists for backwards compatibility. + */ + fun offset(offset: Long) = offset(offset as Long?) + + /** Alias for calling [Builder.offset] with `offset.orElse(null)`. */ + fun offset(offset: Optional) = offset(offset.getOrNull()) + + fun additionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun additionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.clear() + putAllAdditionalHeaders(additionalHeaders) + } + + fun putAdditionalHeader(name: String, value: String) = apply { + additionalHeaders.put(name, value) + } + + fun putAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.put(name, values) + } + + fun putAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun putAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.putAll(additionalHeaders) + } + + fun replaceAdditionalHeaders(name: String, value: String) = apply { + additionalHeaders.replace(name, value) + } + + fun replaceAdditionalHeaders(name: String, values: Iterable) = apply { + additionalHeaders.replace(name, values) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Headers) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun replaceAllAdditionalHeaders(additionalHeaders: Map>) = apply { + this.additionalHeaders.replaceAll(additionalHeaders) + } + + fun removeAdditionalHeaders(name: String) = apply { additionalHeaders.remove(name) } + + fun removeAllAdditionalHeaders(names: Set) = apply { + additionalHeaders.removeAll(names) + } + + fun additionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun additionalQueryParams(additionalQueryParams: Map>) = apply { + this.additionalQueryParams.clear() + putAllAdditionalQueryParams(additionalQueryParams) + } + + fun putAdditionalQueryParam(key: String, value: String) = apply { + additionalQueryParams.put(key, value) + } + + fun putAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.put(key, values) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun putAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.putAll(additionalQueryParams) + } + + fun replaceAdditionalQueryParams(key: String, value: String) = apply { + additionalQueryParams.replace(key, value) + } + + fun replaceAdditionalQueryParams(key: String, values: Iterable) = apply { + additionalQueryParams.replace(key, values) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: QueryParams) = apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun replaceAllAdditionalQueryParams(additionalQueryParams: Map>) = + apply { + this.additionalQueryParams.replaceAll(additionalQueryParams) + } + + fun removeAdditionalQueryParams(key: String) = apply { additionalQueryParams.remove(key) } + + fun removeAllAdditionalQueryParams(keys: Set) = apply { + additionalQueryParams.removeAll(keys) + } + + /** + * Returns an immutable instance of [InsightListParams]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): InsightListParams = + InsightListParams( + sessionId, + configId, + legacy, + limit, + offset, + additionalHeaders.build(), + additionalQueryParams.build(), + ) + } + + fun _pathParam(index: Int): String = + when (index) { + 0 -> sessionId ?: "" + else -> "" + } + + override fun _headers(): Headers = additionalHeaders + + override fun _queryParams(): QueryParams = + QueryParams.builder() + .apply { + configId?.let { put("config_id", it) } + legacy?.let { put("legacy", it.toString()) } + limit?.let { put("limit", it.toString()) } + offset?.let { put("offset", it.toString()) } + putAll(additionalQueryParams) + } + .build() + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InsightListParams && + sessionId == other.sessionId && + configId == other.configId && + legacy == other.legacy && + limit == other.limit && + offset == other.offset && + additionalHeaders == other.additionalHeaders && + additionalQueryParams == other.additionalQueryParams + } + + override fun hashCode(): Int = + Objects.hash( + sessionId, + configId, + legacy, + limit, + offset, + additionalHeaders, + additionalQueryParams, + ) + + override fun toString() = + "InsightListParams{sessionId=$sessionId, configId=$configId, legacy=$legacy, limit=$limit, offset=$offset, additionalHeaders=$additionalHeaders, additionalQueryParams=$additionalQueryParams}" +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListResponse.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListResponse.kt new file mode 100644 index 000000000..9220ecb4e --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/sessions/insights/InsightListResponse.kt @@ -0,0 +1,718 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.langchain.smith.models.sessions.insights + +import com.fasterxml.jackson.annotation.JsonAnyGetter +import com.fasterxml.jackson.annotation.JsonAnySetter +import com.fasterxml.jackson.annotation.JsonCreator +import com.fasterxml.jackson.annotation.JsonProperty +import com.langchain.smith.core.ExcludeMissing +import com.langchain.smith.core.JsonField +import com.langchain.smith.core.JsonMissing +import com.langchain.smith.core.JsonValue +import com.langchain.smith.core.checkRequired +import com.langchain.smith.core.toImmutable +import com.langchain.smith.errors.LangChainInvalidDataException +import java.time.OffsetDateTime +import java.util.Collections +import java.util.Objects +import java.util.Optional +import kotlin.jvm.optionals.getOrNull + +/** Session cluster job */ +class InsightListResponse +@JsonCreator(mode = JsonCreator.Mode.DISABLED) +private constructor( + private val id: JsonField, + private val createdAt: JsonField, + private val name: JsonField, + private val status: JsonField, + private val configId: JsonField, + private val endTime: JsonField, + private val error: JsonField, + private val metadata: JsonField, + private val shape: JsonField, + private val startTime: JsonField, + private val additionalProperties: MutableMap, +) { + + @JsonCreator + private constructor( + @JsonProperty("id") @ExcludeMissing id: JsonField = JsonMissing.of(), + @JsonProperty("created_at") + @ExcludeMissing + createdAt: JsonField = JsonMissing.of(), + @JsonProperty("name") @ExcludeMissing name: JsonField = JsonMissing.of(), + @JsonProperty("status") @ExcludeMissing status: JsonField = JsonMissing.of(), + @JsonProperty("config_id") @ExcludeMissing configId: JsonField = JsonMissing.of(), + @JsonProperty("end_time") + @ExcludeMissing + endTime: JsonField = JsonMissing.of(), + @JsonProperty("error") @ExcludeMissing error: JsonField = JsonMissing.of(), + @JsonProperty("metadata") @ExcludeMissing metadata: JsonField = JsonMissing.of(), + @JsonProperty("shape") @ExcludeMissing shape: JsonField = JsonMissing.of(), + @JsonProperty("start_time") + @ExcludeMissing + startTime: JsonField = JsonMissing.of(), + ) : this( + id, + createdAt, + name, + status, + configId, + endTime, + error, + metadata, + shape, + startTime, + mutableMapOf(), + ) + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun id(): String = id.getRequired("id") + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun name(): String = name.getRequired("name") + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type or is + * unexpectedly missing or null (e.g. if the server responded with an unexpected value). + */ + fun status(): String = status.getRequired("status") + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun configId(): Optional = configId.getOptional("config_id") + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun endTime(): Optional = endTime.getOptional("end_time") + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun error(): Optional = error.getOptional("error") + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun metadata(): Optional = metadata.getOptional("metadata") + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun shape(): Optional = shape.getOptional("shape") + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun startTime(): Optional = startTime.getOptional("start_time") + + /** + * Returns the raw JSON value of [id]. + * + * Unlike [id], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("id") @ExcludeMissing fun _id(): JsonField = id + + /** + * Returns the raw JSON value of [createdAt]. + * + * Unlike [createdAt], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("created_at") + @ExcludeMissing + fun _createdAt(): JsonField = createdAt + + /** + * Returns the raw JSON value of [name]. + * + * Unlike [name], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("name") @ExcludeMissing fun _name(): JsonField = name + + /** + * Returns the raw JSON value of [status]. + * + * Unlike [status], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("status") @ExcludeMissing fun _status(): JsonField = status + + /** + * Returns the raw JSON value of [configId]. + * + * Unlike [configId], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("config_id") @ExcludeMissing fun _configId(): JsonField = configId + + /** + * Returns the raw JSON value of [endTime]. + * + * Unlike [endTime], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("end_time") @ExcludeMissing fun _endTime(): JsonField = endTime + + /** + * Returns the raw JSON value of [error]. + * + * Unlike [error], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("error") @ExcludeMissing fun _error(): JsonField = error + + /** + * Returns the raw JSON value of [metadata]. + * + * Unlike [metadata], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("metadata") @ExcludeMissing fun _metadata(): JsonField = metadata + + /** + * Returns the raw JSON value of [shape]. + * + * Unlike [shape], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("shape") @ExcludeMissing fun _shape(): JsonField = shape + + /** + * Returns the raw JSON value of [startTime]. + * + * Unlike [startTime], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("start_time") + @ExcludeMissing + fun _startTime(): JsonField = startTime + + @JsonAnySetter + private fun putAdditionalProperty(key: String, value: JsonValue) { + additionalProperties.put(key, value) + } + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = + Collections.unmodifiableMap(additionalProperties) + + fun toBuilder() = Builder().from(this) + + companion object { + + /** + * Returns a mutable builder for constructing an instance of [InsightListResponse]. + * + * The following fields are required: + * ```java + * .id() + * .createdAt() + * .name() + * .status() + * ``` + */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [InsightListResponse]. */ + class Builder internal constructor() { + + private var id: JsonField? = null + private var createdAt: JsonField? = null + private var name: JsonField? = null + private var status: JsonField? = null + private var configId: JsonField = JsonMissing.of() + private var endTime: JsonField = JsonMissing.of() + private var error: JsonField = JsonMissing.of() + private var metadata: JsonField = JsonMissing.of() + private var shape: JsonField = JsonMissing.of() + private var startTime: JsonField = JsonMissing.of() + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(insightListResponse: InsightListResponse) = apply { + id = insightListResponse.id + createdAt = insightListResponse.createdAt + name = insightListResponse.name + status = insightListResponse.status + configId = insightListResponse.configId + endTime = insightListResponse.endTime + error = insightListResponse.error + metadata = insightListResponse.metadata + shape = insightListResponse.shape + startTime = insightListResponse.startTime + additionalProperties = insightListResponse.additionalProperties.toMutableMap() + } + + fun id(id: String) = id(JsonField.of(id)) + + /** + * Sets [Builder.id] to an arbitrary JSON value. + * + * You should usually call [Builder.id] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun id(id: JsonField) = apply { this.id = id } + + fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) + + /** + * Sets [Builder.createdAt] to an arbitrary JSON value. + * + * You should usually call [Builder.createdAt] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + + fun name(name: String) = name(JsonField.of(name)) + + /** + * Sets [Builder.name] to an arbitrary JSON value. + * + * You should usually call [Builder.name] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun name(name: JsonField) = apply { this.name = name } + + fun status(status: String) = status(JsonField.of(status)) + + /** + * Sets [Builder.status] to an arbitrary JSON value. + * + * You should usually call [Builder.status] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun status(status: JsonField) = apply { this.status = status } + + fun configId(configId: String?) = configId(JsonField.ofNullable(configId)) + + /** Alias for calling [Builder.configId] with `configId.orElse(null)`. */ + fun configId(configId: Optional) = configId(configId.getOrNull()) + + /** + * Sets [Builder.configId] to an arbitrary JSON value. + * + * You should usually call [Builder.configId] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun configId(configId: JsonField) = apply { this.configId = configId } + + fun endTime(endTime: OffsetDateTime?) = endTime(JsonField.ofNullable(endTime)) + + /** Alias for calling [Builder.endTime] with `endTime.orElse(null)`. */ + fun endTime(endTime: Optional) = endTime(endTime.getOrNull()) + + /** + * Sets [Builder.endTime] to an arbitrary JSON value. + * + * You should usually call [Builder.endTime] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun endTime(endTime: JsonField) = apply { this.endTime = endTime } + + fun error(error: String?) = error(JsonField.ofNullable(error)) + + /** Alias for calling [Builder.error] with `error.orElse(null)`. */ + fun error(error: Optional) = error(error.getOrNull()) + + /** + * Sets [Builder.error] to an arbitrary JSON value. + * + * You should usually call [Builder.error] with a well-typed [String] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun error(error: JsonField) = apply { this.error = error } + + fun metadata(metadata: Metadata?) = metadata(JsonField.ofNullable(metadata)) + + /** Alias for calling [Builder.metadata] with `metadata.orElse(null)`. */ + fun metadata(metadata: Optional) = metadata(metadata.getOrNull()) + + /** + * Sets [Builder.metadata] to an arbitrary JSON value. + * + * You should usually call [Builder.metadata] with a well-typed [Metadata] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun metadata(metadata: JsonField) = apply { this.metadata = metadata } + + fun shape(shape: Shape?) = shape(JsonField.ofNullable(shape)) + + /** Alias for calling [Builder.shape] with `shape.orElse(null)`. */ + fun shape(shape: Optional) = shape(shape.getOrNull()) + + /** + * Sets [Builder.shape] to an arbitrary JSON value. + * + * You should usually call [Builder.shape] with a well-typed [Shape] value instead. This + * method is primarily for setting the field to an undocumented or not yet supported value. + */ + fun shape(shape: JsonField) = apply { this.shape = shape } + + fun startTime(startTime: OffsetDateTime?) = startTime(JsonField.ofNullable(startTime)) + + /** Alias for calling [Builder.startTime] with `startTime.orElse(null)`. */ + fun startTime(startTime: Optional) = startTime(startTime.getOrNull()) + + /** + * Sets [Builder.startTime] to an arbitrary JSON value. + * + * You should usually call [Builder.startTime] with a well-typed [OffsetDateTime] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun startTime(startTime: JsonField) = apply { this.startTime = startTime } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [InsightListResponse]. + * + * Further updates to this [Builder] will not mutate the returned instance. + * + * The following fields are required: + * ```java + * .id() + * .createdAt() + * .name() + * .status() + * ``` + * + * @throws IllegalStateException if any required field is unset. + */ + fun build(): InsightListResponse = + InsightListResponse( + checkRequired("id", id), + checkRequired("createdAt", createdAt), + checkRequired("name", name), + checkRequired("status", status), + configId, + endTime, + error, + metadata, + shape, + startTime, + additionalProperties.toMutableMap(), + ) + } + + private var validated: Boolean = false + + fun validate(): InsightListResponse = apply { + if (validated) { + return@apply + } + + id() + createdAt() + name() + status() + configId() + endTime() + error() + metadata().ifPresent { it.validate() } + shape().ifPresent { it.validate() } + startTime() + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: LangChainInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + (if (id.asKnown().isPresent) 1 else 0) + + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (name.asKnown().isPresent) 1 else 0) + + (if (status.asKnown().isPresent) 1 else 0) + + (if (configId.asKnown().isPresent) 1 else 0) + + (if (endTime.asKnown().isPresent) 1 else 0) + + (if (error.asKnown().isPresent) 1 else 0) + + (metadata.asKnown().getOrNull()?.validity() ?: 0) + + (shape.asKnown().getOrNull()?.validity() ?: 0) + + (if (startTime.asKnown().isPresent) 1 else 0) + + class Metadata + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Metadata]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Metadata]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(metadata: Metadata) = apply { + additionalProperties = metadata.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Metadata]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Metadata = Metadata(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Metadata = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: LangChainInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Metadata && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Metadata{additionalProperties=$additionalProperties}" + } + + class Shape + @JsonCreator + private constructor( + @com.fasterxml.jackson.annotation.JsonValue + private val additionalProperties: Map + ) { + + @JsonAnyGetter + @ExcludeMissing + fun _additionalProperties(): Map = additionalProperties + + fun toBuilder() = Builder().from(this) + + companion object { + + /** Returns a mutable builder for constructing an instance of [Shape]. */ + @JvmStatic fun builder() = Builder() + } + + /** A builder for [Shape]. */ + class Builder internal constructor() { + + private var additionalProperties: MutableMap = mutableMapOf() + + @JvmSynthetic + internal fun from(shape: Shape) = apply { + additionalProperties = shape.additionalProperties.toMutableMap() + } + + fun additionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.clear() + putAllAdditionalProperties(additionalProperties) + } + + fun putAdditionalProperty(key: String, value: JsonValue) = apply { + additionalProperties.put(key, value) + } + + fun putAllAdditionalProperties(additionalProperties: Map) = apply { + this.additionalProperties.putAll(additionalProperties) + } + + fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) } + + fun removeAllAdditionalProperties(keys: Set) = apply { + keys.forEach(::removeAdditionalProperty) + } + + /** + * Returns an immutable instance of [Shape]. + * + * Further updates to this [Builder] will not mutate the returned instance. + */ + fun build(): Shape = Shape(additionalProperties.toImmutable()) + } + + private var validated: Boolean = false + + fun validate(): Shape = apply { + if (validated) { + return@apply + } + + validated = true + } + + fun isValid(): Boolean = + try { + validate() + true + } catch (e: LangChainInvalidDataException) { + false + } + + /** + * Returns a score indicating how many valid values are contained in this object + * recursively. + * + * Used for best match union deserialization. + */ + @JvmSynthetic + internal fun validity(): Int = + additionalProperties.count { (_, value) -> !value.isNull() && !value.isMissing() } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is Shape && additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { Objects.hash(additionalProperties) } + + override fun hashCode(): Int = hashCode + + override fun toString() = "Shape{additionalProperties=$additionalProperties}" + } + + override fun equals(other: Any?): Boolean { + if (this === other) { + return true + } + + return other is InsightListResponse && + id == other.id && + createdAt == other.createdAt && + name == other.name && + status == other.status && + configId == other.configId && + endTime == other.endTime && + error == other.error && + metadata == other.metadata && + shape == other.shape && + startTime == other.startTime && + additionalProperties == other.additionalProperties + } + + private val hashCode: Int by lazy { + Objects.hash( + id, + createdAt, + name, + status, + configId, + endTime, + error, + metadata, + shape, + startTime, + additionalProperties, + ) + } + + override fun hashCode(): Int = hashCode + + override fun toString() = + "InsightListResponse{id=$id, createdAt=$createdAt, name=$name, status=$status, configId=$configId, endTime=$endTime, error=$error, metadata=$metadata, shape=$shape, startTime=$startTime, additionalProperties=$additionalProperties}" +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsync.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsync.kt index 524998e36..6890477b5 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsync.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsync.kt @@ -9,6 +9,8 @@ import com.langchain.smith.models.sessions.insights.InsightCreateParams import com.langchain.smith.models.sessions.insights.InsightCreateResponse import com.langchain.smith.models.sessions.insights.InsightDeleteParams import com.langchain.smith.models.sessions.insights.InsightDeleteResponse +import com.langchain.smith.models.sessions.insights.InsightListPageAsync +import com.langchain.smith.models.sessions.insights.InsightListParams import com.langchain.smith.models.sessions.insights.InsightRetrieveJobParams import com.langchain.smith.models.sessions.insights.InsightRetrieveJobResponse import com.langchain.smith.models.sessions.insights.InsightRetrieveRunsParams @@ -80,6 +82,41 @@ interface InsightServiceAsync { requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture + /** Get all clusters for a session. */ + fun list(sessionId: String): CompletableFuture = + list(sessionId, InsightListParams.none()) + + /** @see list */ + fun list( + sessionId: String, + params: InsightListParams = InsightListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture = + list(params.toBuilder().sessionId(sessionId).build(), requestOptions) + + /** @see list */ + fun list( + sessionId: String, + params: InsightListParams = InsightListParams.none(), + ): CompletableFuture = list(sessionId, params, RequestOptions.none()) + + /** @see list */ + fun list( + params: InsightListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture + + /** @see list */ + fun list(params: InsightListParams): CompletableFuture = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + sessionId: String, + requestOptions: RequestOptions, + ): CompletableFuture = + list(sessionId, InsightListParams.none(), requestOptions) + /** Delete a session cluster job. */ fun delete( jobId: String, @@ -230,6 +267,47 @@ interface InsightServiceAsync { requestOptions: RequestOptions = RequestOptions.none(), ): CompletableFuture> + /** + * Returns a raw HTTP response for `get /api/v1/sessions/{session_id}/insights`, but is + * otherwise the same as [InsightServiceAsync.list]. + */ + fun list(sessionId: String): CompletableFuture> = + list(sessionId, InsightListParams.none()) + + /** @see list */ + fun list( + sessionId: String, + params: InsightListParams = InsightListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> = + list(params.toBuilder().sessionId(sessionId).build(), requestOptions) + + /** @see list */ + fun list( + sessionId: String, + params: InsightListParams = InsightListParams.none(), + ): CompletableFuture> = + list(sessionId, params, RequestOptions.none()) + + /** @see list */ + fun list( + params: InsightListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): CompletableFuture> + + /** @see list */ + fun list( + params: InsightListParams + ): CompletableFuture> = + list(params, RequestOptions.none()) + + /** @see list */ + fun list( + sessionId: String, + requestOptions: RequestOptions, + ): CompletableFuture> = + list(sessionId, InsightListParams.none(), requestOptions) + /** * Returns a raw HTTP response for `delete /api/v1/sessions/{session_id}/insights/{job_id}`, * but is otherwise the same as [InsightServiceAsync.delete]. diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsyncImpl.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsyncImpl.kt index 73c3c54a2..38517f5db 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsyncImpl.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsyncImpl.kt @@ -20,6 +20,9 @@ import com.langchain.smith.models.sessions.insights.InsightCreateParams import com.langchain.smith.models.sessions.insights.InsightCreateResponse import com.langchain.smith.models.sessions.insights.InsightDeleteParams import com.langchain.smith.models.sessions.insights.InsightDeleteResponse +import com.langchain.smith.models.sessions.insights.InsightListPageAsync +import com.langchain.smith.models.sessions.insights.InsightListPageResponse +import com.langchain.smith.models.sessions.insights.InsightListParams import com.langchain.smith.models.sessions.insights.InsightRetrieveJobParams import com.langchain.smith.models.sessions.insights.InsightRetrieveJobResponse import com.langchain.smith.models.sessions.insights.InsightRetrieveRunsParams @@ -56,6 +59,13 @@ class InsightServiceAsyncImpl internal constructor(private val clientOptions: Cl // patch /api/v1/sessions/{session_id}/insights/{job_id} withRawResponse().update(params, requestOptions).thenApply { it.parse() } + override fun list( + params: InsightListParams, + requestOptions: RequestOptions, + ): CompletableFuture = + // get /api/v1/sessions/{session_id}/insights + withRawResponse().list(params, requestOptions).thenApply { it.parse() } + override fun delete( params: InsightDeleteParams, requestOptions: RequestOptions, @@ -165,6 +175,47 @@ class InsightServiceAsyncImpl internal constructor(private val clientOptions: Cl } } + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: InsightListParams, + requestOptions: RequestOptions, + ): CompletableFuture> { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("sessionId", params.sessionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("api", "v1", "sessions", params._pathParam(0), "insights") + .build() + .prepareAsync(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + return request + .thenComposeAsync { clientOptions.httpClient.executeAsync(it, requestOptions) } + .thenApply { response -> + errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + InsightListPageAsync.builder() + .service(InsightServiceAsyncImpl(clientOptions)) + .streamHandlerExecutor(clientOptions.streamHandlerExecutor) + .params(params) + .response(it) + .build() + } + } + } + } + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/blocking/sessions/InsightService.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/blocking/sessions/InsightService.kt index 6c39a18c6..2d2969437 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/blocking/sessions/InsightService.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/blocking/sessions/InsightService.kt @@ -10,6 +10,8 @@ import com.langchain.smith.models.sessions.insights.InsightCreateParams import com.langchain.smith.models.sessions.insights.InsightCreateResponse import com.langchain.smith.models.sessions.insights.InsightDeleteParams import com.langchain.smith.models.sessions.insights.InsightDeleteResponse +import com.langchain.smith.models.sessions.insights.InsightListPage +import com.langchain.smith.models.sessions.insights.InsightListParams import com.langchain.smith.models.sessions.insights.InsightRetrieveJobParams import com.langchain.smith.models.sessions.insights.InsightRetrieveJobResponse import com.langchain.smith.models.sessions.insights.InsightRetrieveRunsParams @@ -75,6 +77,35 @@ interface InsightService { requestOptions: RequestOptions = RequestOptions.none(), ): InsightUpdateResponse + /** Get all clusters for a session. */ + fun list(sessionId: String): InsightListPage = list(sessionId, InsightListParams.none()) + + /** @see list */ + fun list( + sessionId: String, + params: InsightListParams = InsightListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): InsightListPage = list(params.toBuilder().sessionId(sessionId).build(), requestOptions) + + /** @see list */ + fun list( + sessionId: String, + params: InsightListParams = InsightListParams.none(), + ): InsightListPage = list(sessionId, params, RequestOptions.none()) + + /** @see list */ + fun list( + params: InsightListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): InsightListPage + + /** @see list */ + fun list(params: InsightListParams): InsightListPage = list(params, RequestOptions.none()) + + /** @see list */ + fun list(sessionId: String, requestOptions: RequestOptions): InsightListPage = + list(sessionId, InsightListParams.none(), requestOptions) + /** Delete a session cluster job. */ fun delete(jobId: String, params: InsightDeleteParams): InsightDeleteResponse = delete(jobId, params, RequestOptions.none()) @@ -214,6 +245,50 @@ interface InsightService { requestOptions: RequestOptions = RequestOptions.none(), ): HttpResponseFor + /** + * Returns a raw HTTP response for `get /api/v1/sessions/{session_id}/insights`, but is + * otherwise the same as [InsightService.list]. + */ + @MustBeClosed + fun list(sessionId: String): HttpResponseFor = + list(sessionId, InsightListParams.none()) + + /** @see list */ + @MustBeClosed + fun list( + sessionId: String, + params: InsightListParams = InsightListParams.none(), + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor = + list(params.toBuilder().sessionId(sessionId).build(), requestOptions) + + /** @see list */ + @MustBeClosed + fun list( + sessionId: String, + params: InsightListParams = InsightListParams.none(), + ): HttpResponseFor = list(sessionId, params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list( + params: InsightListParams, + requestOptions: RequestOptions = RequestOptions.none(), + ): HttpResponseFor + + /** @see list */ + @MustBeClosed + fun list(params: InsightListParams): HttpResponseFor = + list(params, RequestOptions.none()) + + /** @see list */ + @MustBeClosed + fun list( + sessionId: String, + requestOptions: RequestOptions, + ): HttpResponseFor = + list(sessionId, InsightListParams.none(), requestOptions) + /** * Returns a raw HTTP response for `delete /api/v1/sessions/{session_id}/insights/{job_id}`, * but is otherwise the same as [InsightService.delete]. diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/blocking/sessions/InsightServiceImpl.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/blocking/sessions/InsightServiceImpl.kt index aa53fa07b..e5f2b7c23 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/blocking/sessions/InsightServiceImpl.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/services/blocking/sessions/InsightServiceImpl.kt @@ -20,6 +20,9 @@ import com.langchain.smith.models.sessions.insights.InsightCreateParams import com.langchain.smith.models.sessions.insights.InsightCreateResponse import com.langchain.smith.models.sessions.insights.InsightDeleteParams import com.langchain.smith.models.sessions.insights.InsightDeleteResponse +import com.langchain.smith.models.sessions.insights.InsightListPage +import com.langchain.smith.models.sessions.insights.InsightListPageResponse +import com.langchain.smith.models.sessions.insights.InsightListParams import com.langchain.smith.models.sessions.insights.InsightRetrieveJobParams import com.langchain.smith.models.sessions.insights.InsightRetrieveJobResponse import com.langchain.smith.models.sessions.insights.InsightRetrieveRunsParams @@ -55,6 +58,10 @@ class InsightServiceImpl internal constructor(private val clientOptions: ClientO // patch /api/v1/sessions/{session_id}/insights/{job_id} withRawResponse().update(params, requestOptions).parse() + override fun list(params: InsightListParams, requestOptions: RequestOptions): InsightListPage = + // get /api/v1/sessions/{session_id}/insights + withRawResponse().list(params, requestOptions).parse() + override fun delete( params: InsightDeleteParams, requestOptions: RequestOptions, @@ -158,6 +165,43 @@ class InsightServiceImpl internal constructor(private val clientOptions: ClientO } } + private val listHandler: Handler = + jsonHandler(clientOptions.jsonMapper) + + override fun list( + params: InsightListParams, + requestOptions: RequestOptions, + ): HttpResponseFor { + // We check here instead of in the params builder because this can be specified + // positionally or in the params class. + checkRequired("sessionId", params.sessionId().getOrNull()) + val request = + HttpRequest.builder() + .method(HttpMethod.GET) + .baseUrl(clientOptions.baseUrl()) + .addPathSegments("api", "v1", "sessions", params._pathParam(0), "insights") + .build() + .prepare(clientOptions, params) + val requestOptions = requestOptions.applyDefaults(RequestOptions.from(clientOptions)) + val response = clientOptions.httpClient.execute(request, requestOptions) + return errorHandler.handle(response).parseable { + response + .use { listHandler.handle(it) } + .also { + if (requestOptions.responseValidation!!) { + it.validate() + } + } + .let { + InsightListPage.builder() + .service(InsightServiceImpl(clientOptions)) + .params(params) + .response(it) + .build() + } + } + } + private val deleteHandler: Handler = jsonHandler(clientOptions.jsonMapper) diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageResponseTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageResponseTest.kt new file mode 100644 index 000000000..3345eba34 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListPageResponseTest.kt @@ -0,0 +1,104 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.langchain.smith.models.sessions.insights + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.langchain.smith.core.JsonValue +import com.langchain.smith.core.jsonMapper +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class InsightListPageResponseTest { + + @Test + fun create() { + val insightListPageResponse = + InsightListPageResponse.builder() + .addClusteringJob( + InsightListResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .name("name") + .status("status") + .configId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .endTime(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .error("error") + .metadata( + InsightListResponse.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .shape( + InsightListResponse.Shape.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .startTime(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + ) + .build() + + assertThat(insightListPageResponse.clusteringJobs()) + .containsExactly( + InsightListResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .name("name") + .status("status") + .configId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .endTime(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .error("error") + .metadata( + InsightListResponse.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .shape( + InsightListResponse.Shape.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .startTime(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + ) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val insightListPageResponse = + InsightListPageResponse.builder() + .addClusteringJob( + InsightListResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .name("name") + .status("status") + .configId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .endTime(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .error("error") + .metadata( + InsightListResponse.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .shape( + InsightListResponse.Shape.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .startTime(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + ) + .build() + + val roundtrippedInsightListPageResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(insightListPageResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedInsightListPageResponse).isEqualTo(insightListPageResponse) + } +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListParamsTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListParamsTest.kt new file mode 100644 index 000000000..318c96263 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListParamsTest.kt @@ -0,0 +1,65 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.langchain.smith.models.sessions.insights + +import com.langchain.smith.core.http.QueryParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class InsightListParamsTest { + + @Test + fun create() { + InsightListParams.builder() + .sessionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .configId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .legacy(true) + .limit(1L) + .offset(0L) + .build() + } + + @Test + fun pathParams() { + val params = + InsightListParams.builder().sessionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + assertThat(params._pathParam(0)).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + // out-of-bound path param + assertThat(params._pathParam(1)).isEqualTo("") + } + + @Test + fun queryParams() { + val params = + InsightListParams.builder() + .sessionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .configId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .legacy(true) + .limit(1L) + .offset(0L) + .build() + + val queryParams = params._queryParams() + + assertThat(queryParams) + .isEqualTo( + QueryParams.builder() + .put("config_id", "182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .put("legacy", "true") + .put("limit", "1") + .put("offset", "0") + .build() + ) + } + + @Test + fun queryParamsWithoutOptionalFields() { + val params = + InsightListParams.builder().sessionId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e").build() + + val queryParams = params._queryParams() + + assertThat(queryParams).isEqualTo(QueryParams.builder().build()) + } +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListResponseTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListResponseTest.kt new file mode 100644 index 000000000..e614af7af --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/sessions/insights/InsightListResponseTest.kt @@ -0,0 +1,96 @@ +// File generated from our OpenAPI spec by Stainless. + +package com.langchain.smith.models.sessions.insights + +import com.fasterxml.jackson.module.kotlin.jacksonTypeRef +import com.langchain.smith.core.JsonValue +import com.langchain.smith.core.jsonMapper +import java.time.OffsetDateTime +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +internal class InsightListResponseTest { + + @Test + fun create() { + val insightListResponse = + InsightListResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .name("name") + .status("status") + .configId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .endTime(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .error("error") + .metadata( + InsightListResponse.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .shape( + InsightListResponse.Shape.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .startTime(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + assertThat(insightListResponse.id()).isEqualTo("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(insightListResponse.createdAt()) + .isEqualTo(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(insightListResponse.name()).isEqualTo("name") + assertThat(insightListResponse.status()).isEqualTo("status") + assertThat(insightListResponse.configId()).contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + assertThat(insightListResponse.endTime()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(insightListResponse.error()).contains("error") + assertThat(insightListResponse.metadata()) + .contains( + InsightListResponse.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + assertThat(insightListResponse.shape()) + .contains( + InsightListResponse.Shape.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + assertThat(insightListResponse.startTime()) + .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + } + + @Test + fun roundtrip() { + val jsonMapper = jsonMapper() + val insightListResponse = + InsightListResponse.builder() + .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .name("name") + .status("status") + .configId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + .endTime(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .error("error") + .metadata( + InsightListResponse.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build() + ) + .shape( + InsightListResponse.Shape.builder() + .putAdditionalProperty("foo", JsonValue.from(0)) + .build() + ) + .startTime(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .build() + + val roundtrippedInsightListResponse = + jsonMapper.readValue( + jsonMapper.writeValueAsString(insightListResponse), + jacksonTypeRef(), + ) + + assertThat(roundtrippedInsightListResponse).isEqualTo(insightListResponse) + } +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsyncTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsyncTest.kt index 24df9c0e8..5d6b949b5 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsyncTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/sessions/InsightServiceAsyncTest.kt @@ -95,6 +95,23 @@ internal class InsightServiceAsyncTest { insight.validate() } + @Disabled("Mock server tests are disabled") + @Test + fun list() { + val client = + LangsmithOkHttpClientAsync.builder() + .apiKey("My API Key") + .tenantId("My Tenant ID") + .organizationId("My Organization ID") + .build() + val insightServiceAsync = client.sessions().insights() + + val pageFuture = insightServiceAsync.list("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + val page = pageFuture.get() + page.response().validate() + } + @Disabled("Mock server tests are disabled") @Test fun delete() { diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/sessions/InsightServiceTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/sessions/InsightServiceTest.kt index 16166a607..3eca7ce46 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/sessions/InsightServiceTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/sessions/InsightServiceTest.kt @@ -93,6 +93,22 @@ internal class InsightServiceTest { insight.validate() } + @Disabled("Mock server tests are disabled") + @Test + fun list() { + val client = + LangsmithOkHttpClient.builder() + .apiKey("My API Key") + .tenantId("My Tenant ID") + .organizationId("My Organization ID") + .build() + val insightService = client.sessions().insights() + + val page = insightService.list("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") + + page.response().validate() + } + @Disabled("Mock server tests are disabled") @Test fun delete() { From 1f8e4f065b48fe8474c48a649edf3b40cacb7b1d Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 30 Mar 2026 10:13:45 +0000 Subject: [PATCH 24/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index 157303fd6..45de7173b 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 103 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-bc1f302915c4d87fd6fc962d3789ae714d63b9f2164e3ef512a7be94cf0a2643.yml -openapi_spec_hash: 02460db53e7a9603d3d9b554e3589fa4 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-c8cfbe86e6def6ed237572671330ab268d0f4482ca206d46523a504d5202c78a.yml +openapi_spec_hash: e3c416da737cb6f4fb8945ca8010443d config_hash: c217b34d458f1b65f260715693d447f9 From ea6c3d29d7c726b7b8455e6e93ec3322330ea5e7 Mon Sep 17 00:00:00 2001 From: Jacob Lee Date: Mon, 30 Mar 2026 11:08:17 -0700 Subject: [PATCH 25/35] fix: Fix format detection when pulling legacy prompts (#115) * Fix format detection when pulling legacy prompts * Feedback --- AGENTS.md | 40 ++++++++++++ .../langchain/smith/prompts/ManifestParser.kt | 14 ++++- .../langchain/smith/prompts/PromptMessages.kt | 7 +++ .../smith/prompts/ManifestParserTest.kt | 61 +++++++++++++++++++ .../com/langchain/smith/prompts/PromptTest.kt | 41 +++++++++++++ 5 files changed, 160 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 253148492..a0b8c8532 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -157,6 +157,25 @@ The project uses ktfmt with `--kotlinlang-style`. ## Testing +### Don't add comments that restate the test name + +Test function names should be descriptive enough on their own. Don't add comments that repeat what the name already says: + +```kotlin +// Good — name is self-documenting +@Test +fun parseLegacyPromptTemplateWithTemplateFormat() { + val manifest = ... +} + +// Bad — comment restates the function name +@Test +fun parseLegacyPromptTemplateWithTemplateFormat() { + // Legacy PromptTemplate format with template_format field + val manifest = ... +} +``` + ### Running tests ```bash @@ -189,4 +208,25 @@ Tests skip gracefully via `assumeTrue` if keys are missing. - `toString()` should be single-line, following the `ClassName{field=value, field=value}` convention used by the rest of the SDK. - Avoid `@Suppress("UNCHECKED_CAST")` — restructure code to use safe patterns (`as? String`, `is Map<*, *>` with `entries.associate`, etc). +- Use named arguments for constructor/function calls with 2+ parameters, especially when types could be confused: + ```kotlin + // Good + PromptMessage( + role = PromptMessage.Role.HUMAN, + template = template, + templateFormat = templateFormat, + ) + + // Bad — positional args are ambiguous + PromptMessage(PromptMessage.Role.HUMAN, template, templateFormat = templateFormat) + ``` +- When an `Optional` has a fallback default, use `orElse(default)` directly instead of `orElse(null) ?: default`: + ```kotlin + // Good — default goes straight into orElse + kwargs["template_format"]?.asString()?.orElse("f-string") ?: "f-string" + + // Bad — creates unnecessary null intermediary + kwargs["template_format"]?.asString()?.orElse(null) ?: "f-string" + ``` + The `?: "f-string"` is still needed to handle the case where the key is missing from the map (`null` from `kwargs["template_format"]`), but `orElse` should carry the default for when the key exists but isn't a string. - Anthropic SDK is a `compileOnly` dependency — users must add it themselves. Methods that use Anthropic types should catch `NoClassDefFoundError` and throw `IllegalStateException` with a clear message. diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/prompts/ManifestParser.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/prompts/ManifestParser.kt index 09f21e561..887ea1f47 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/prompts/ManifestParser.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/prompts/ManifestParser.kt @@ -102,9 +102,17 @@ internal object ManifestParser { kwargs["template"]?.asString()?.orElse(null) ?: throw IllegalArgumentException("PromptTemplate missing 'template' in kwargs") + val templateFormat = kwargs["template_format"]?.asString()?.orElse("f-string") ?: "f-string" val inputVariables = extractInputVariables(kwargs) - return PromptMessages(listOf(PromptMessage.human(template)), inputVariables) + return PromptMessages.of( + PromptMessage( + role = PromptMessage.Role.HUMAN, + template = template, + templateFormat = templateFormat, + ), + inputVariables, + ) } /** Holds a parsed template string and its format. */ @@ -164,7 +172,7 @@ internal object ManifestParser { private fun extractTemplate(kwargs: Map): TemplateInfo? { // Check for direct template kwargs["template"]?.asString()?.orElse(null)?.let { tmpl -> - val fmt = kwargs["template_format"]?.asString()?.orElse(null) ?: "f-string" + val fmt = kwargs["template_format"]?.asString()?.orElse("f-string") ?: "f-string" return TemplateInfo(tmpl, fmt) } @@ -172,7 +180,7 @@ internal object ManifestParser { val prompt = kwargs["prompt"]?.asObject()?.orElse(null) ?: return null val promptKwargs = extractKwargs(prompt) val tmpl = promptKwargs["template"]?.asString()?.orElse(null) ?: return null - val fmt = promptKwargs["template_format"]?.asString()?.orElse(null) ?: "f-string" + val fmt = promptKwargs["template_format"]?.asString()?.orElse("f-string") ?: "f-string" return TemplateInfo(tmpl, fmt) } diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/prompts/PromptMessages.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/prompts/PromptMessages.kt index 50d00ff56..52d3089fa 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/prompts/PromptMessages.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/prompts/PromptMessages.kt @@ -114,6 +114,13 @@ internal class PromptMessages( } return "PromptMessages{${parts.joinToString(", ")}}" } + + companion object { + + /** Creates a [PromptMessages] from a single message and input variables. */ + fun of(message: PromptMessage, inputVariables: List): PromptMessages = + PromptMessages(listOf(message), inputVariables) + } } private fun toPromptMessage(value: Any?): PromptMessage? = diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/ManifestParserTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/ManifestParserTest.kt index 9c5257e49..3991b9fcc 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/ManifestParserTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/ManifestParserTest.kt @@ -114,6 +114,32 @@ internal class ManifestParserTest { assertThat(result.inputVariables).containsExactly("topic") } + @Test + fun parseLegacyPromptTemplateWithTemplateFormat() { + val manifest = + mapOf( + "lc" to 1, + "type" to "constructor", + "id" to listOf("langchain_core", "prompts", "prompt", "PromptTemplate"), + "kwargs" to + mapOf( + "input_variables" to listOf("input"), + "template_format" to "f-string", + "template" to + "You are a parrot. The current date is 2026-03-29T14:26:33.834Z\n{input}", + ), + ) + + val result = ManifestParser.parse(JsonValue.from(manifest)) + + assertThat(result.messages).hasSize(1) + assertThat(result.messages[0].role).isEqualTo(PromptMessage.Role.HUMAN) + assertThat(result.messages[0].template) + .isEqualTo("You are a parrot. The current date is 2026-03-29T14:26:33.834Z\n{input}") + assertThat(result.messages[0].templateFormat).isEqualTo("f-string") + assertThat(result.inputVariables).containsExactly("input") + } + @Test fun parseDirectTemplateInKwargs() { // Some manifests have the template directly in the message kwargs, @@ -144,6 +170,41 @@ internal class ManifestParserTest { assertThat(result.messages[0].template).isEqualTo("Direct template text") } + @Test + fun parseDirectTemplateWithTemplateFormat() { + // Test that template_format is preserved in direct template pattern + val manifest = + buildChatPromptManifest( + messages = + listOf( + mapOf( + "lc" to 1, + "type" to "constructor", + "id" to + listOf( + "langchain_core", + "prompts", + "chat", + "HumanMessagePromptTemplate", + ), + "kwargs" to + mapOf( + "template" to "Hello {{name}}", + "template_format" to "mustache", + ), + ) + ), + inputVariables = listOf("name"), + ) + + val result = ManifestParser.parse(JsonValue.from(manifest)) + + assertThat(result.messages).hasSize(1) + assertThat(result.messages[0].role).isEqualTo(PromptMessage.Role.HUMAN) + assertThat(result.messages[0].template).isEqualTo("Hello {{name}}") + assertThat(result.messages[0].templateFormat).isEqualTo("mustache") + } + @Test fun parseManifestWithoutExplicitId() { // Falls back to detecting type from kwargs structure diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptTest.kt index 3c9559e0b..1cdb00a94 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/prompts/PromptTest.kt @@ -66,4 +66,45 @@ internal class PromptTest { assertThat(prompt.hasOutputSchema()).isFalse() assertThat(prompt.outputSchema).isNull() } + + @Test + fun legacyPromptTemplateEndToEnd() { + val prompt = + promptFromManifest( + mapOf( + "lc" to 1, + "type" to "constructor", + "id" to listOf("langchain_core", "prompts", "prompt", "PromptTemplate"), + "kwargs" to + mapOf( + "input_variables" to listOf("input"), + "template_format" to "f-string", + "template" to + "You are a parrot. The current date is 2026-03-29T14:26:33.834Z\n{input}", + ), + ) + ) + + assertThat(prompt.inputVariables).containsExactly("input") + + val result = prompt.invoke(mapOf("input" to "Hello world!")) + + assertThat(result.messages).hasSize(1) + assertThat(result.messages[0].role).isEqualTo(PromptMessage.Role.HUMAN) + assertThat(result.messages[0].template) + .isEqualTo( + "You are a parrot. The current date is 2026-03-29T14:26:33.834Z\nHello world!" + ) + } + + /** Creates a [Prompt] from a raw manifest map, simulating the pull → parse flow. */ + private fun promptFromManifest(manifest: Map): Prompt = + Prompt.fromCommit( + PromptCommit.of( + owner = "test", + repo = "test", + commitHash = "test", + manifest = com.langchain.smith.core.JsonValue.from(manifest), + ) + ) } From 07c760434cdae34a9bc61d3586ab03a5f2828fd5 Mon Sep 17 00:00:00 2001 From: Jacob Lee Date: Mon, 30 Mar 2026 11:45:08 -0700 Subject: [PATCH 26/35] Update AGENTS.md (#116) --- AGENTS.md | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a0b8c8532..a17ffbf54 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,20 +178,24 @@ fun parseLegacyPromptTemplateWithTemplateFormat() { ### Running tests +Try to run targeted tests matching the code you changed: + ```bash -# All prompt tests (unit + integration) -./gradlew :langsmith-java-core:test --tests "com.langchain.smith.prompts.*" +# Run tests for the package you changed +./gradlew :langsmith-java-core:test --tests "com.langchain.smith.prompts.*" --rerun -# Just integration tests (requires API keys) -./gradlew :langsmith-java-core:test --tests "com.langchain.smith.prompts.PromptIntegrationTest" +# Run a single test class +./gradlew :langsmith-java-core:test --tests "com.langchain.smith.prompts.ManifestParserTest" --rerun -# Force re-run (skip Gradle cache) -./gradlew :langsmith-java-core:test --tests "..." --rerun +# Run a single test method +./gradlew :langsmith-java-core:test --tests "com.langchain.smith.prompts.ManifestParserTest.parsePromptTemplate" --rerun # See println output ./gradlew :langsmith-java-core:test --tests "..." --rerun --info ``` +Only run the full suite (`./gradlew :langsmith-java-core:test --rerun`) before finalizing a PR or after large cross-cutting changes. + ### Integration tests Integration tests require environment variables: From 63e0bdc5c893185399065c2c602ed0d5c46bbc68 Mon Sep 17 00:00:00 2001 From: Jacob Lee Date: Mon, 30 Mar 2026 12:54:22 -0700 Subject: [PATCH 27/35] feat: Rework wrapOpenAI (#114) * Update wrapOpenAI * Remove * Fixes * nits * Feedback * Cache * Remove comment * Fix --- langsmith-java-core/build.gradle.kts | 4 +- .../langchain/smith/tracing/TraceProcessIO.kt | 10 +- .../com/langchain/smith/tracing/Traceable.kt | 10 +- .../wrappers/openai/ExperimentContext.kt | 91 --- .../wrappers/openai/OpenTelemetryConfig.kt | 271 --------- .../smith/wrappers/openai/TracingUtils.kt | 225 ++++--- .../smith/wrappers/openai/WrapOpenAI.kt | 204 +++++++ .../wrappers/openai/WrappedChatService.kt | 573 ------------------ .../wrappers/openai/WrappedOpenAIClient.kt | 104 ---- .../wrappers/openai/WrappedResponseService.kt | 414 ------------- .../langchain/smith/tracing/TraceableTest.kt | 273 --------- .../smith/wrappers/openai/TracingUtilsTest.kt | 329 ++++++++++ .../openai/WrapOpenAISerializationTest.kt | 178 ++++++ .../smith/wrappers/openai/WrapOpenAITest.kt | 254 ++++++++ .../langchain/smith/example/E2eEvalExample.kt | 285 --------- .../example/StreamingLangSmithExample.kt | 138 ----- .../smith/example/WrapOpenAIExample.kt | 49 ++ .../smith/example/otel/OtelOpenAIExample.kt | 285 --------- 18 files changed, 1183 insertions(+), 2514 deletions(-) delete mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/ExperimentContext.kt delete mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/OpenTelemetryConfig.kt create mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAI.kt delete mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedChatService.kt delete mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedOpenAIClient.kt delete mode 100644 langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedResponseService.kt create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/TracingUtilsTest.kt create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAISerializationTest.kt create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAITest.kt delete mode 100644 langsmith-java-example/src/main/kotlin/com/langchain/smith/example/E2eEvalExample.kt delete mode 100644 langsmith-java-example/src/main/kotlin/com/langchain/smith/example/StreamingLangSmithExample.kt create mode 100644 langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIExample.kt delete mode 100644 langsmith-java-example/src/main/kotlin/com/langchain/smith/example/otel/OtelOpenAIExample.kt diff --git a/langsmith-java-core/build.gradle.kts b/langsmith-java-core/build.gradle.kts index 878625786..0252bfe75 100644 --- a/langsmith-java-core/build.gradle.kts +++ b/langsmith-java-core/build.gradle.kts @@ -52,8 +52,8 @@ dependencies { api("io.opentelemetry:opentelemetry-exporter-otlp:1.32.0") api("io.opentelemetry.semconv:opentelemetry-semconv:1.23.1-alpha") - // OpenAI SDK (for OpenTelemetry wrappers) - api("com.openai:openai-java:4.6.1") + // OpenAI SDK (for wrapOpenAI tracing wrapper) + api("com.openai:openai-java:4.30.0") // Mustache template engine (for prompt template formatting) implementation("com.samskivert:jmustache:1.16") diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt index 15fb26162..4af01a810 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt @@ -8,9 +8,13 @@ import java.util.function.Function * Typed processors for transforming inputs and outputs before they are recorded on a traced run. * * The type parameters describe what the processors receive: - * - [PI] — the type passed to [inputs]. For 1-arg traced functions this is the raw input type; for - * 0/2/3-arg functions this is `Map` (the packed representation). - * - [PO] — the type passed to [outputs]. This is always the raw output type of the traced function. + * - [PI] — the type passed to `processInputs`. Depends on the arity of the traced function: + * - **1-arg** ([traceFunction]): the raw input type (e.g. `String`) + * - **0-arg** ([traceSupplier]): `Map` (empty map) + * - **2-arg** ([traceBiFunction]): `Pair` + * - **3-arg** ([traceTriFunction]): `Triple` + * - [PO] — the type passed to `processOutputs`. This is always the raw output type of the traced + * function. * * When [inputs] is set, it replaces the default input serialization entirely. Same for [outputs]. * diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt index 2d00d0cac..3a4dcb7e9 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt @@ -464,8 +464,9 @@ fun traceable(block: Function, config: TraceConfig): Function fun traceable(block: (I1, I2) -> O, config: TraceConfig): (I1, I2) -> O { val resolvedConfig = resolveConfig(config, block) return { i1, i2 -> - val packed = mapOf("args" to listOf(i1, i2)) - val serializedInputs = applyProcessInputs(resolvedConfig, packed) ?: packed + val rawArgs = Pair(i1, i2) + val serializedInputs = + applyProcessInputs(resolvedConfig, rawArgs) ?: mapOf("args" to listOf(i1, i2)) executeTraced(resolvedConfig, serializedInputs) { block(i1, i2) } } } @@ -484,8 +485,9 @@ fun traceable( fun traceable(block: (I1, I2, I3) -> O, config: TraceConfig): (I1, I2, I3) -> O { val resolvedConfig = resolveConfig(config, block) return { i1, i2, i3 -> - val packed = mapOf("args" to listOf(i1, i2, i3)) - val serializedInputs = applyProcessInputs(resolvedConfig, packed) ?: packed + val rawArgs = Triple(i1, i2, i3) + val serializedInputs = + applyProcessInputs(resolvedConfig, rawArgs) ?: mapOf("args" to listOf(i1, i2, i3)) executeTraced(resolvedConfig, serializedInputs) { block(i1, i2, i3) } } } diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/ExperimentContext.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/ExperimentContext.kt deleted file mode 100644 index 9d613c223..000000000 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/ExperimentContext.kt +++ /dev/null @@ -1,91 +0,0 @@ -package com.langchain.smith.wrappers.openai - -import io.opentelemetry.context.Context -import io.opentelemetry.context.ContextKey -import io.opentelemetry.context.Scope -import java.util.Optional - -/** - * Immutable context for experiment metadata that will be automatically attached to OpenTelemetry - * spans. - * - * When you set experiment context using this class, the wrapped OpenAI client will automatically - * attach it to the spans it creates. Follows the OpenTelemetry Context pattern with immutable - * context objects and explicit scope management. - * - * Example (recommended - use scope): - * ``` - * ExperimentContext.withExperiment("example-123", "session-789").use { scope -> - * val completion = client.chat().completions().create(params) - * } - * ``` - * - * Thread Safety: This class is thread-safe. Each thread maintains its own context via - * OpenTelemetry's Context mechanism. - */ -class ExperimentContext private constructor(private val data: ExperimentData) { - - fun withReferenceExampleId(exampleId: String): ExperimentContext { - require(exampleId.isNotBlank()) { "exampleId cannot be null or empty" } - return ExperimentContext(data.withReferenceExampleId(exampleId)) - } - - fun withSessionId(sessionId: String): ExperimentContext { - require(sessionId.isNotBlank()) { "sessionId cannot be null or empty" } - return ExperimentContext(data.withSessionId(sessionId)) - } - - fun withMetadata(key: String, value: String): ExperimentContext { - require(key.isNotBlank()) { "metadata key cannot be null or empty" } - require(value.isNotBlank()) { "metadata value cannot be null or empty" } - return ExperimentContext(data.withMetadata(key, value)) - } - - private fun makeCurrent(): Scope { - val otelContext = Context.current().with(CONTEXT_KEY, data) - return otelContext.makeCurrent() - } - - fun getReferenceExampleId(): Optional = Optional.ofNullable(data.referenceExampleId) - - fun getSessionId(): Optional = Optional.ofNullable(data.sessionId) - - fun getMetadata(): Map = data.metadata - - companion object { - private val CONTEXT_KEY = ContextKey.named("langsmith-experiment-context") - - @JvmStatic - fun current(): ExperimentContext { - val otelContext = Context.current() - val data = otelContext.get(CONTEXT_KEY) ?: ExperimentData.empty() - return ExperimentContext(data) - } - - @JvmStatic - fun withExperiment(exampleId: String, sessionId: String): Scope { - require(exampleId.isNotBlank()) { "exampleId cannot be null or empty" } - require(sessionId.isNotBlank()) { "sessionId cannot be null or empty" } - return current() - .withReferenceExampleId(exampleId) - .withSessionId(sessionId) - .makeCurrent() - } - } - - private data class ExperimentData( - val referenceExampleId: String?, - val sessionId: String?, - val metadata: Map, - ) { - fun withReferenceExampleId(exampleId: String) = copy(referenceExampleId = exampleId) - - fun withSessionId(sessionId: String) = copy(sessionId = sessionId) - - fun withMetadata(key: String, value: String) = copy(metadata = metadata + (key to value)) - - companion object { - fun empty() = ExperimentData(null, null, emptyMap()) - } - } -} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/OpenTelemetryConfig.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/OpenTelemetryConfig.kt deleted file mode 100644 index 496090bca..000000000 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/OpenTelemetryConfig.kt +++ /dev/null @@ -1,271 +0,0 @@ -package com.langchain.smith.wrappers.openai - -import io.opentelemetry.api.GlobalOpenTelemetry -import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter -import io.opentelemetry.sdk.OpenTelemetrySdk -import io.opentelemetry.sdk.common.CompletableResultCode -import io.opentelemetry.sdk.resources.Resource -import io.opentelemetry.sdk.trace.SdkTracerProvider -import io.opentelemetry.sdk.trace.SpanProcessor -import io.opentelemetry.sdk.trace.data.SpanData -import io.opentelemetry.sdk.trace.export.BatchSpanProcessor -import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor -import io.opentelemetry.sdk.trace.export.SpanExporter -import java.io.PrintWriter -import java.io.StringWriter -import java.util.concurrent.TimeUnit -import org.slf4j.LoggerFactory - -/** - * Configuration utility for setting up OpenTelemetry to export traces to LangSmith. - * - * Example usage: - * ``` - * OpenTelemetryConfig.builder() - * .apiKey("your-langsmith-api-key") - * .projectName("your-project-name") - * .build() - * - * // Or using only environment variables (LANGSMITH_API_KEY, LANGSMITH_PROJECT) - * OpenTelemetryConfig.builder().build() - * - * val client = WrappedOpenAIClient.fromEnv() - * ``` - */ -object OpenTelemetryConfig { - private val logger = LoggerFactory.getLogger(OpenTelemetryConfig::class.java) - - const val DEFAULT_BASE_URL: String = "https://api.smith.langchain.com" - const val OTLP_TRACES_PATH: String = "/otel/v1/traces" - - enum class SpanProcessorType { - /** Batch export - best for production. */ - BATCH, - /** Simple synchronous export on span.end() - best for testing. */ - SIMPLE, - } - - @JvmStatic fun builder(): Builder = Builder() - - @JvmStatic fun flush(): Boolean = flush(5, TimeUnit.SECONDS) - - @JvmStatic - fun flush(timeout: Long, unit: TimeUnit): Boolean { - val openTelemetry = GlobalOpenTelemetry.get() - if (openTelemetry is OpenTelemetrySdk) { - val tracerProvider = openTelemetry.getSdkTracerProvider() - if (tracerProvider != null) { - return try { - val result = tracerProvider.forceFlush() - result.join(timeout, unit) - if (!result.isSuccess) logger.warn("Flush did not complete successfully") - result.isSuccess - } catch (e: Exception) { - logger.warn("Failed to flush spans", e) - false - } - } - } - return true - } - - @JvmStatic - fun shutdown() { - val openTelemetry = GlobalOpenTelemetry.get() - if (openTelemetry is OpenTelemetrySdk) { - val tracerProvider = openTelemetry.getSdkTracerProvider() - if (tracerProvider != null) { - try { - tracerProvider.shutdown().join(5, TimeUnit.SECONDS) - } catch (e: Exception) { - logger.warn("Failed to shutdown OpenTelemetry", e) - } - } - } - } - - private fun buildOtlpEndpoint(baseUrl: String?): String { - val base = - (baseUrl?.takeIf { it.isNotBlank() } - ?: System.getenv("LANGSMITH_ENDPOINT")?.takeIf { it.isNotBlank() } - ?: DEFAULT_BASE_URL) - .trim() - .removeSuffix("/") - return base + OTLP_TRACES_PATH - } - - class Builder { - private var apiKey: String? = System.getenv("LANGSMITH_API_KEY") - private var projectName: String? = System.getenv("LANGSMITH_PROJECT") - private var serviceName: String? = System.getenv("OTEL_SERVICE_NAME") - private var baseUrl: String? = System.getenv("LANGSMITH_ENDPOINT") - private var processorType: SpanProcessorType = SpanProcessorType.BATCH - private var maxBatchSize: Int = 512 - - fun apiKey(apiKey: String) = apply { this.apiKey = apiKey } - - fun projectName(projectName: String?) = apply { this.projectName = projectName } - - fun serviceName(serviceName: String?) = apply { this.serviceName = serviceName } - - fun baseUrl(baseUrl: String?) = apply { this.baseUrl = baseUrl } - - fun processorType(processorType: SpanProcessorType) = apply { - this.processorType = processorType - } - - fun maxBatchSize(maxBatchSize: Int) = apply { this.maxBatchSize = maxBatchSize } - - fun buildSpanProcessor(): SpanProcessor { - require(!apiKey.isNullOrEmpty()) { - "LangSmith API key is required. Set it using apiKey() or LANGSMITH_API_KEY environment variable." - } - val endpointUrl = buildOtlpEndpoint(baseUrl) - val exporterBuilder = - OtlpHttpSpanExporter.builder() - .setEndpoint(endpointUrl) - .addHeader("x-api-key", apiKey!!) - if (!projectName.isNullOrEmpty()) { - exporterBuilder.addHeader("Langsmith-Project", projectName!!) - } - val spanExporter = exporterBuilder.build() - val loggingExporter = LoggingSpanExporter(spanExporter) - return when (processorType) { - SpanProcessorType.SIMPLE -> SimpleSpanProcessor.create(loggingExporter) - SpanProcessorType.BATCH -> - BatchSpanProcessor.builder(loggingExporter) - .setScheduleDelay(100, TimeUnit.MILLISECONDS) - .setMaxExportBatchSize(maxBatchSize) - .setExporterTimeout(5, TimeUnit.SECONDS) - .build() - } - } - - fun build(): io.opentelemetry.api.OpenTelemetry { - require(!apiKey.isNullOrEmpty()) { - "LangSmith API key is required. Set it using apiKey() or LANGSMITH_API_KEY environment variable." - } - val endpointUrl = buildOtlpEndpoint(baseUrl) - val exporterBuilder = - OtlpHttpSpanExporter.builder() - .setEndpoint(endpointUrl) - .addHeader("x-api-key", apiKey!!) - if (!projectName.isNullOrEmpty()) { - exporterBuilder.addHeader("Langsmith-Project", projectName!!) - } - val spanExporter = exporterBuilder.build() - val loggingExporter = LoggingSpanExporter(spanExporter) - val resource = - Resource.getDefault() - .merge( - Resource.builder() - .put("service.name", serviceName ?: "langsmith-java-otel-wrappers") - .build() - ) - val spanProcessor = - when (processorType) { - SpanProcessorType.SIMPLE -> SimpleSpanProcessor.create(loggingExporter) - SpanProcessorType.BATCH -> - BatchSpanProcessor.builder(loggingExporter) - .setScheduleDelay(100, TimeUnit.MILLISECONDS) - .setMaxExportBatchSize(maxBatchSize) - .setExporterTimeout(5, TimeUnit.SECONDS) - .build() - } - val tracerProvider = - SdkTracerProvider.builder() - .addSpanProcessor(spanProcessor) - .setResource(resource) - .build() - return OpenTelemetrySdk.builder() - .setTracerProvider(tracerProvider) - .buildAndRegisterGlobal() - } - - private fun buildOtlpEndpoint(baseUrl: String?): String = - OpenTelemetryConfig.buildOtlpEndpoint(baseUrl) - } - - private class LoggingSpanExporter(private val delegate: SpanExporter) : SpanExporter { - override fun export(spans: Collection): CompletableResultCode { - if (DEBUG) { - logger.debug("[LangSmith] Exporting ${spans.size} span(s):") - for (span in spans) { - logger.debug( - " - ${span.name} (kind=${span.kind}, attributes=${span.attributes.size()})" - ) - } - } - val result = delegate.export(spans) - // Always wait for export to complete so flush/shutdown don't run before the HTTP - // request finishes. Without this, shutdown can abort in-flight exports and traces are - // lost. - try { - result.join(5, TimeUnit.SECONDS) - } catch (e: Exception) { - if (DEBUG) logger.error("[LangSmith ERROR] Exception waiting for export result", e) - else logger.error("[LangSmith] Exception waiting for export result", e) - } - if (!result.isSuccess) { - logger.error( - "[LangSmith ERROR] Failed to export ${spans.size} span(s) to LangSmith" - ) - logExportException(result) - if (DEBUG) { - for (span in spans) { - logger.error( - " - ${span.name} (traceId=${span.traceId}, spanId=${span.spanId})" - ) - } - logger.error( - " This usually indicates a network error, authentication problem, or invalid span data" - ) - logger.error(" Check your LANGSMITH_API_KEY and network connectivity") - } else { - logger.error(" Set LANGSMITH_DEBUG=true for more details") - } - } else if (DEBUG) { - logger.debug("[LangSmith] Successfully exported ${spans.size} span(s)") - } - return result - } - - override fun flush(): CompletableResultCode { - if (DEBUG) logger.debug("[LangSmith] Flushing spans...") - val result = delegate.flush() - result.whenComplete { - if (!result.isSuccess) logger.error("[LangSmith ERROR] Failed to flush spans") - else if (DEBUG) logger.debug("[LangSmith] Flush completed successfully") - } - return result - } - - override fun shutdown(): CompletableResultCode { - if (DEBUG) logger.debug("[LangSmith] Shutting down span exporter...") - return delegate.shutdown() - } - - companion object { - private val logger = LoggerFactory.getLogger(LoggingSpanExporter::class.java) - private val DEBUG = - java.lang.Boolean.getBoolean("langsmith.debug") || - "true".equals(System.getenv("LANGSMITH_DEBUG"), ignoreCase = true) - - private fun logExportException(result: CompletableResultCode) { - try { - val getExceptionMethod = result.javaClass.getMethod("getException") - val exception = getExceptionMethod.invoke(result) as? Throwable - if (exception != null) { - logger.error(" Error: ${exception.message}") - exception.cause?.let { logger.error(" Caused by: ${it.message}") } - if (DEBUG) { - val sw = StringWriter() - exception.printStackTrace(PrintWriter(sw)) - logger.debug(" Stack trace:\n${sw}") - } - } - } catch (_: Exception) {} - } - } - } -} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/TracingUtils.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/TracingUtils.kt index 481fa4276..170c4b7f7 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/TracingUtils.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/TracingUtils.kt @@ -1,90 +1,173 @@ package com.langchain.smith.wrappers.openai -import com.fasterxml.jackson.databind.ObjectMapper -import io.opentelemetry.api.common.AttributeKey -import io.opentelemetry.api.trace.Span -import io.opentelemetry.api.trace.SpanBuilder -import io.opentelemetry.api.trace.SpanKind -import io.opentelemetry.api.trace.Tracer - -/** Internal utility for OpenTelemetry span creation and management. */ -internal object TracingUtils { - private const val INSTRUMENTATION_NAME = "langsmith-java-otel-wrappers" - private val jsonMapper = ObjectMapper() - - fun getTracer(): Tracer = - io.opentelemetry.api.GlobalOpenTelemetry.get().getTracer(INSTRUMENTATION_NAME) - - fun createSpanBuilder( - model: String?, - operationType: String, - spanKind: String? = "llm", - ): SpanBuilder { - val tracer = getTracer() - val spanName = "$operationType ${model ?: "unknown"}" - val builder = - tracer - .spanBuilder(spanName) - .setSpanKind(SpanKind.CLIENT) - .setAttribute(AttributeKey.stringKey("gen_ai.system"), "openai") - .setAttribute(AttributeKey.stringKey("gen_ai.operation.name"), operationType) - .setAttribute(AttributeKey.stringKey("gen_ai.provider.name"), "openai") - spanKind?.let { builder.setAttribute(AttributeKey.stringKey("langsmith.span.kind"), it) } - return builder - } +import com.fasterxml.jackson.core.type.TypeReference +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper +import com.langchain.smith.tracing.getCurrentRunTree +import com.openai.core.jsonMapper +import com.openai.models.chat.completions.ChatCompletionCreateParams +import com.openai.models.responses.ResponseCreateParams - fun setRequestAttributes(span: Span, model: String?) { - model?.let { span.setAttribute(AttributeKey.stringKey("gen_ai.request.model"), it) } - } +/** + * The OpenAI SDK's own ObjectMapper — understands JsonField, @ExcludeMissing, and @JsonProperty + * annotations. Used to serialize OpenAI SDK model types (Body, ChatCompletion, Response) which rely + * on explicit @JsonProperty annotations with snake_case keys rather than getter auto-detection. + */ +private val openAIMapper = jsonMapper() - fun setRequestParameters(span: Span, temperature: Double?, topP: Double?, maxTokens: Long?) { - temperature?.let { - span.setAttribute(AttributeKey.doubleKey("gen_ai.request.temperature"), it) - } - topP?.let { span.setAttribute(AttributeKey.doubleKey("gen_ai.request.top_p"), it) } - maxTokens?.let { span.setAttribute(AttributeKey.longKey("gen_ai.request.max_tokens"), it) } - } +/** A standard Jackson mapper for general-purpose serialization (e.g. RequestOptions). */ +private val genericMapper = jacksonObjectMapper() - fun setInputMessages(span: Span, messagesJson: String?) { - messagesJson?.let { span.setAttribute(AttributeKey.stringKey("gen_ai.input.messages"), it) } - } +private val MAP_TYPE = object : TypeReference>() {} + +/** + * Converts an OpenAI SDK model object to a `Map` using the OpenAI SDK's own + * ObjectMapper, which correctly handles @JsonProperty, @ExcludeMissing, and JsonField. + */ +internal fun toMap(value: Any): Map = openAIMapper.convertValue(value, MAP_TYPE) + +/** + * Converts a general object to a `Map` using a standard Jackson mapper with getter + * auto-detection. Used for non-OpenAI types like `RequestOptions`. + */ +internal fun toGenericMap(value: Any): Map = + genericMapper.convertValue(value, MAP_TYPE) + +/** + * Serializes [ChatCompletionCreateParams] to a `Map` using the inner Body (which has + * proper `@JsonProperty` snake_case annotations), matching the OpenAI REST API wire format. + */ +internal fun chatParamsToMap(params: ChatCompletionCreateParams): Map = + toMap(params._body()) + +/** + * Serializes [ResponseCreateParams] to a `Map` using the inner Body (which has proper + * `@JsonProperty` snake_case annotations), matching the OpenAI REST API wire format. + */ +internal fun responseParamsToMap(params: ResponseCreateParams): Map = + toMap(params._body()) + +// Keys from the request params that go into ls_invocation_params (matching JS SDK) +internal val TRACED_INVOCATION_KEYS = + setOf( + "frequency_penalty", + "n", + "logit_bias", + "logprobs", + "modalities", + "parallel_tool_calls", + "prediction", + "presence_penalty", + "prompt_cache_key", + "reasoning", + "reasoning_effort", + "response_format", + "seed", + "service_tier", + "stream_options", + "top_logprobs", + "top_p", + "truncation", + "user", + "verbosity", + "web_search_options", + ) + +/** + * Processes a chat completion output to restructure usage into `usage_metadata`, matching the + * LangSmith JS SDK's `processChatCompletion`. + */ +internal fun processChatCompletionOutput(raw: Map): Map { + val result = raw.toMutableMap() + val usage = result.remove("usage") + if (usage is Map<*, *>) { + val serviceTier = result["service_tier"] as? String + val recognized = if (serviceTier in listOf("priority", "flex")) serviceTier else null + val prefix = if (recognized != null) "${recognized}_" else "" + + // Chat completions use prompt_tokens/completion_tokens + // Responses API uses input_tokens/output_tokens + val inputTokens = (usage["prompt_tokens"] ?: usage["input_tokens"]) as? Number ?: 0 + val outputTokens = (usage["completion_tokens"] ?: usage["output_tokens"]) as? Number ?: 0 + val totalTokens = (usage["total_tokens"]) as? Number ?: 0 + + val inputTokenDetails = mutableMapOf() + val outputTokenDetails = mutableMapOf() - fun setOutputMessages(span: Span, messagesJson: String?) { - messagesJson?.let { - span.setAttribute(AttributeKey.stringKey("gen_ai.output.messages"), it) + // Chat completions token details + val promptDetails = usage["prompt_tokens_details"] as? Map<*, *> + val completionDetails = usage["completion_tokens_details"] as? Map<*, *> + // Responses API token details + val inputDetails = usage["input_tokens_details"] as? Map<*, *> + val outputDetails = usage["output_tokens_details"] as? Map<*, *> + + val cachedTokens = promptDetails?.get("cached_tokens") ?: inputDetails?.get("cached_tokens") + if (cachedTokens != null) { + inputTokenDetails["${prefix}cache_read"] = cachedTokens } - } - fun setResponseAttributes( - span: Span, - inputTokens: Long?, - outputTokens: Long?, - totalTokens: Long?, - ) { - inputTokens?.let { - span.setAttribute(AttributeKey.longKey("gen_ai.usage.input_tokens"), it) + val audioInputTokens = promptDetails?.get("audio_tokens") + if (audioInputTokens != null) { + inputTokenDetails["audio"] = audioInputTokens } - outputTokens?.let { - span.setAttribute(AttributeKey.longKey("gen_ai.usage.output_tokens"), it) + + val reasoningTokens = + completionDetails?.get("reasoning_tokens") ?: outputDetails?.get("reasoning_tokens") + if (reasoningTokens != null) { + outputTokenDetails["${prefix}reasoning"] = reasoningTokens } - totalTokens?.let { - span.setAttribute(AttributeKey.longKey("gen_ai.usage.total_tokens"), it) + + val audioOutputTokens = completionDetails?.get("audio_tokens") + if (audioOutputTokens != null) { + outputTokenDetails["audio"] = audioOutputTokens } - } - fun setResponseMetadata(span: Span, responseModel: String?, finishReason: String?) { - responseModel?.let { - span.setAttribute(AttributeKey.stringKey("gen_ai.response.model"), it) + if (recognized != null) { + val cacheRead = (inputTokenDetails["${prefix}cache_read"] as? Number)?.toLong() ?: 0L + inputTokenDetails[recognized] = inputTokens.toLong() - cacheRead + val reasoning = (outputTokenDetails["${prefix}reasoning"] as? Number)?.toLong() ?: 0L + outputTokenDetails[recognized] = outputTokens.toLong() - reasoning } - finishReason?.let { - span.setAttribute(AttributeKey.stringKey("gen_ai.response.finish_reason"), it) + + result["usage_metadata"] = buildMap { + put("input_tokens", inputTokens) + put("output_tokens", outputTokens) + put("total_tokens", totalTokens) + if (inputTokenDetails.isNotEmpty()) put("input_token_details", inputTokenDetails) + if (outputTokenDetails.isNotEmpty()) put("output_token_details", outputTokenDetails) } } + return result +} - fun recordException(span: Span, exception: Throwable) { - span.recordException(exception) - span.setAttribute(AttributeKey.booleanKey("error"), true) +/** + * Extracts invocation params from chat completion request params and sets them as metadata on the + * current run, matching the JS SDK's `getInvocationParams`. + */ +internal fun setInvocationParams(params: Map, useResponsesApi: Boolean) { + val run = getCurrentRunTree() ?: return + + val invocationParams = mutableMapOf() + for ((key, value) in params) { + if (key in TRACED_INVOCATION_KEYS) { + invocationParams[key] = value + } + } + if (useResponsesApi) { + invocationParams["use_responses_api"] = true } - fun writeJson(value: Any): String = jsonMapper.writeValueAsString(value) + run.metadata["ls_provider"] = "openai" + run.metadata["ls_model_type"] = "chat" + params["model"]?.let { run.metadata["ls_model_name"] = it } + (params["max_completion_tokens"] ?: params["max_tokens"])?.let { + run.metadata["ls_max_tokens"] = it + } + params["temperature"]?.let { run.metadata["ls_temperature"] = it } + val stop = params["stop"] + if (stop != null) { + run.metadata["ls_stop"] = if (stop is String) listOf(stop) else stop + } + if (invocationParams.isNotEmpty()) { + run.metadata["ls_invocation_params"] = invocationParams + } } diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAI.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAI.kt new file mode 100644 index 000000000..6f3cc799c --- /dev/null +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAI.kt @@ -0,0 +1,204 @@ +@file:JvmName("OpenAITracing") + +package com.langchain.smith.wrappers.openai + +import com.langchain.smith.tracing.RunType +import com.langchain.smith.tracing.TraceConfig +import com.langchain.smith.tracing.TraceProcessIO +import com.langchain.smith.tracing.traceBiFunction +import com.langchain.smith.tracing.traceable +import com.openai.client.OpenAIClient +import com.openai.core.ClientOptions +import com.openai.core.RequestOptions +import com.openai.models.chat.completions.ChatCompletion +import com.openai.models.chat.completions.ChatCompletionCreateParams +import com.openai.models.responses.Response +import com.openai.models.responses.ResponseCreateParams +import com.openai.services.blocking.ChatService +import com.openai.services.blocking.ResponseService +import com.openai.services.blocking.chat.ChatCompletionService +import java.util.function.Consumer +import java.util.function.Function + +/** + * Wraps an [OpenAIClient] with LangSmith tracing. + * + * The returned client traces `chat().completions().create()` and `responses().create()` calls using + * [traceable], recording inputs and outputs as JSON maps. All other methods — including + * `createStreaming()` — pass through to the delegate unchanged. + * + * // TODO: Trace `createStreaming()` for both chat completions and responses. + * + * The [config] is used as the base configuration for all traced calls — the wrapper overrides + * [TraceConfig.name] and [TraceConfig.runType] per operation. + * + * ## Example (Kotlin) + * + * ```kotlin + * val client = wrapOpenAI( + * OpenAIOkHttpClient.fromEnv(), + * TraceConfig(client = langsmithClient), + * ) + * val completion = client.chat().completions().create(params) + * ``` + * + * ## Example (Java) + * + * ```java + * OpenAIClient client = OpenAITracing.wrapOpenAI( + * OpenAIOkHttpClient.fromEnv(), + * TraceConfig.builder().client(langsmithClient).build()); + * ChatCompletion completion = client.chat().completions().create(params); + * ``` + * + * @param client the OpenAI client to wrap + * @param config base tracing configuration (client, project, tags, etc.) + * @return a wrapped [OpenAIClient] that traces LLM calls to LangSmith + */ +fun wrapOpenAI(client: OpenAIClient, config: TraceConfig): OpenAIClient = + TracedOpenAIClient(client, config) + +private class TracedOpenAIClient( + private val delegate: OpenAIClient, + private val config: TraceConfig, +) : OpenAIClient by delegate { + + private val tracedChat by lazy { TracedChatService(delegate.chat(), config) } + private val tracedResponses by lazy { TracedResponseService(delegate.responses(), config) } + + override fun chat(): ChatService = tracedChat + + override fun responses(): ResponseService = tracedResponses + + override fun withOptions(modifier: Consumer): OpenAIClient = + TracedOpenAIClient(delegate.withOptions(modifier), config) +} + +private class TracedChatService( + private val delegate: ChatService, + private val config: TraceConfig, +) : ChatService by delegate { + + private val tracedCompletions by lazy { + TracedChatCompletionService(delegate.completions(), config) + } + + override fun completions(): ChatCompletionService = tracedCompletions + + override fun withOptions(modifier: Consumer): ChatService = + TracedChatService(delegate.withOptions(modifier), config) +} + +/** + * Builds the traced `create` functions (1-arg and 2-arg) for an OpenAI service. + * + * Both [TracedChatCompletionService] and [TracedResponseService] follow the same pattern — this + * extracts the shared tracing plumbing so each service only provides the type-specific bits. + * + * @param P the params type (e.g. [ChatCompletionCreateParams]) + * @param R the response type (e.g. [ChatCompletion]) + * @param config base tracing configuration + * @param paramsToMap serializes params to a map for recording as run inputs + * @param useResponsesApi whether this is the responses API (affects metadata) + * @param createOne calls the underlying service's `create(params)` method + * @param createTwo calls the underlying service's `create(params, requestOptions)` method + */ +private class TracedOpenAIClientCreate( + config: TraceConfig, + paramsToMap: (P) -> Map, + useResponsesApi: Boolean, + createOne: (P) -> R, + createTwo: (P, RequestOptions) -> R, +) { + val oneArg: Function = + traceable( + Function { + setInvocationParams(paramsToMap(it), useResponsesApi = useResponsesApi) + createOne(it) + }, + config + .toBuilder() + .name("ChatOpenAI") + .runType(RunType.LLM) + .processTracedIO( + TraceProcessIO( + processInputs = Function { params -> paramsToMap(params) }, + processOutputs = + Function { response -> processChatCompletionOutput(toMap(response)) }, + ) + ) + .build(), + ) + + val twoArg: java.util.function.BiFunction = + traceBiFunction( + java.util.function.BiFunction { params, opts -> + setInvocationParams(paramsToMap(params), useResponsesApi = useResponsesApi) + createTwo(params, opts) + }, + config + .toBuilder() + .name("ChatOpenAI") + .runType(RunType.LLM) + .processTracedIO( + TraceProcessIO, R>( + processInputs = + Function { (params, opts) -> + paramsToMap(params) + ("request_options" to toGenericMap(opts)) + }, + processOutputs = + Function { response -> processChatCompletionOutput(toMap(response)) }, + ) + ) + .build(), + ) +} + +private class TracedChatCompletionService( + private val delegate: ChatCompletionService, + private val config: TraceConfig, +) : ChatCompletionService by delegate { + + private val traced = + TracedOpenAIClientCreate( + config = config, + paramsToMap = ::chatParamsToMap, + useResponsesApi = false, + createOne = delegate::create, + createTwo = delegate::create, + ) + + override fun create(params: ChatCompletionCreateParams): ChatCompletion = + traced.oneArg.apply(params) + + override fun create( + params: ChatCompletionCreateParams, + requestOptions: RequestOptions, + ): ChatCompletion = traced.twoArg.apply(params, requestOptions) + + override fun withOptions(modifier: Consumer): ChatCompletionService = + TracedChatCompletionService(delegate.withOptions(modifier), config) +} + +private class TracedResponseService( + private val delegate: ResponseService, + private val config: TraceConfig, +) : ResponseService by delegate { + + private val traced = + TracedOpenAIClientCreate( + config = config, + paramsToMap = ::responseParamsToMap, + useResponsesApi = true, + createOne = delegate::create, + createTwo = delegate::create, + ) + + override fun create(params: ResponseCreateParams): Response = traced.oneArg.apply(params) + + override fun create(params: ResponseCreateParams, requestOptions: RequestOptions): Response = + traced.twoArg.apply(params, requestOptions) + + override fun withOptions(modifier: Consumer): ResponseService = + TracedResponseService(delegate.withOptions(modifier), config) +} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedChatService.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedChatService.kt deleted file mode 100644 index 42c9605b0..000000000 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedChatService.kt +++ /dev/null @@ -1,573 +0,0 @@ -package com.langchain.smith.wrappers.openai - -import com.openai.core.ClientOptions -import com.openai.core.RequestOptions -import com.openai.core.http.StreamResponse -import com.openai.helpers.ChatCompletionAccumulator -import com.openai.models.chat.completions.ChatCompletion -import com.openai.models.chat.completions.ChatCompletionChunk -import com.openai.models.chat.completions.ChatCompletionCreateParams -import com.openai.models.chat.completions.ChatCompletionStreamOptions -import com.openai.models.chat.completions.StructuredChatCompletion -import com.openai.models.chat.completions.StructuredChatCompletionCreateParams -import com.openai.services.blocking.ChatService -import com.openai.services.blocking.chat.ChatCompletionService -import io.opentelemetry.api.common.AttributeKey -import io.opentelemetry.api.trace.Span -import java.util.function.Consumer -import java.util.regex.Pattern -import java.util.stream.Stream -import kotlin.jvm.optionals.getOrNull - -/** Wrapped ChatService that adds OpenTelemetry tracing to chat completion operations. */ -internal class WrappedChatService(private val delegate: ChatService) : ChatService { - - override fun withRawResponse() = delegate.withRawResponse() - - override fun withOptions(options: Consumer) = - WrappedChatService(delegate.withOptions(options)) - - override fun completions(): ChatCompletionService = - WrappedChatCompletionService(delegate.completions()) - - private class WrappedChatCompletionService(private val delegate: ChatCompletionService) : - ChatCompletionService { - - override fun withRawResponse() = delegate.withRawResponse() - - override fun withOptions(options: Consumer) = - WrappedChatCompletionService(delegate.withOptions(options)) - - override fun messages() = delegate.messages() - - override fun create(params: ChatCompletionCreateParams): ChatCompletion = - createChat(params, null) - - override fun create( - params: ChatCompletionCreateParams, - requestOptions: RequestOptions, - ): ChatCompletion = createChat(params, requestOptions) - - private fun createChat( - params: ChatCompletionCreateParams, - requestOptions: RequestOptions?, - ): ChatCompletion { - val model = params.model()?.toString() - val span = TracingUtils.createSpanBuilder(model, "chat").startSpan() - try { - span.makeCurrent().use { - setExperimentContextAttributes(span) - TracingUtils.setRequestAttributes(span, model) - TracingUtils.setRequestParameters( - span, - params.temperature().orElse(null), - params.topP().orElse(null), - params.maxCompletionTokens().orElse(null), - ) - val promptTextNonStream = - extractPromptFromParams(params)?.takeIf { it.isNotEmpty() } - promptTextNonStream?.let { - span.setAttribute(AttributeKey.stringKey("gen_ai.prompt"), it) - } - TracingUtils.setInputMessages(span, formatInputMessages(params)) - val result = - if (requestOptions == null) delegate.create(params) - else delegate.create(params, requestOptions) - applyChatCompletionToSpan(span, result) - return result - } - } catch (e: Exception) { - TracingUtils.recordException(span, e) - throw e - } finally { - span.end() - } - } - - /** - * Applies completion output, gen_ai.completion JSON, and usage to the span (shared by - * non-streaming and streaming). - */ - private fun applyChatCompletionToSpan(span: Span, completion: ChatCompletion) { - formatOutputMessages(completion).let { TracingUtils.setOutputMessages(span, it) } - span.setAttribute( - AttributeKey.stringKey("gen_ai.completion"), - "{\"messages\":${formatOutputMessages(completion)}}", - ) - val responseModel = completion.model() - val finishReason = - completion.choices().firstOrNull()?.finishReason()?.toString() ?: "stop" - TracingUtils.setResponseMetadata(span, responseModel, finishReason) - completion.usage().ifPresent { usage -> - TracingUtils.setResponseAttributes( - span, - usage.promptTokens().toLong(), - usage.completionTokens().toLong(), - usage.totalTokens().toLong(), - ) - } - } - - private fun setExperimentContextAttributes(span: Span) { - ExperimentContext.current() - .getReferenceExampleId() - .filter { it.isNotEmpty() } - .ifPresent { - span.setAttribute(AttributeKey.stringKey("langsmith.reference_example_id"), it) - } - ExperimentContext.current() - .getSessionId() - .filter { it.isNotEmpty() } - .ifPresent { - span.setAttribute(AttributeKey.stringKey("langsmith.trace.session_id"), it) - } - for ((key, value) in ExperimentContext.current().getMetadata()) { - span.setAttribute(AttributeKey.stringKey("langsmith.metadata.$key"), value) - } - } - - private fun formatInputMessages(params: ChatCompletionCreateParams): String { - if (params.messages().isEmpty()) return "[]" - val messages = mutableListOf>() - for (messageParam in params.messages()) { - var role: String? = null - var content: String? = null - try { - val isUser = - messageParam.javaClass.getMethod("isUser").invoke(messageParam) as Boolean - val isSystem = - messageParam.javaClass.getMethod("isSystem").invoke(messageParam) as Boolean - val isAssistant = - messageParam.javaClass.getMethod("isAssistant").invoke(messageParam) - as Boolean - val isTool = - messageParam.javaClass.getMethod("isTool").invoke(messageParam) as Boolean - val actualMessage = - when { - isUser -> { - role = "user" - messageParam.javaClass.getMethod("asUser").invoke(messageParam) - } - isSystem -> { - role = "system" - messageParam.javaClass.getMethod("asSystem").invoke(messageParam) - } - isAssistant -> { - role = "assistant" - messageParam.javaClass.getMethod("asAssistant").invoke(messageParam) - } - isTool -> { - role = "tool" - messageParam.javaClass.getMethod("asTool").invoke(messageParam) - } - else -> null - } - if (actualMessage != null) { - try { - val contentResult = - actualMessage.javaClass.getMethod("content").invoke(actualMessage) - if (contentResult != null) { - try { - val textResult = - contentResult.javaClass - .getMethod("text") - .invoke(contentResult) - content = - when (textResult) { - is java.util.Optional<*> -> - (textResult as java.util.Optional<*>) - .orElse(null) - ?.toString() - is String -> textResult - else -> null - } - } catch (_: NoSuchMethodException) { - content = - when (contentResult) { - is String -> contentResult - is java.util.Optional<*> -> - (contentResult as java.util.Optional<*>) - .orElse(null) - ?.toString() - else -> null - } - } - } - } catch (_: NoSuchMethodException) {} - } - if (role == null) { - val roleResult = - messageParam.javaClass.getMethod("role").invoke(messageParam) - role = roleResult?.toString()?.lowercase() - } - } catch (_: Exception) {} - if (role == null) { - val className = messageParam.javaClass.simpleName - val fullName = messageParam.javaClass.name - role = - when { - "User" in className || "User" in fullName -> "user" - "System" in className || "System" in fullName -> "system" - "Assistant" in className || "Assistant" in fullName -> "assistant" - "Tool" in className || "Tool" in fullName -> "tool" - else -> null - } - } - if (content == null) { - content = extractContentFromToString(messageParam.toString(), role) - } - val outRole = role ?: "user" - val partType = if (role == "tool") "tool_call_response" else "text" - val partKey = if (role == "tool") "response" else "content" - val parts = - if (content != null) { - listOf(mapOf("type" to partType, partKey to content)) - } else { - emptyList>() - } - messages.add(mapOf("role" to outRole, "parts" to parts)) - } - return TracingUtils.writeJson(messages) - } - - private fun extractContentFromToString(messageStr: String, role: String?): String? { - if (role == "tool") { - val toolContentPattern = Pattern.compile("text=\\{([^}]+)\\}") - val toolMatcher = toolContentPattern.matcher(messageStr) - if (toolMatcher.find()) return "{" + toolMatcher.group(1) + "}" - val simplePattern = Pattern.compile("text=[\"']([^\"']+)[\"']") - val simpleMatcher = simplePattern.matcher(messageStr) - if (simpleMatcher.find()) return simpleMatcher.group(1) - } - var contentIdx = messageStr.indexOf("content=") - if (contentIdx >= 0) { - val textIdx = messageStr.indexOf("text=", contentIdx) - if (textIdx > contentIdx) { - val start1 = messageStr.indexOf("\"", textIdx) - if (start1 >= 0) { - var end = start1 + 1 - while (end < messageStr.length && messageStr[end] != '"') { - if (messageStr[end] == '\\') end += 2 else end++ - } - if (end < messageStr.length) return messageStr.substring(start1 + 1, end) - } - } - val start2 = messageStr.indexOf("\"", contentIdx) - if (start2 >= 0) { - val end = messageStr.indexOf("\"", start2 + 1) - if (end > start2) return messageStr.substring(start2 + 1, end) - } - } - val pattern = Pattern.compile("content[=:]\\s*[\"']([^\"']+)[\"']") - val matcher = pattern.matcher(messageStr) - if (matcher.find()) return matcher.group(1) - val fallback = Pattern.compile("[\"']([^\"']+)[\"']").matcher(messageStr) - if (fallback.find()) { - val potential = fallback.group(1) - if ( - !potential.contains("com.openai") && - potential !in listOf("user", "system", "assistant", "tool") && - potential.isNotEmpty() - ) - return potential - } - return null - } - - /** OTel GenAI schema: each message has role, parts array, and finish_reason (output). */ - private fun formatOutputMessages(completion: ChatCompletion): String { - if (completion.choices().isEmpty()) return "[]" - val choices = - completion.choices().map { choice -> - val message = choice.message() - val finishReason = choice.finishReason()?.toString()?.lowercase() ?: "stop" - val parts = mutableListOf>() - message.content().ifPresent { content -> - parts.add(mapOf("type" to "text", "content" to content)) - } - message.toolCalls().ifPresent { toolCalls -> - for (toolCall in toolCalls) { - if (!toolCall.isFunction()) continue - val fn = toolCall.asFunction() - parts.add( - mapOf( - "type" to "tool_call", - "id" to fn.id(), - "name" to fn.function().name(), - "arguments" to fn.function().arguments(), - ) - ) - } - } - mapOf("role" to "assistant", "parts" to parts, "finish_reason" to finishReason) - } - return TracingUtils.writeJson(choices) - } - - private fun extractPromptFromParams(params: ChatCompletionCreateParams): String? { - for (messageParam in params.messages()) { - if (messageParam.isUser()) { - val userMessage = messageParam.asUser() - val text = userMessage.content().text().getOrNull() - if (!text.isNullOrEmpty()) return text - } - } - return null - } - - override fun create( - params: StructuredChatCompletionCreateParams - ): StructuredChatCompletion = createStructured(params, null) - - override fun create( - params: StructuredChatCompletionCreateParams, - requestOptions: RequestOptions, - ): StructuredChatCompletion = createStructured(params, requestOptions) - - private fun createStructured( - params: StructuredChatCompletionCreateParams, - requestOptions: RequestOptions?, - ): StructuredChatCompletion { - val model = params.rawParams?.model()?.toString() - val span = TracingUtils.createSpanBuilder(model, "chat").startSpan() - try { - span.makeCurrent().use { - setExperimentContextAttributes(span) - TracingUtils.setRequestAttributes(span, model) - params.rawParams?.let { raw -> - TracingUtils.setRequestParameters( - span, - raw.temperature().orElse(null), - raw.topP().orElse(null), - raw.maxCompletionTokens().orElse(null), - ) - val promptStructured = - extractPromptFromParams(raw)?.takeIf { it.isNotEmpty() } - promptStructured?.let { - span.setAttribute(AttributeKey.stringKey("gen_ai.prompt"), it) - } - TracingUtils.setInputMessages(span, formatInputMessages(raw)) - } - val result = - if (requestOptions == null) delegate.create(params) - else delegate.create(params, requestOptions!!) - TracingUtils.setResponseMetadata(span, model, null) - result.usage().ifPresent { u -> - TracingUtils.setResponseAttributes( - span, - u.promptTokens().toLong(), - u.completionTokens().toLong(), - u.totalTokens().toLong(), - ) - } - return result - } - } catch (e: Exception) { - TracingUtils.recordException(span, e) - throw e - } finally { - span.end() - } - } - - override fun createStreaming( - params: ChatCompletionCreateParams - ): StreamResponse = createStreamingChat(params, null) - - override fun createStreaming( - params: ChatCompletionCreateParams, - requestOptions: RequestOptions, - ): StreamResponse = createStreamingChat(params, requestOptions) - - /** - * Ensures the request asks for usage in the stream so we get token counts in the final - * chunk. Without stream_options.include_usage=true the API does not send usage and traces - * lack token metadata. - */ - private fun ensureStreamIncludeUsage( - params: ChatCompletionCreateParams - ): ChatCompletionCreateParams { - val existing = params.streamOptions().orElse(null) - if (existing != null && existing.includeUsage().orElse(false)) return params - val streamOptsBuilder = ChatCompletionStreamOptions.builder().includeUsage(true) - existing?.includeObfuscation()?.ifPresent { streamOptsBuilder.includeObfuscation(it) } - val newOpts = streamOptsBuilder.build() - return params.toBuilder().streamOptions(newOpts).build() - } - - private fun createStreamingChat( - params: ChatCompletionCreateParams, - requestOptions: RequestOptions?, - ): StreamResponse { - val model = params.model()?.toString() - val span = TracingUtils.createSpanBuilder(model, "chat").startSpan() - try { - span.makeCurrent().use { - setExperimentContextAttributes(span) - TracingUtils.setRequestAttributes(span, model) - span.setAttribute(AttributeKey.booleanKey("gen_ai.streaming"), true) - TracingUtils.setRequestParameters( - span, - params.temperature().orElse(null), - params.topP().orElse(null), - params.maxCompletionTokens().orElse(null), - ) - val promptText = extractPromptFromParams(params)?.takeIf { it.isNotEmpty() } - promptText?.let { - span.setAttribute(AttributeKey.stringKey("gen_ai.prompt"), it) - } - TracingUtils.setInputMessages(span, formatInputMessages(params)) - val accumulator = ChatCompletionAccumulator.create() - val paramsWithUsage = ensureStreamIncludeUsage(params) - val startNanos = System.nanoTime() - val delegateStream = - if (requestOptions == null) delegate.createStreaming(paramsWithUsage) - else delegate.createStreaming(paramsWithUsage, requestOptions!!) - return TracedChatStreamResponse( - span, - accumulator, - delegateStream, - startNanos, - ) { s, c -> - c?.let { applyChatCompletionToSpan(s, it) } - } - } - } catch (e: Exception) { - TracingUtils.recordException(span, e) - span.end() - throw e - } - } - - override fun retrieve(completionId: String) = delegate.retrieve(completionId) - - override fun retrieve( - completionId: String, - params: com.openai.models.chat.completions.ChatCompletionRetrieveParams, - ) = delegate.retrieve(completionId, params) - - override fun retrieve(completionId: String, requestOptions: RequestOptions) = - delegate.retrieve(completionId, requestOptions) - - override fun retrieve( - completionId: String, - params: com.openai.models.chat.completions.ChatCompletionRetrieveParams, - requestOptions: RequestOptions, - ) = delegate.retrieve(completionId, params, requestOptions) - - override fun retrieve( - params: com.openai.models.chat.completions.ChatCompletionRetrieveParams - ) = delegate.retrieve(params) - - override fun retrieve( - params: com.openai.models.chat.completions.ChatCompletionRetrieveParams, - requestOptions: RequestOptions, - ) = delegate.retrieve(params, requestOptions) - - override fun update( - completionId: String, - params: com.openai.models.chat.completions.ChatCompletionUpdateParams, - ) = delegate.update(completionId, params) - - override fun update( - completionId: String, - params: com.openai.models.chat.completions.ChatCompletionUpdateParams, - requestOptions: RequestOptions, - ) = delegate.update(completionId, params, requestOptions) - - override fun update(params: com.openai.models.chat.completions.ChatCompletionUpdateParams) = - delegate.update(params) - - override fun update( - params: com.openai.models.chat.completions.ChatCompletionUpdateParams, - requestOptions: RequestOptions, - ) = delegate.update(params, requestOptions) - - override fun list() = delegate.list() - - override fun list(requestOptions: RequestOptions) = delegate.list(requestOptions) - - override fun list(params: com.openai.models.chat.completions.ChatCompletionListParams) = - delegate.list(params) - - override fun list( - params: com.openai.models.chat.completions.ChatCompletionListParams, - requestOptions: RequestOptions, - ) = delegate.list(params, requestOptions) - - override fun delete(completionId: String) = delegate.delete(completionId) - - override fun delete(completionId: String, requestOptions: RequestOptions) = - delegate.delete(completionId, requestOptions) - - override fun delete( - completionId: String, - params: com.openai.models.chat.completions.ChatCompletionDeleteParams, - ) = delegate.delete(completionId, params) - - override fun delete( - completionId: String, - params: com.openai.models.chat.completions.ChatCompletionDeleteParams, - requestOptions: RequestOptions, - ) = delegate.delete(completionId, params, requestOptions) - - override fun delete(params: com.openai.models.chat.completions.ChatCompletionDeleteParams) = - delegate.delete(params) - - override fun delete( - params: com.openai.models.chat.completions.ChatCompletionDeleteParams, - requestOptions: RequestOptions, - ) = delegate.delete(params, requestOptions) - } -} - -private class TracedChatStreamResponse( - private val span: Span, - private val accumulator: ChatCompletionAccumulator, - private val delegate: StreamResponse, - private val startNanos: Long, - private val onComplete: (Span, ChatCompletion?) -> Unit, -) : StreamResponse { - - @Volatile private var closed = false - @Volatile private var timeToFirstTokenSet = false - - override fun stream(): Stream = - delegate.stream().map { chunk -> - if (!timeToFirstTokenSet) { - val hasContent = - chunk.choices().isNotEmpty() && - chunk.choices()[0].delta().content().getOrNull()?.isNotEmpty() == true - if (hasContent) { - val ttftMs = (System.nanoTime() - startNanos) / 1_000_000 - span.setAttribute( - AttributeKey.longKey("gen_ai.usage.time_to_first_token_ms"), - ttftMs, - ) - timeToFirstTokenSet = true - } - } - accumulator.accumulate(chunk) - chunk - } - - override fun close() { - if (closed) return - closed = true - try { - try { - val completion = accumulator.chatCompletion() - onComplete(span, completion) - } catch (_: IllegalStateException) { - // Stream closed before a complete response - } - } finally { - span.end() - try { - delegate.close() - } catch (_: Exception) { - // Already ended span; ensure delegate is closed best-effort - } - } - } -} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedOpenAIClient.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedOpenAIClient.kt deleted file mode 100644 index 0ef758269..000000000 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedOpenAIClient.kt +++ /dev/null @@ -1,104 +0,0 @@ -package com.langchain.smith.wrappers.openai - -import com.openai.client.OpenAIClient -import com.openai.client.okhttp.OpenAIOkHttpClient -import com.openai.core.ClientOptions -import com.openai.services.blocking.ChatService -import com.openai.services.blocking.ResponseService -import java.util.function.Consumer - -/** - * Wrapped OpenAI client that maintains the same developer experience as the original client while - * adding LangSmith tracing capabilities. - * - * This wrapper delegates all calls to the underlying OpenAI client. - */ -class WrappedOpenAIClient(private val delegate: OpenAIClient) : OpenAIClient { - - fun getDelegate(): OpenAIClient = delegate - - override fun async() = delegate.async() - - override fun withRawResponse(): OpenAIClient.WithRawResponse = delegate.withRawResponse() - - override fun withOptions(options: Consumer) = - delegate.withOptions(options) - - override fun completions() = delegate.completions() - - override fun chat(): ChatService = WrappedChatService(delegate.chat()) - - override fun embeddings() = delegate.embeddings() - - override fun files() = delegate.files() - - override fun images() = delegate.images() - - override fun audio() = delegate.audio() - - override fun moderations() = delegate.moderations() - - override fun models() = delegate.models() - - override fun fineTuning() = delegate.fineTuning() - - override fun graders() = delegate.graders() - - override fun vectorStores() = delegate.vectorStores() - - override fun webhooks() = delegate.webhooks() - - override fun beta() = delegate.beta() - - override fun batches() = delegate.batches() - - override fun uploads() = delegate.uploads() - - override fun responses(): ResponseService = WrappedResponseService(delegate.responses()) - - override fun realtime() = delegate.realtime() - - override fun conversations() = delegate.conversations() - - override fun evals() = delegate.evals() - - override fun containers() = delegate.containers() - - override fun videos() = delegate.videos() - - override fun close() = delegate.close() - - class Builder { - private val delegateBuilder = OpenAIOkHttpClient.builder() - - fun fromEnv() = apply { delegateBuilder.fromEnv() } - - fun apiKey(apiKey: String) = apply { delegateBuilder.apiKey(apiKey) } - - fun organization(organization: String) = apply { - delegateBuilder.organization(organization) - } - - fun project(project: String) = apply { delegateBuilder.project(project) } - - fun webhookSecret(webhookSecret: String) = apply { - delegateBuilder.webhookSecret(webhookSecret) - } - - fun baseUrl(baseUrl: String) = apply { delegateBuilder.baseUrl(baseUrl) } - - fun build(): WrappedOpenAIClient = WrappedOpenAIClient(delegateBuilder.build()) - } - - companion object { - @JvmStatic fun builder(): Builder = Builder() - - @JvmStatic - fun wrap(client: OpenAIClient): WrappedOpenAIClient { - require(client != null) { "client cannot be null" } - return WrappedOpenAIClient(client) - } - - @JvmStatic fun fromEnv(): WrappedOpenAIClient = builder().fromEnv().build() - } -} diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedResponseService.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedResponseService.kt deleted file mode 100644 index a9ca43fcf..000000000 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrappedResponseService.kt +++ /dev/null @@ -1,414 +0,0 @@ -package com.langchain.smith.wrappers.openai - -import com.openai.core.ClientOptions -import com.openai.core.RequestOptions -import com.openai.core.http.StreamResponse -import com.openai.helpers.ResponseAccumulator -import com.openai.models.responses.Response -import com.openai.models.responses.ResponseCreateParams -import com.openai.models.responses.ResponseStreamEvent -import com.openai.models.responses.StructuredResponse -import com.openai.models.responses.StructuredResponseCreateParams -import com.openai.services.blocking.ResponseService -import io.opentelemetry.api.common.AttributeKey -import io.opentelemetry.api.trace.Span -import java.util.function.Consumer -import java.util.stream.Stream -import kotlin.jvm.optionals.getOrNull - -/** Wrapped ResponseService that adds OpenTelemetry tracing to response operations. */ -internal class WrappedResponseService(private val delegate: ResponseService) : ResponseService { - - override fun withRawResponse() = delegate.withRawResponse() - - override fun withOptions(options: Consumer) = - WrappedResponseService(delegate.withOptions(options)) - - override fun inputItems() = delegate.inputItems() - - override fun inputTokens() = delegate.inputTokens() - - override fun create(): Response = createResponse(null, null) - - override fun create(requestOptions: RequestOptions): Response = - createResponse(null, requestOptions) - - override fun create(params: ResponseCreateParams): Response = createResponse(params, null) - - override fun create(params: ResponseCreateParams, requestOptions: RequestOptions): Response = - createResponse(params, requestOptions) - - private fun createResponse( - params: ResponseCreateParams?, - requestOptions: RequestOptions?, - ): Response { - val model = - if (params != null && params.model().isPresent) params.model().toString() else null - val span = TracingUtils.createSpanBuilder(model, "response").startSpan() - try { - span.makeCurrent().use { - setExperimentContextAttributes(span) - TracingUtils.setRequestAttributes(span, model) - if (params != null) { - TracingUtils.setRequestParameters( - span, - params.temperature().orElse(null), - params.topP().orElse(null), - null, - ) - } - val result = - when { - params == null && requestOptions == null -> delegate.create() - params == null -> delegate.create(requestOptions!!) - requestOptions == null -> delegate.create(params) - else -> delegate.create(params, requestOptions) - } - TracingUtils.setResponseMetadata(span, model, null) - result.usage().ifPresent { usage -> - TracingUtils.setResponseAttributes( - span, - usage.inputTokens().toLong(), - usage.outputTokens().toLong(), - usage.totalTokens().toLong(), - ) - } - result.status()?.let { - span.setAttribute( - AttributeKey.stringKey("gen_ai.response.status"), - it.toString(), - ) - } - return result - } - } catch (e: Exception) { - TracingUtils.recordException(span, e) - throw e - } finally { - span.end() - } - } - - override fun create( - params: StructuredResponseCreateParams - ): StructuredResponse = createStructured(params, null) - - override fun create( - params: StructuredResponseCreateParams, - requestOptions: RequestOptions, - ): StructuredResponse = createStructured(params, requestOptions) - - private fun createStructured( - params: StructuredResponseCreateParams, - requestOptions: RequestOptions?, - ): StructuredResponse { - val model = - if (params.rawParams != null && params.rawParams!!.model() != null) - params.rawParams!!.model().toString() - else null - val span = TracingUtils.createSpanBuilder(model, "response").startSpan() - try { - span.makeCurrent().use { - setExperimentContextAttributes(span) - TracingUtils.setRequestAttributes(span, model) - if (params.rawParams != null) { - val raw = params.rawParams!! - TracingUtils.setRequestParameters( - span, - raw.temperature().orElse(null), - raw.topP().orElse(null), - null, - ) - } - val result = - if (requestOptions == null) delegate.create(params) - else delegate.create(params, requestOptions) - TracingUtils.setResponseMetadata(span, model, null) - result.usage().ifPresent { usage -> - TracingUtils.setResponseAttributes( - span, - usage.inputTokens().toLong(), - usage.outputTokens().toLong(), - usage.totalTokens().toLong(), - ) - } - return result - } - } catch (e: Exception) { - TracingUtils.recordException(span, e) - throw e - } finally { - span.end() - } - } - - override fun createStreaming(): StreamResponse = - createStreamingResponse(null, null) - - override fun createStreaming( - requestOptions: RequestOptions - ): StreamResponse = createStreamingResponse(null, requestOptions) - - override fun createStreaming( - params: ResponseCreateParams - ): StreamResponse = createStreamingResponse(params, null) - - override fun createStreaming( - params: ResponseCreateParams, - requestOptions: RequestOptions, - ): StreamResponse = createStreamingResponse(params, requestOptions) - - private fun createStreamingResponse( - params: ResponseCreateParams?, - requestOptions: RequestOptions?, - ): StreamResponse { - val model = - if (params != null && params.model() != null) params.model().toString() else null - val span = TracingUtils.createSpanBuilder(model, "response").startSpan() - try { - span.makeCurrent().use { - setExperimentContextAttributes(span) - TracingUtils.setRequestAttributes(span, model) - span.setAttribute(AttributeKey.booleanKey("gen_ai.streaming"), true) - if (params != null) { - TracingUtils.setRequestParameters( - span, - params.temperature().orElse(null), - params.topP().orElse(null), - null, - ) - } - val accumulator = ResponseAccumulator.create() - val delegateStream = - when { - params == null && requestOptions == null -> delegate.createStreaming() - params == null -> delegate.createStreaming(requestOptions!!) - requestOptions == null -> delegate.createStreaming(params) - else -> delegate.createStreaming(params, requestOptions) - } - return TracedResponseStreamResponse(span, accumulator, delegateStream) - } - } catch (e: Exception) { - TracingUtils.recordException(span, e) - span.end() - throw e - } - } - - override fun createStreaming( - params: StructuredResponseCreateParams<*> - ): StreamResponse = createStreamingStructured(params, null) - - override fun createStreaming( - params: StructuredResponseCreateParams<*>, - requestOptions: RequestOptions, - ): StreamResponse = createStreamingStructured(params, requestOptions) - - private fun createStreamingStructured( - params: StructuredResponseCreateParams<*>?, - requestOptions: RequestOptions?, - ): StreamResponse { - val model = - if (params != null && params.rawParams != null && params.rawParams!!.model() != null) - params.rawParams!!.model().toString() - else null - val span = TracingUtils.createSpanBuilder(model, "response").startSpan() - try { - span.makeCurrent().use { - setExperimentContextAttributes(span) - TracingUtils.setRequestAttributes(span, model) - span.setAttribute(AttributeKey.booleanKey("gen_ai.streaming"), true) - if (params != null && params.rawParams != null) { - val raw = params.rawParams!! - TracingUtils.setRequestParameters( - span, - raw.temperature().orElse(null), - raw.topP().orElse(null), - null, - ) - } - val accumulator = ResponseAccumulator.create() - val delegateStream = - when { - requestOptions == null -> delegate.createStreaming(params!!) - else -> delegate.createStreaming(params!!, requestOptions) - } - return TracedResponseStreamResponse(span, accumulator, delegateStream) - } - } catch (e: Exception) { - TracingUtils.recordException(span, e) - span.end() - throw e - } - } - - private fun setExperimentContextAttributes(span: Span) { - ExperimentContext.current() - .getReferenceExampleId() - .filter { it.isNotEmpty() } - .ifPresent { - span.setAttribute(AttributeKey.stringKey("langsmith.reference_example_id"), it) - } - ExperimentContext.current() - .getSessionId() - .filter { it.isNotEmpty() } - .ifPresent { - span.setAttribute(AttributeKey.stringKey("langsmith.trace.session_id"), it) - } - for ((key, value) in ExperimentContext.current().getMetadata()) { - span.setAttribute(AttributeKey.stringKey("langsmith.metadata.$key"), value) - } - } - - override fun retrieve(responseId: String) = delegate.retrieve(responseId) - - override fun retrieve(responseId: String, requestOptions: RequestOptions) = - delegate.retrieve(responseId, requestOptions) - - override fun retrieve( - responseId: String, - params: com.openai.models.responses.ResponseRetrieveParams, - ) = delegate.retrieve(responseId, params) - - override fun retrieve( - responseId: String, - params: com.openai.models.responses.ResponseRetrieveParams, - requestOptions: RequestOptions, - ) = delegate.retrieve(responseId, params, requestOptions) - - override fun retrieve(params: com.openai.models.responses.ResponseRetrieveParams) = - delegate.retrieve(params) - - override fun retrieve( - params: com.openai.models.responses.ResponseRetrieveParams, - requestOptions: RequestOptions, - ) = delegate.retrieve(params, requestOptions) - - override fun retrieveStreaming(responseId: String) = delegate.retrieveStreaming(responseId) - - override fun retrieveStreaming(responseId: String, requestOptions: RequestOptions) = - delegate.retrieveStreaming(responseId, requestOptions) - - override fun retrieveStreaming( - responseId: String, - params: com.openai.models.responses.ResponseRetrieveParams, - ) = delegate.retrieveStreaming(responseId, params) - - override fun retrieveStreaming( - responseId: String, - params: com.openai.models.responses.ResponseRetrieveParams, - requestOptions: RequestOptions, - ) = delegate.retrieveStreaming(responseId, params, requestOptions) - - override fun retrieveStreaming(params: com.openai.models.responses.ResponseRetrieveParams) = - delegate.retrieveStreaming(params) - - override fun retrieveStreaming( - params: com.openai.models.responses.ResponseRetrieveParams, - requestOptions: RequestOptions, - ) = delegate.retrieveStreaming(params, requestOptions) - - override fun delete(responseId: String) = delegate.delete(responseId) - - override fun delete(responseId: String, requestOptions: RequestOptions) = - delegate.delete(responseId, requestOptions) - - override fun delete( - responseId: String, - params: com.openai.models.responses.ResponseDeleteParams, - ) = delegate.delete(responseId, params) - - override fun delete( - responseId: String, - params: com.openai.models.responses.ResponseDeleteParams, - requestOptions: RequestOptions, - ) = delegate.delete(responseId, params, requestOptions) - - override fun delete(params: com.openai.models.responses.ResponseDeleteParams) = - delegate.delete(params) - - override fun delete( - params: com.openai.models.responses.ResponseDeleteParams, - requestOptions: RequestOptions, - ) = delegate.delete(params, requestOptions) - - override fun cancel(responseId: String) = delegate.cancel(responseId) - - override fun cancel(responseId: String, requestOptions: RequestOptions) = - delegate.cancel(responseId, requestOptions) - - override fun cancel( - responseId: String, - params: com.openai.models.responses.ResponseCancelParams, - ) = delegate.cancel(responseId, params) - - override fun cancel( - responseId: String, - params: com.openai.models.responses.ResponseCancelParams, - requestOptions: RequestOptions, - ) = delegate.cancel(responseId, params, requestOptions) - - override fun cancel(params: com.openai.models.responses.ResponseCancelParams) = - delegate.cancel(params) - - override fun cancel( - params: com.openai.models.responses.ResponseCancelParams, - requestOptions: RequestOptions, - ) = delegate.cancel(params, requestOptions) -} - -/** - * Wraps a streaming Responses API stream so that completion/usage are applied to the span from the - * response.completed (or terminal) event, and the span is ended when the stream is closed. - */ -private class TracedResponseStreamResponse( - private val span: Span, - private val accumulator: ResponseAccumulator, - private val delegate: StreamResponse, -) : StreamResponse { - - @Volatile private var closed = false - - override fun stream(): Stream = - delegate.stream().map { event -> - try { - accumulator.accumulate(event) - } catch (_: IllegalStateException) { - // Terminal event already accumulated; ignore duplicate or late events - } - event - } - - override fun close() { - if (closed) return - closed = true - try { - try { - val resp = accumulator.response() - resp.usage().ifPresent { u -> - TracingUtils.setResponseAttributes( - span, - u.inputTokens().toLong(), - u.outputTokens().toLong(), - u.totalTokens().toLong(), - ) - } - resp.status().getOrNull()?.let { - span.setAttribute( - AttributeKey.stringKey("gen_ai.response.status"), - it.toString(), - ) - } - } catch (_: IllegalStateException) { - // Stream closed before a terminal event (completed/incomplete/failed) - } - } finally { - span.end() - try { - delegate.close() - } catch (_: Exception) { - // Already ended span; ensure delegate is closed best-effort - } - } - } -} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt index 197095e86..37d9199d2 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableTest.kt @@ -1,21 +1,6 @@ package com.langchain.smith.tracing -import com.fasterxml.jackson.core.type.TypeReference -import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.langchain.smith.client.okhttp.LangsmithOkHttpClient -import com.openai.client.okhttp.OpenAIOkHttpClient -import com.openai.core.JsonValue -import com.openai.models.ChatModel -import com.openai.models.FunctionDefinition -import com.openai.models.FunctionParameters -import com.openai.models.chat.completions.ChatCompletion -import com.openai.models.chat.completions.ChatCompletionCreateParams -import com.openai.models.chat.completions.ChatCompletionFunctionTool -import com.openai.models.chat.completions.ChatCompletionMessage -import com.openai.models.chat.completions.ChatCompletionMessageParam -import com.openai.models.chat.completions.ChatCompletionToolMessageParam -import java.util.function.Function as JFunction -import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.Assumptions.assumeTrue @@ -23,100 +8,6 @@ import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance -private val testJsonMapper = jacksonObjectMapper() - -private fun toJsonMap(value: Any): Map = - testJsonMapper.convertValue(value, object : TypeReference>() {}) - -private fun weatherTool(): ChatCompletionFunctionTool = - ChatCompletionFunctionTool.builder() - .function( - FunctionDefinition.builder() - .name("get_weather") - .description("Get the weather for a location") - .parameters( - FunctionParameters.builder() - .putAdditionalProperty("type", JsonValue.from("object")) - .putAdditionalProperty( - "properties", - JsonValue.from( - mapOf( - "location" to - mapOf( - "type" to "string", - "description" to - "City and state, e.g. San Francisco, CA", - ) - ) - ), - ) - .putAdditionalProperty("required", JsonValue.from(listOf("location"))) - .build() - ) - .build() - ) - .build() - -private fun buildToolLoopParams( - messages: List -): ChatCompletionCreateParams = - ChatCompletionCreateParams.builder() - .model(ChatModel.GPT_4_1_MINI) - .messages(messages) - .addTool(weatherTool()) - .maxCompletionTokens(150) - .build() - -private fun toolLoopInputMap(params: ChatCompletionCreateParams): Map = - mapOf( - "model" to params.model().toString(), - "messages" to params.messages().map { toJsonMap(it) }, - "tools" to params.tools().getOrNull()?.map { toJsonMap(it) }, - ) - -private fun toolLoopOutputMap(completion: ChatCompletion): Map = - mapOf( - "id" to completion.id(), - "model" to completion.model().toString(), - "choices" to - completion.choices().map { choice -> - mapOf( - "finish_reason" to choice.finishReason().toString(), - "message" to toJsonMap(choice.message()), - ) - }, - ) - -private fun userMessage(content: String): ChatCompletionMessageParam = - ChatCompletionMessageParam.ofUser( - com.openai.models.chat.completions.ChatCompletionUserMessageParam.builder() - .content(content) - .build() - ) - -private fun assistantMessage(message: ChatCompletionMessage): ChatCompletionMessageParam = - ChatCompletionMessageParam.ofAssistant(message.toParam()) - -private fun toolMessage(toolCallId: String, result: Map): ChatCompletionMessageParam = - ChatCompletionMessageParam.ofTool( - ChatCompletionToolMessageParam.builder() - .toolCallId(toolCallId) - .contentAsJson(result) - .build() - ) - -private fun toolResult(argumentsJson: String): Map = - mapOf( - "tool" to "get_weather", - "arguments_json" to argumentsJson, - "location" to "San Francisco, CA", - "forecast" to "sunny", - "temperature_f" to 72, - ) - -private fun finalContent(message: ChatCompletionMessage): String = - message.content().getOrNull() ?: "" - /** * Integration tests for [traceable] that post real runs to LangSmith. * @@ -235,165 +126,6 @@ internal class TraceableTest { assertThat(result).isEqualTo("deep result") } - @Test - fun traceableWithOpenAiToolLoop_usesProcessInputsAndOutputs() { - assumeTrue( - !System.getenv("OPENAI_API_KEY").isNullOrBlank(), - "Skipping: OPENAI_API_KEY must be set", - ) - - val openai = OpenAIOkHttpClient.fromEnv() - var capturedLlmRun: RunTree? = null - var capturedAgentRun: RunTree? = null - - val callOpenAi = - traceable( - { params: ChatCompletionCreateParams -> - capturedLlmRun = getCurrentRunTree() - openai.chat().completions().create(params) - }, - TraceConfig( - name = "call-openai-tool-loop", - client = client, - runType = RunType.LLM, - projectName = "traceable-java-tests", - tracingEnabled = true, - processTracedIO = - TraceProcessIO( - processInputs = JFunction(::toolLoopInputMap), - processOutputs = JFunction(::toolLoopOutputMap), - ), - ), - ) - - val executeTool = - traceable( - { argumentsJson: String -> toolResult(argumentsJson) }, - config("get_weather", runType = RunType.TOOL), - ) - - val agent = - traceable( - { question: String -> - capturedAgentRun = getCurrentRunTree() - val messages = mutableListOf() - messages += - userMessage( - "$question Use the get_weather tool and then answer succinctly." - ) - - repeat(3) { - val completion = callOpenAi(buildToolLoopParams(messages)) - val message = completion.choices()[0].message() - val toolCalls = message.toolCalls().getOrNull().orEmpty() - - if (toolCalls.isEmpty()) { - return@traceable finalContent(message) - } - - messages += assistantMessage(message) - toolCalls.forEach { toolCall -> - val fn = toolCall.asFunction() - val result = executeTool(fn.function().arguments()) - messages += toolMessage(fn.id(), result) - } - } - - error("Model did not finish tool loop in time") - }, - TraceConfig( - name = "openai-tool-loop-agent", - client = client, - projectName = "traceable-java-tests", - tracingEnabled = true, - processTracedIO = - TraceProcessIO( - processInputs = - JFunction { question: String -> mapOf("question" to question) }, - processOutputs = - JFunction { answer: String -> mapOf("answer" to answer) }, - ), - ), - ) - - val result = agent("What is the weather in San Francisco?") - assertThat(result).isNotBlank() - assertThat(capturedAgentRun).isNotNull - assertThat(capturedAgentRun!!.inputs) - .isEqualTo(mapOf("question" to "What is the weather in San Francisco?")) - assertThat(capturedAgentRun!!.outputs).isEqualTo(mapOf("answer" to result)) - assertThat(capturedLlmRun).isNotNull - assertThat(capturedLlmRun!!.inputs).containsKeys("model", "messages", "tools") - assertThat(capturedLlmRun!!.outputs).containsKeys("id", "model", "choices") - - println("[Traceable+OpenAI Tool Loop] Result: $result") - awaitPendingRuns() - } - - @Test - fun traceableWithOpenAiResponsesCall() { - assumeTrue( - !System.getenv("OPENAI_API_KEY").isNullOrBlank(), - "Skipping: OPENAI_API_KEY must be set", - ) - - val openai = com.openai.client.okhttp.OpenAIOkHttpClient.fromEnv() - - val callOpenAiResponses = - traceable( - { question: String -> - val response = - openai - .responses() - .create( - com.openai.models.responses.ResponseCreateParams.builder() - .model(com.openai.models.ChatModel.GPT_4_1_MINI) - .input("$question Answer in one word.") - .build() - ) - response.output().firstNotNullOfOrNull { item -> - item.message().getOrNull()?.content()?.firstNotNullOfOrNull { block -> - block.outputText().getOrNull()?.text() - } - } ?: "" - }, - config("call-openai-responses", runType = RunType.LLM), - ) - - val agent = - traceable( - { input: Map -> callOpenAiResponses(input["question"] as String) }, - config("openai-responses-agent"), - ) - - val result = agent(mapOf("question" to "What is the capital of France?")) - - assertThat(result).containsIgnoringCase("Paris") - println("[Traceable+OpenAI Responses] Result: $result") - - awaitPendingRuns() - } - - @Test - fun getCurrentRun_returnsRunTree() { - var capturedRun: RunTree? = null - val traced = - traceable( - { _: Unit -> - capturedRun = getCurrentRunTree() - "done" - }, - config("get-run-test"), - ) - traced(Unit) - assertThat(capturedRun).isNotNull - assertThat(capturedRun!!.id).isNotBlank() - assertThat(capturedRun!!.traceId).isNotBlank() - assertThat(capturedRun!!.name).isEqualTo("get-run-test") - assertThat(capturedRun!!.parentRunId).isNull() - awaitPendingRuns() - } - @Test fun getCurrentRun_nestedRunHasParent() { var parentRun: RunTree? = null @@ -470,9 +202,4 @@ internal class TraceableTest { fun getCurrentRun_outsideTracedFunction() { assertThat(getCurrentRunTree()).isNull() } - - // TODO: Add agent loop with OpenAI tool calling integration test once - // the OpenAI SDK dependency is bumped (requires updating OTel wrappers - // for new abstract members). The tool calling API (`addTool`, `arguments()`, - // `contentAsJson`) requires OpenAI Java SDK 4.10+. } diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/TracingUtilsTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/TracingUtilsTest.kt new file mode 100644 index 000000000..ac5835598 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/TracingUtilsTest.kt @@ -0,0 +1,329 @@ +package com.langchain.smith.wrappers.openai + +import com.langchain.smith.tracing.RunTree +import com.langchain.smith.tracing.RunType +import com.langchain.smith.tracing.withParent +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +/** + * Unit tests for the tracing utility functions in [TracingUtils]. + * + * These tests do NOT require API keys — they validate pure transformation logic and metadata + * population in isolation. + */ +internal class TracingUtilsTest { + + @Test + fun `processChatCompletionOutput restructures usage into usage_metadata`() { + val raw = + mapOf( + "id" to "chatcmpl-123", + "model" to "gpt-4.1-mini", + "usage" to + mapOf("prompt_tokens" to 10, "completion_tokens" to 20, "total_tokens" to 30), + ) + + val result = processChatCompletionOutput(raw) + + assertThat(result).doesNotContainKey("usage") + assertThat(result).containsKey("usage_metadata") + val meta = result["usage_metadata"] as Map<*, *> + assertThat(meta["input_tokens"]).isEqualTo(10) + assertThat(meta["output_tokens"]).isEqualTo(20) + assertThat(meta["total_tokens"]).isEqualTo(30) + assertThat(meta.keys).doesNotContain("input_token_details") + assertThat(meta.keys).doesNotContain("output_token_details") + } + + @Test + fun `processChatCompletionOutput handles responses API token keys`() { + val raw = + mapOf( + "id" to "resp-123", + "usage" to mapOf("input_tokens" to 15, "output_tokens" to 25, "total_tokens" to 40), + ) + + val result = processChatCompletionOutput(raw) + + val meta = result["usage_metadata"] as Map<*, *> + assertThat(meta["input_tokens"]).isEqualTo(15) + assertThat(meta["output_tokens"]).isEqualTo(25) + assertThat(meta["total_tokens"]).isEqualTo(40) + } + + @Test + fun `processChatCompletionOutput extracts token details`() { + val raw = + mapOf( + "id" to "chatcmpl-123", + "usage" to + mapOf( + "prompt_tokens" to 100, + "completion_tokens" to 50, + "total_tokens" to 150, + "prompt_tokens_details" to + mapOf("cached_tokens" to 30, "audio_tokens" to 5), + "completion_tokens_details" to + mapOf("reasoning_tokens" to 10, "audio_tokens" to 3), + ), + ) + + val result = processChatCompletionOutput(raw) + + val meta = result["usage_metadata"] as Map<*, *> + assertThat(meta["input_tokens"]).isEqualTo(100) + assertThat(meta["output_tokens"]).isEqualTo(50) + + val inputDetails = meta["input_token_details"] as Map<*, *> + assertThat(inputDetails["cache_read"]).isEqualTo(30) + assertThat(inputDetails["audio"]).isEqualTo(5) + + val outputDetails = meta["output_token_details"] as Map<*, *> + assertThat(outputDetails["reasoning"]).isEqualTo(10) + assertThat(outputDetails["audio"]).isEqualTo(3) + } + + @Test + fun `processChatCompletionOutput extracts responses API token details`() { + val raw = + mapOf( + "id" to "resp-123", + "usage" to + mapOf( + "input_tokens" to 100, + "output_tokens" to 50, + "total_tokens" to 150, + "input_tokens_details" to mapOf("cached_tokens" to 20), + "output_tokens_details" to mapOf("reasoning_tokens" to 15), + ), + ) + + val result = processChatCompletionOutput(raw) + + val meta = result["usage_metadata"] as Map<*, *> + val inputDetails = meta["input_token_details"] as Map<*, *> + assertThat(inputDetails["cache_read"]).isEqualTo(20) + + val outputDetails = meta["output_token_details"] as Map<*, *> + assertThat(outputDetails["reasoning"]).isEqualTo(15) + } + + @Test + fun `processChatCompletionOutput handles priority service tier`() { + val raw = + mapOf( + "id" to "chatcmpl-123", + "service_tier" to "priority", + "usage" to + mapOf( + "prompt_tokens" to 100, + "completion_tokens" to 50, + "total_tokens" to 150, + "prompt_tokens_details" to mapOf("cached_tokens" to 30), + "completion_tokens_details" to mapOf("reasoning_tokens" to 10), + ), + ) + + val result = processChatCompletionOutput(raw) + + val meta = result["usage_metadata"] as Map<*, *> + val inputDetails = meta["input_token_details"] as Map<*, *> + assertThat(inputDetails["priority_cache_read"]).isEqualTo(30) + // priority = input_tokens - cache_read = 100 - 30 = 70 + assertThat(inputDetails["priority"]).isEqualTo(70L) + + val outputDetails = meta["output_token_details"] as Map<*, *> + assertThat(outputDetails["priority_reasoning"]).isEqualTo(10) + // priority = output_tokens - reasoning = 50 - 10 = 40 + assertThat(outputDetails["priority"]).isEqualTo(40L) + } + + @Test + fun `processChatCompletionOutput handles flex service tier`() { + val raw = + mapOf( + "id" to "chatcmpl-123", + "service_tier" to "flex", + "usage" to + mapOf("prompt_tokens" to 80, "completion_tokens" to 40, "total_tokens" to 120), + ) + + val result = processChatCompletionOutput(raw) + + val meta = result["usage_metadata"] as Map<*, *> + val inputDetails = meta["input_token_details"] as Map<*, *> + // No cache_read, so flex = input_tokens - 0 = 80 + assertThat(inputDetails["flex"]).isEqualTo(80L) + + val outputDetails = meta["output_token_details"] as Map<*, *> + // No reasoning, so flex = output_tokens - 0 = 40 + assertThat(outputDetails["flex"]).isEqualTo(40L) + } + + @Test + fun `processChatCompletionOutput ignores unrecognized service tier`() { + val raw = + mapOf( + "id" to "chatcmpl-123", + "service_tier" to "default", + "usage" to + mapOf("prompt_tokens" to 10, "completion_tokens" to 20, "total_tokens" to 30), + ) + + val result = processChatCompletionOutput(raw) + + val meta = result["usage_metadata"] as Map<*, *> + // No tier-specific details should be added + assertThat(meta.keys).doesNotContain("input_token_details") + assertThat(meta.keys).doesNotContain("output_token_details") + } + + @Test + fun `processChatCompletionOutput passes through when no usage`() { + val raw = + mapOf("id" to "chatcmpl-123", "model" to "gpt-4.1-mini", "choices" to listOf("hello")) + + val result = processChatCompletionOutput(raw) + + assertThat(result).doesNotContainKey("usage_metadata") + assertThat(result["id"]).isEqualTo("chatcmpl-123") + assertThat(result["model"]).isEqualTo("gpt-4.1-mini") + assertThat(result["choices"]).isEqualTo(listOf("hello")) + } + + @Test + fun `processChatCompletionOutput preserves non-usage fields`() { + val raw = + mapOf( + "id" to "chatcmpl-123", + "model" to "gpt-4.1-mini", + "service_tier" to "priority", + "choices" to listOf("result"), + "usage" to + mapOf("prompt_tokens" to 5, "completion_tokens" to 10, "total_tokens" to 15), + ) + + val result = processChatCompletionOutput(raw) + + assertThat(result["id"]).isEqualTo("chatcmpl-123") + assertThat(result["model"]).isEqualTo("gpt-4.1-mini") + assertThat(result["service_tier"]).isEqualTo("priority") + assertThat(result["choices"]).isEqualTo(listOf("result")) + } + + @Test + fun `setInvocationParams sets ls metadata on current run`() { + val run = RunTree(name = "test-run", runType = RunType.LLM) + + withParent(run) { + setInvocationParams( + mapOf( + "model" to "gpt-4.1-mini", + "temperature" to 0.5, + "max_completion_tokens" to 100, + "stop" to listOf("END"), + "frequency_penalty" to 0.1, + "top_p" to 0.9, + "seed" to 42, + ), + useResponsesApi = false, + ) + } + + assertThat(run.metadata["ls_provider"]).isEqualTo("openai") + assertThat(run.metadata["ls_model_type"]).isEqualTo("chat") + assertThat(run.metadata["ls_model_name"]).isEqualTo("gpt-4.1-mini") + assertThat(run.metadata["ls_temperature"]).isEqualTo(0.5) + assertThat(run.metadata["ls_max_tokens"]).isEqualTo(100) + assertThat(run.metadata["ls_stop"]).isEqualTo(listOf("END")) + + val invocationParams = run.metadata["ls_invocation_params"] as Map<*, *> + assertThat(invocationParams["frequency_penalty"]).isEqualTo(0.1) + assertThat(invocationParams["top_p"]).isEqualTo(0.9) + assertThat(invocationParams["seed"]).isEqualTo(42) + } + + @Test + fun `setInvocationParams uses max_tokens fallback`() { + val run = RunTree(name = "test-run", runType = RunType.LLM) + + withParent(run) { + setInvocationParams( + mapOf("model" to "gpt-4", "max_tokens" to 200), + useResponsesApi = false, + ) + } + + assertThat(run.metadata["ls_max_tokens"]).isEqualTo(200) + } + + @Test + fun `setInvocationParams prefers max_completion_tokens over max_tokens`() { + val run = RunTree(name = "test-run", runType = RunType.LLM) + + withParent(run) { + setInvocationParams( + mapOf("model" to "gpt-4", "max_completion_tokens" to 150, "max_tokens" to 200), + useResponsesApi = false, + ) + } + + assertThat(run.metadata["ls_max_tokens"]).isEqualTo(150) + } + + @Test + fun `setInvocationParams wraps string stop as list`() { + val run = RunTree(name = "test-run", runType = RunType.LLM) + + withParent(run) { + setInvocationParams( + mapOf("model" to "gpt-4", "stop" to "DONE"), + useResponsesApi = false, + ) + } + + assertThat(run.metadata["ls_stop"]).isEqualTo(listOf("DONE")) + } + + @Test + fun `setInvocationParams sets use_responses_api when true`() { + val run = RunTree(name = "test-run", runType = RunType.LLM) + + withParent(run) { + setInvocationParams( + mapOf("model" to "gpt-4.1-mini", "reasoning_effort" to "high"), + useResponsesApi = true, + ) + } + + val invocationParams = run.metadata["ls_invocation_params"] as Map<*, *> + assertThat(invocationParams["use_responses_api"]).isEqualTo(true) + assertThat(invocationParams["reasoning_effort"]).isEqualTo("high") + } + + @Test + fun `setInvocationParams omits optional fields when not present`() { + val run = RunTree(name = "test-run", runType = RunType.LLM) + + withParent(run) { + setInvocationParams( + mapOf("model" to "gpt-4.1-mini", "messages" to listOf("hello")), + useResponsesApi = false, + ) + } + + assertThat(run.metadata["ls_provider"]).isEqualTo("openai") + assertThat(run.metadata["ls_model_name"]).isEqualTo("gpt-4.1-mini") + assertThat(run.metadata).doesNotContainKey("ls_temperature") + assertThat(run.metadata).doesNotContainKey("ls_max_tokens") + assertThat(run.metadata).doesNotContainKey("ls_stop") + assertThat(run.metadata).doesNotContainKey("ls_invocation_params") + } + + @Test + fun `setInvocationParams is no-op when no current run`() { + // Should not throw — just returns silently + setInvocationParams(mapOf("model" to "gpt-4"), useResponsesApi = false) + } +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAISerializationTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAISerializationTest.kt new file mode 100644 index 000000000..f67db2056 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAISerializationTest.kt @@ -0,0 +1,178 @@ +package com.langchain.smith.wrappers.openai + +import com.fasterxml.jackson.core.type.TypeReference +import com.openai.core.jsonMapper +import com.openai.models.ChatModel +import com.openai.models.chat.completions.ChatCompletionCreateParams +import com.openai.models.responses.ResponseCreateParams +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +/** + * Unit tests verifying that the OpenAI wrapper's input serialization produces the correct + * snake_case keys matching the OpenAI REST API wire format. + * + * These tests do NOT require API keys and validate the serialization logic in isolation. + */ +internal class WrapOpenAISerializationTest { + + private val mapper = jsonMapper() + private val mapType = object : TypeReference>() {} + + private fun toMap(value: Any): Map = mapper.convertValue(value, mapType) + + @Test + fun `chatParamsToMap produces snake_case keys`() { + val params = + ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .addUserMessage("Hello") + .maxCompletionTokens(100) + .temperature(0.5) + .topP(0.9) + .frequencyPenalty(0.1) + .presencePenalty(0.2) + .seed(42) + .build() + + val map = toMap(params._body()) + + // Verify snake_case keys are used (not camelCase) + assertThat(map).containsKey("model") + assertThat(map).containsKey("messages") + assertThat(map).containsKey("max_completion_tokens") + assertThat(map).containsKey("temperature") + assertThat(map).containsKey("top_p") + assertThat(map).containsKey("frequency_penalty") + assertThat(map).containsKey("presence_penalty") + assertThat(map).containsKey("seed") + + // Verify camelCase keys are NOT present + assertThat(map).doesNotContainKey("maxCompletionTokens") + assertThat(map).doesNotContainKey("topP") + assertThat(map).doesNotContainKey("frequencyPenalty") + assertThat(map).doesNotContainKey("presencePenalty") + + // Verify values + assertThat(map["max_completion_tokens"]).isEqualTo(100L) + assertThat(map["temperature"]).isEqualTo(0.5) + assertThat(map["top_p"]).isEqualTo(0.9) + assertThat(map["frequency_penalty"]).isEqualTo(0.1) + assertThat(map["presence_penalty"]).isEqualTo(0.2) + assertThat(map["seed"]).isEqualTo(42L) + + // Verify unset optional fields are not present (not null, just absent) + assertThat(map).doesNotContainKey("logprobs") + assertThat(map).doesNotContainKey("stop") + assertThat(map).doesNotContainKey("tools") + assertThat(map).doesNotContainKey("tool_choice") + assertThat(map).doesNotContainKey("stream_options") + + // Verify messages structure + val messages = map["messages"] as List<*> + assertThat(messages).hasSize(1) + val message = messages[0] as Map<*, *> + assertThat(message["role"]).isEqualTo("user") + } + + @Test + fun `responseParamsToMap produces snake_case keys`() { + val params = + ResponseCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .input("What is the capital of France?") + .temperature(0.7) + .topP(0.95) + .build() + + val map = toMap(params._body()) + + // Verify snake_case keys + assertThat(map).containsKey("model") + assertThat(map).containsKey("input") + assertThat(map).containsKey("temperature") + assertThat(map).containsKey("top_p") + + // Verify camelCase keys are NOT present + assertThat(map).doesNotContainKey("topP") + + // Verify values + assertThat(map["temperature"]).isEqualTo(0.7) + assertThat(map["top_p"]).isEqualTo(0.95) + + // Verify unset optional fields are not present + assertThat(map).doesNotContainKey("max_output_tokens") + assertThat(map).doesNotContainKey("tools") + assertThat(map).doesNotContainKey("instructions") + } + + @Test + fun `chatParamsToMap only includes set fields`() { + val params = + ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .addUserMessage("test") + .build() + + val map = toMap(params._body()) + + // Only messages and model should be present (required fields) + assertThat(map).containsKey("messages") + assertThat(map).containsKey("model") + + // Optional fields that were not set should NOT be present + assertThat(map).doesNotContainKey("temperature") + assertThat(map).doesNotContainKey("max_completion_tokens") + assertThat(map).doesNotContainKey("max_tokens") + assertThat(map).doesNotContainKey("top_p") + assertThat(map).doesNotContainKey("frequency_penalty") + assertThat(map).doesNotContainKey("presence_penalty") + assertThat(map).doesNotContainKey("seed") + assertThat(map).doesNotContainKey("stop") + assertThat(map).doesNotContainKey("tools") + assertThat(map).doesNotContainKey("n") + } + + @Test + fun `chatParamsToMap with tools produces correct structure`() { + val params = + ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .addUserMessage("What is the weather?") + .addTool( + com.openai.models.chat.completions.ChatCompletionFunctionTool.builder() + .function( + com.openai.models.FunctionDefinition.builder() + .name("get_weather") + .description("Get weather for a location") + .parameters( + com.openai.models.FunctionParameters.builder() + .putAdditionalProperty( + "type", + com.openai.core.JsonValue.from("object"), + ) + .putAdditionalProperty( + "properties", + com.openai.core.JsonValue.from( + mapOf("location" to mapOf("type" to "string")) + ), + ) + .build() + ) + .build() + ) + .build() + ) + .build() + + val map = toMap(params._body()) + + assertThat(map).containsKey("tools") + val tools = map["tools"] as List<*> + assertThat(tools).hasSize(1) + val tool = tools[0] as Map<*, *> + assertThat(tool["type"]).isEqualTo("function") + val function = tool["function"] as Map<*, *> + assertThat(function["name"]).isEqualTo("get_weather") + } +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAITest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAITest.kt new file mode 100644 index 000000000..78b23ea53 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAITest.kt @@ -0,0 +1,254 @@ +package com.langchain.smith.wrappers.openai + +import com.langchain.smith.client.okhttp.LangsmithOkHttpClient +import com.langchain.smith.tracing.RunType +import com.langchain.smith.tracing.TraceConfig +import com.langchain.smith.tracing.getCurrentRunTree +import com.langchain.smith.tracing.traceable +import com.openai.client.okhttp.OpenAIOkHttpClient +import com.openai.models.ChatModel +import com.openai.models.chat.completions.ChatCompletionCreateParams +import com.openai.models.chat.completions.ChatCompletionMessageParam +import com.openai.models.chat.completions.ChatCompletionToolMessageParam +import com.openai.models.responses.ResponseCreateParams +import kotlin.jvm.optionals.getOrNull +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Assumptions.assumeTrue +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance + +/** + * Integration tests for [wrapOpenAI]. + * + * Requires `LANGSMITH_API_KEY` and `OPENAI_API_KEY` to be set. Tests are skipped if either is + * missing. + * + * Run with: + * ```bash + * ./gradlew :langsmith-java-core:test --tests "com.langchain.smith.wrappers.openai.WrapOpenAITest" + * ``` + */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +internal class WrapOpenAITest { + + private lateinit var langsmith: com.langchain.smith.client.LangsmithClient + + private fun awaitPendingRuns() = Thread.sleep(2000) + + private fun baseConfig() = + TraceConfig(client = langsmith, projectName = "wrapOpenAI-tests", tracingEnabled = true) + + @BeforeAll + fun setUp() { + assumeTrue( + !System.getenv("LANGSMITH_API_KEY").isNullOrBlank(), + "Skipping: LANGSMITH_API_KEY must be set", + ) + assumeTrue( + !System.getenv("OPENAI_API_KEY").isNullOrBlank(), + "Skipping: OPENAI_API_KEY must be set", + ) + langsmith = LangsmithOkHttpClient.fromEnv() + } + + @Test + fun chatCompletions_tracedWithInputsAndOutputs() { + val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), baseConfig()) + + val completion = + openai + .chat() + .completions() + .create( + ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .addUserMessage("What is 2+2? Answer in one word.") + .maxCompletionTokens(10) + .build() + ) + + val answer = completion.choices()[0].message().content().getOrNull() ?: "" + assertThat(answer).isNotBlank() + println("[wrapOpenAI chat] Result: $answer") + awaitPendingRuns() + } + + @Test + fun responses_tracedWithInputsAndOutputs() { + val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), baseConfig()) + + val response = + openai + .responses() + .create( + ResponseCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .input("What is the capital of France? Answer in one word.") + .build() + ) + + val answer = + response.output().firstNotNullOfOrNull { item -> + item.message().getOrNull()?.content()?.firstNotNullOfOrNull { block -> + block.outputText().getOrNull()?.text() + } + } ?: "" + assertThat(answer).containsIgnoringCase("Paris") + println("[wrapOpenAI responses] Result: $answer") + awaitPendingRuns() + } + + @Test + fun chatCompletions_nestsUnderParentTrace() { + val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), baseConfig()) + + var parentRunId: String? = null + + val agent = + traceable( + { question: String -> + parentRunId = getCurrentRunTree()?.id + openai + .chat() + .completions() + .create( + ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .addUserMessage("$question Answer in one word.") + .maxCompletionTokens(10) + .build() + ) + .choices()[0] + .message() + .content() + .getOrNull() ?: "" + }, + TraceConfig( + name = "agent", + client = langsmith, + projectName = "wrapOpenAI-tests", + tracingEnabled = true, + ), + ) + + val result = agent("What is 2+2?") + assertThat(result).isNotBlank() + assertThat(parentRunId).isNotNull() + println("[wrapOpenAI nested] Result: $result") + awaitPendingRuns() + } + + @Test + fun chatCompletions_toolCallLoop() { + val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), baseConfig()) + + val executeTool = + traceable( + { _: String -> """{"location":"San Francisco","temp_f":72,"condition":"sunny"}""" }, + TraceConfig( + name = "get_weather", + client = langsmith, + projectName = "wrapOpenAI-tests", + runType = RunType.TOOL, + tracingEnabled = true, + ), + ) + + val agent = + traceable( + { question: String -> + val messages = mutableListOf() + messages += + ChatCompletionMessageParam.ofUser( + com.openai.models.chat.completions.ChatCompletionUserMessageParam + .builder() + .content("$question Use the get_weather tool.") + .build() + ) + + val weatherTool = + com.openai.models.chat.completions.ChatCompletionFunctionTool.builder() + .function( + com.openai.models.FunctionDefinition.builder() + .name("get_weather") + .description("Get weather for a location") + .parameters( + com.openai.models.FunctionParameters.builder() + .putAdditionalProperty( + "type", + com.openai.core.JsonValue.from("object"), + ) + .putAdditionalProperty( + "properties", + com.openai.core.JsonValue.from( + mapOf( + "location" to + mapOf( + "type" to "string", + "description" to "City name", + ) + ) + ), + ) + .putAdditionalProperty( + "required", + com.openai.core.JsonValue.from(listOf("location")), + ) + .build() + ) + .build() + ) + .build() + + repeat(3) { + val completion = + openai + .chat() + .completions() + .create( + ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .messages(messages) + .addTool(weatherTool) + .maxCompletionTokens(150) + .build() + ) + + val message = completion.choices()[0].message() + val toolCalls = message.toolCalls().getOrNull().orEmpty() + + if (toolCalls.isEmpty()) { + return@traceable message.content().getOrNull() ?: "" + } + + messages += ChatCompletionMessageParam.ofAssistant(message.toParam()) + toolCalls.forEach { toolCall -> + val fn = toolCall.asFunction() + val result = executeTool(fn.function().arguments()) + messages += + ChatCompletionMessageParam.ofTool( + ChatCompletionToolMessageParam.builder() + .toolCallId(fn.id()) + .content(result) + .build() + ) + } + } + + error("Model did not finish tool loop in time") + }, + TraceConfig( + name = "weather-agent", + client = langsmith, + projectName = "wrapOpenAI-tests", + tracingEnabled = true, + ), + ) + + val result = agent("What is the weather in San Francisco?") + assertThat(result).isNotBlank() + println("[wrapOpenAI tool loop] Result: $result") + awaitPendingRuns() + } +} diff --git a/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/E2eEvalExample.kt b/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/E2eEvalExample.kt deleted file mode 100644 index bac5ab021..000000000 --- a/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/E2eEvalExample.kt +++ /dev/null @@ -1,285 +0,0 @@ -package com.langchain.smith.example - -import com.langchain.smith.client.LangsmithClient -import com.langchain.smith.example.util.buildDatasetUrl -import com.langchain.smith.example.util.generateExampleId -import com.langchain.smith.client.okhttp.LangsmithOkHttpClient -import com.langchain.smith.core.JsonValue -import com.langchain.smith.models.datasets.DatasetCreateParams -import com.langchain.smith.models.datasets.DatasetListParams -import com.langchain.smith.models.examples.bulk.BulkCreateParams -import com.langchain.smith.wrappers.openai.ExperimentContext -import com.langchain.smith.wrappers.openai.OpenTelemetryConfig -import com.langchain.smith.wrappers.openai.WrappedOpenAIClient -import com.openai.models.ChatModel -import com.openai.models.chat.completions.ChatCompletion -import com.openai.models.chat.completions.ChatCompletionCreateParams -import java.time.OffsetDateTime -import java.time.format.DateTimeFormatter - -/** - * Demonstrates how to run real experiments in LangSmith using OpenAI with automatic tracing. - * - * This example shows: - * - Configuring OpenTelemetry to send traces to LangSmith automatically - * - Creating a dataset idempotently (get or create) - * - Creating examples with deterministic IDs for idempotent operations - * - Running real OpenAI experiments using the wrapped client - * - Using ExperimentContext to link traces to dataset examples - * - Automatic trace submission via OpenTelemetry (no manual run ingestion!) - * - * ## Key Differences from RecordExperimentExample - * - Uses wrapped OpenAI client for **real** LLM calls (not mocked) - * - **No manual session creation** - project name in OTel config acts as the session - * - **No manual run ingestion** - OpenTelemetry automatically sends traces to LangSmith - * - Uses ExperimentContext to link traces to dataset examples automatically - * - * ## Prerequisites - * Set these environment variables before running: - * - `LANGSMITH_API_KEY`: Your LangSmith API key - * - `OPENAI_API_KEY`: Your OpenAI API key - * - * ## Running - * ```bash - * ./gradlew :langsmith-java-example:run -Pexample=RunExperiment - * ``` - */ - -/** - * Simple Q&A agent that uses OpenAI to answer questions. - */ -class SimpleQAAgent(private val client: WrappedOpenAIClient, private val model: ChatModel = ChatModel.GPT_4O_MINI) { - - /** - * Answer a question using OpenAI. - * The wrapped client automatically creates OpenTelemetry spans that are sent to LangSmith. - */ - fun answer(question: String): String { - val params = ChatCompletionCreateParams.builder() - .model(model) - .addUserMessage(question) - .build() - - val completion: ChatCompletion = client.chat().completions().create(params) - return completion.choices()[0].message().content().orElse("No response") - } -} - -fun main() { - println("=".repeat(60)) - println("LangSmith Real Experiment Example (with OpenAI)") - println("=".repeat(60)) - println() - - // Check required environment variables - if (System.getenv("LANGSMITH_API_KEY").isNullOrEmpty()) { - System.err.println("✗ Error: LANGSMITH_API_KEY environment variable is required") - System.err.println(" Please set your LangSmith API key to run experiments") - return - } - - val openaiApiKey = System.getenv("OPENAI_API_KEY") - if (openaiApiKey.isNullOrEmpty()) { - System.err.println("✗ Error: OPENAI_API_KEY environment variable is required") - System.err.println(" Please set your OpenAI API key to run the agent") - return - } - - // Configure LangSmith client first (needed to create session) - val langsmithClient: LangsmithClient = LangsmithOkHttpClient.fromEnv() - - val datasetName = "Q&A Evaluation Dataset - Kotlin Example" - val experimentName = "E2eEvalExample-${OffsetDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss"))}" - - // Define test cases with questions and expected answers - println("Defining test cases...") - val testCases = listOf( - mapOf( - "question" to "What is the capital of France?", - "expected_answer" to "Paris" - ), - mapOf( - "question" to "What is 2 + 2?", - "expected_answer" to "4" - ), - mapOf( - "question" to "Who wrote Romeo and Juliet?", - "expected_answer" to "William Shakespeare" - ), - mapOf( - "question" to "What is the largest planet in our solar system?", - "expected_answer" to "Jupiter" - ) - ) - println(" ✓ Defined ${testCases.size} test cases") - println() - - // 1. Get or create dataset (idempotent) - println("1. Getting or creating dataset '$datasetName'...") - val listParams = DatasetListParams.builder() - .name(datasetName) - .build() - val existingDatasets = langsmithClient.datasets().list(listParams) - - val dataset = if (existingDatasets.items().isNotEmpty()) { - val existing = existingDatasets.items()[0] - println(" ✓ Found existing dataset (ID: ${existing.id()})") - existing - } else { - val createParams = DatasetCreateParams.builder() - .name(datasetName) - .description("Dataset for Q&A evaluation with real OpenAI experiments.") - .build() - val created = langsmithClient.datasets().create(createParams) - println(" ✓ Created new dataset (ID: ${created.id()})") - created - } - println(" → View dataset: ${buildDatasetUrl(dataset)}") - println() - - // 2. Create examples from test cases (idempotent with deterministic IDs) - println("2. Creating dataset examples from test cases...") - val exampleBodies = testCases.map { testCase -> - val input = mapOf("question" to testCase["question"]!!) - val referenceOutput = mapOf("answer" to testCase["expected_answer"]!!) - - // Generate deterministic ID for idempotent creation - val exampleId = generateExampleId(dataset.id(), input, referenceOutput) - - BulkCreateParams.Body.builder() - .id(exampleId) - .datasetId(dataset.id()) - .inputs(JsonValue.from(input)) - .outputs(JsonValue.from(referenceOutput)) - .build() - } - - val bulkCreateParams = BulkCreateParams.builder() - .apply { exampleBodies.forEach { addBody(it) } } - .build() - - val createdExamples = langsmithClient.examples().bulk().create(bulkCreateParams) - println(" ✓ Created/updated ${createdExamples.size} examples with deterministic IDs") - println() - - // 3. Create experiment session linked to the dataset - // Each run creates a new session with a unique timestamped name - println("3. Creating experiment session linked to dataset...") - val sessionParams = com.langchain.smith.models.sessions.SessionCreateParams.builder() - .name(experimentName) - .description("Experiment session for Q&A evaluation using OpenAI") - .referenceDatasetId(dataset.id()) // Link session to dataset - critical for Experiments tab - .build() - val created = langsmithClient.sessions().create(sessionParams) - val sessionId = created.id() - val sessionTenantId = created.tenantId() - println(" ✓ Created experiment session: ${created.name()}") - println(" ✓ Session ID: $sessionId") - println(" ✓ Session linked to dataset") - println() - - // 4. Configure OpenTelemetry to send traces to LangSmith - // Initializes global OpenTelemetry SDK for automatic trace collection (return value not needed) - println("4. Configuring OpenTelemetry for LangSmith...") - OpenTelemetryConfig.builder() - .processorType(OpenTelemetryConfig.SpanProcessorType.SIMPLE) - .build() - println(" ✓ OpenTelemetry configured to send traces with session_id attribute") - println() - - // 5. Create wrapped OpenAI client - // The wrapped client automatically creates OpenTelemetry spans for each LLM call - val openaiClient: WrappedOpenAIClient = WrappedOpenAIClient.fromEnv() - - // 6. Run experiments: Execute agent against each test case - println("5. Running experiments with OpenAI agent...") - println(" Each LLM call will automatically create a trace in LangSmith") - println(" linked to the corresponding dataset example.") - println() - - val agent = SimpleQAAgent(openaiClient) - - createdExamples.forEachIndexed { index, example -> - val testCase = testCases[index] - val question = testCase["question"] as String - val expectedAnswer = testCase["expected_answer"] as String - - println(" Test ${index + 1}/${testCases.size}: \"$question\"") - println(" Expected: $expectedAnswer") - - try { - // Attach example and session id to experiment run. - ExperimentContext.withExperiment(example.id(), sessionId).use { - // Run the agent - the wrapped OpenAI client will automatically: - // 1. Create OpenTelemetry spans for the LLM call - // 2. Include reference_example_id and session_id from ExperimentContext - // 3. Send the spans to LangSmith via the configured OTLP exporter - // 4. Link the run to the experiment session (appears in Experiments tab!) - val actualAnswer = agent.answer(question) - - println(" Actual: $actualAnswer") - println(" → Trace sent to LangSmith and linked to experiment") - } - - } catch (e: Exception) { - println(" ✗ Error: ${e.message}") - } - println() - } - - println(" ✓ Completed ${createdExamples.size} experiment runs") - println() - - // Close clients and flush traces - openaiClient.close() - - // Force flush to ensure all spans are exported to LangSmith - println("6. Flushing traces to LangSmith...") - val flushed = OpenTelemetryConfig.flush(10, java.util.concurrent.TimeUnit.SECONDS) - if (!flushed) { - System.err.println(" ✗ Warning: Flush did not complete successfully") - System.err.println(" Some traces may not have been sent to LangSmith") - } else { - println(" ✓ All traces flushed successfully") - } - println() - - // Summary - println("=".repeat(60)) - println("Experiment Complete!") - println("=".repeat(60)) - println() - println("What happened:") - println(" • Dataset: $datasetName with ${createdExamples.size} examples") - println(" • Session: $experimentName linked to dataset (aka. experiement)") - println(" • Each run includes:") - println(" - Input question from the dataset") - println(" - Reference/expected answer") - println(" - Actual answer from OpenAI") - println(" - Complete OpenTelemetry trace automatically sent to LangSmith and linked to dataset") - println() - println("How it works:") - println(" 1. Create/find a session linked to the dataset (via reference_dataset_id)") - println(" 2. Configure OpenTelemetry") - println(" 3. Use ExperimentContext.withExperiment() to link the experiment run to the dataset/example") - println(" 4. WrappedOpenAIClient automatically creates and exports traces with proper linkage") - println(" 5. Experiment appears in dataset's 'Experiments' tab!") - println() - println("Next steps:") - println(" 1. View the dataset and experiments tab:") - println(" ${buildDatasetUrl(dataset)}") - println() - println(" 2. In the LangSmith UI, you can:") - println(" - Compare actual answers vs expected answers side-by-side") - println(" - Add LLM-as-judge evaluators to automatically evaluate your experiments") - println(" - View detailed traces of each OpenAI call") - println(" - Analyze token usage and latency metrics") - println(" - Much more...") - println() - println(" 3. Run this example again:") - println(" - A new experiment session will be created with a unique timestamp") - println(" - Dataset and examples are reused (idempotent)") - println(" - Each run appears as a separate experiment in the Experiments tab of the dataset") - println(" - You can compare results across multiple experiment runs") - println() -} diff --git a/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/StreamingLangSmithExample.kt b/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/StreamingLangSmithExample.kt deleted file mode 100644 index 04b714565..000000000 --- a/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/StreamingLangSmithExample.kt +++ /dev/null @@ -1,138 +0,0 @@ -package com.langchain.smith.example - -import com.langchain.smith.wrappers.openai.OpenTelemetryConfig -import com.langchain.smith.wrappers.openai.WrappedOpenAIClient -import com.openai.models.ChatModel -import com.openai.models.chat.completions.ChatCompletionCreateParams -import kotlin.jvm.optionals.getOrNull -import java.util.concurrent.TimeUnit -import kotlin.system.exitProcess - -/** - * Example: Stream chat completions and send traces to LangSmith. - * - * - Creates a streaming chat completion request - * - Consumes the full stream (all chunks until done), accumulates content, counts chunks - * - Closes the stream so the span is ended and completion/usage are written - * - Flushes traces to LangSmith - * - * Uses the wrapped OpenAI client so streaming calls are traced and exported via OpenTelemetry. - * In LangSmith, streaming traces have span attribute `gen_ai.streaming` = true. - * - * ## Prerequisites - * Export these environment variables before running: - * - `OPENAI_API_KEY`: Your OpenAI API key - * - `LANGSMITH_API_KEY`: Your LangSmith API key - * - `LANGSMITH_PROJECT`: (optional) LangSmith project name; defaults to "default" - * - `LANGSMITH_ENDPOINT`: (optional) LangSmith API base URL; defaults to https://api.smith.langchain.com - * - * ## Running - * ```bash - * ./gradlew :langsmith-java-example:run -Pexample=StreamingLangSmith - * ``` - */ -fun main() { - println("=== Streaming Chat + LangSmith Traces Example ===\n") - - val openaiKey = System.getenv("OPENAI_API_KEY") - if (openaiKey.isNullOrEmpty()) { - System.err.println("ERROR: OPENAI_API_KEY environment variable is required!") - System.err.println(" export OPENAI_API_KEY=your_openai_api_key") - exitProcess(1) - } - - val langsmithKey = System.getenv("LANGSMITH_API_KEY") - if (langsmithKey.isNullOrEmpty()) { - System.err.println("ERROR: LANGSMITH_API_KEY environment variable is required!") - System.err.println(" export LANGSMITH_API_KEY=your_langsmith_api_key") - exitProcess(1) - } - - val projectName = System.getenv("LANGSMITH_PROJECT") ?: "default" - - val traceEndpoint = System.getenv("LANGSMITH_ENDPOINT") ?: OpenTelemetryConfig.DEFAULT_BASE_URL - println("Configuration:") - println(" LangSmith project: $projectName") - println(" Trace endpoint: $traceEndpoint/otel/v1/traces") - println() - - try { - OpenTelemetryConfig.builder() - .apiKey(langsmithKey) - .projectName(projectName) - .serviceName("streaming-langsmith-example") - .processorType(OpenTelemetryConfig.SpanProcessorType.SIMPLE) - .maxBatchSize(1) - .build() - println("✓ OpenTelemetry configured for LangSmith\n") - } catch (e: Exception) { - System.err.println("✗ Failed to configure OpenTelemetry: ${e.message}") - e.printStackTrace() - exitProcess(1) - } - - val client = WrappedOpenAIClient.fromEnv() - - - val prompt = "Count from 1 to 20" - println("Prompt: \"$prompt\"") - println("Streamed reply: ") - - var chunkCount = 0 - val fullContent = StringBuilder() - - try { - val params = ChatCompletionCreateParams.builder() - .model(ChatModel.GPT_4O_MINI) - .addUserMessage(prompt) - .maxCompletionTokens(100) - .temperature(0.0) - .build() - - // This uses the streaming API (createStreaming). Traces will have gen_ai.streaming=true. - val streamResponse = client.chat().completions().createStreaming(params) - try { - streamResponse.stream().forEach { chunk -> - chunkCount++ - val choices = chunk.choices() - if (choices.isNotEmpty()) { - val delta = choices[0].delta() - delta.content().getOrNull()?.let { content -> - fullContent.append(content) - print(content) - } - } - } - } finally { - streamResponse.close() - } - println("\n") - } catch (e: Exception) { - System.err.println("\n✗ Error during streaming: ${e.message}") - e.printStackTrace() - client.close() - exitProcess(1) - } - - client.close() - - println("Chunks received: $chunkCount") - println("Full content: \"${fullContent}\"") - println("(Trace was streaming: see gen_ai.streaming=true on the span in LangSmith)") - if (chunkCount == 0) { - System.err.println("✗ Expected at least one chunk") - } - if (fullContent.isEmpty()) { - System.err.println("✗ Expected non-empty streamed content") - } - - println("\nFlushing traces to LangSmith...") - val flushed = OpenTelemetryConfig.flush(10, TimeUnit.SECONDS) - OpenTelemetryConfig.shutdown() - if (flushed) { - println("✓ Flush completed. View traces: https://smith.langchain.com/projects/$projectName") - println(" (If you don't see traces, set LANGSMITH_DEBUG=true and run again to see export errors.)") - } else { - System.err.println("✗ Warning: Flush may not have completed. Set LANGSMITH_DEBUG=true to see export errors.") - } -} diff --git a/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIExample.kt b/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIExample.kt new file mode 100644 index 000000000..3ed4ea279 --- /dev/null +++ b/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIExample.kt @@ -0,0 +1,49 @@ +package com.langchain.smith.example + +import com.langchain.smith.client.okhttp.LangsmithOkHttpClient +import com.langchain.smith.tracing.TraceConfig +import com.langchain.smith.wrappers.openai.wrapOpenAI +import com.openai.client.okhttp.OpenAIOkHttpClient +import com.openai.models.ChatModel +import com.openai.models.chat.completions.ChatCompletionCreateParams + +/** + * Demonstrates tracing OpenAI calls with LangSmith using [wrapOpenAI]. + * + * Wrap your OpenAI client once, then use it normally — all `chat().completions().create()` and + * `responses().create()` calls are automatically traced to LangSmith. + * + * ## Prerequisites + * - `LANGSMITH_API_KEY`: Your LangSmith API key + * - `OPENAI_API_KEY`: Your OpenAI API key + * - `LANGSMITH_TRACING`: Set to "true" to enable tracing + * + * ## Running + * ```bash + * export LANGSMITH_TRACING=true + * ./gradlew :langsmith-java-example:run -Pexample=WrapOpenAI + * ``` + */ +fun main() { + println("=== wrapOpenAI Example ===\n") + + // 1. Create clients + val langsmith = LangsmithOkHttpClient.fromEnv() + val openai = wrapOpenAI( + OpenAIOkHttpClient.fromEnv(), + TraceConfig.builder().client(langsmith).build(), + ) + + // 2. Use the wrapped client normally — calls are traced automatically + val params = ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .addUserMessage("What is the capital of France? Reply in one word.") + .build() + + println("Sending chat completion request...") + val completion = openai.chat().completions().create(params) + + val reply = completion.choices().firstOrNull()?.message()?.content()?.orElse(null) + println("Response: $reply") + println("\nTrace recorded to LangSmith (check your dashboard)") +} diff --git a/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/otel/OtelOpenAIExample.kt b/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/otel/OtelOpenAIExample.kt deleted file mode 100644 index 8775bb649..000000000 --- a/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/otel/OtelOpenAIExample.kt +++ /dev/null @@ -1,285 +0,0 @@ -package com.langchain.smith.example.otel - -import com.fasterxml.jackson.databind.JsonNode -import com.fasterxml.jackson.databind.ObjectMapper -import com.langchain.smith.wrappers.openai.OpenTelemetryConfig -import com.langchain.smith.wrappers.openai.WrappedOpenAIClient -import com.openai.models.ChatModel -import com.openai.models.FunctionDefinition -import com.openai.models.FunctionParameters -import com.openai.models.chat.completions.ChatCompletionAssistantMessageParam -import com.openai.models.chat.completions.ChatCompletionCreateParams -import com.openai.models.chat.completions.ChatCompletionFunctionTool -import com.openai.models.chat.completions.ChatCompletionMessageParam -import com.openai.models.chat.completions.ChatCompletionMessageToolCall -import com.openai.models.chat.completions.ChatCompletionTool -import com.openai.models.chat.completions.ChatCompletionToolChoiceOption -import com.openai.models.chat.completions.ChatCompletionToolMessageParam -import io.opentelemetry.api.OpenTelemetry -import io.opentelemetry.api.common.AttributeKey -import io.opentelemetry.api.trace.Span -import io.opentelemetry.api.trace.SpanKind -import io.opentelemetry.api.trace.StatusCode -import io.opentelemetry.api.trace.Tracer -import io.opentelemetry.context.Scope -import java.util.concurrent.TimeUnit -import kotlin.system.exitProcess - -/** - * Example: Make real OpenAI API calls with OpenTelemetry tracing to LangSmith. - * - * Demonstrates: - * - Configuring OpenTelemetry to send traces to LangSmith - * - Using the wrapped OpenAI client for automatic tracing - * - Making actual API calls to OpenAI with tool definitions - * - Automatic tool call span creation - * - Multi-turn conversations with tool execution - * - * Usage: - * export OPENAI_API_KEY=your_openai_api_key - * export LANGSMITH_API_KEY=your_langsmith_api_key - * export LANGSMITH_PROJECT=your_project_name - * ./gradlew :langsmith-java-example:run -Pexample=OtelOpenAI - */ -private const val SEPARATOR = "============================================================" - -fun main() { - println("=== OpenAI + LangSmith OpenTelemetry Example ===\n") - - val openaiKey = System.getenv("OPENAI_API_KEY") - if (openaiKey.isNullOrEmpty()) { - System.err.println("ERROR: OPENAI_API_KEY environment variable is required!") - System.err.println("Get your API key from: https://platform.openai.com/api-keys") - exitProcess(1) - } - - val langsmithKey = System.getenv("LANGSMITH_API_KEY") - if (langsmithKey.isNullOrEmpty()) { - System.err.println("ERROR: LANGSMITH_API_KEY environment variable is required!") - System.err.println("Get your API key from: https://smith.langchain.com/settings") - exitProcess(1) - } - - val projectName = System.getenv("LANGSMITH_PROJECT") ?: "default" - - println("Configuration:") - println(" LangSmith Project: $projectName") - println(" Service Name: langsmith-kotlin-openai-example") - println() - - try { - OpenTelemetryConfig.builder() - .apiKey(langsmithKey) - .projectName(projectName) - .serviceName("langsmith-kotlin-openai-example") - .processorType(OpenTelemetryConfig.SpanProcessorType.SIMPLE) - .maxBatchSize(1) - .build() - println("✓ OpenTelemetry configured for LangSmith\n") - } catch (e: Exception) { - System.err.println("✗ Failed to configure OpenTelemetry: ${e.message}") - e.printStackTrace() - exitProcess(1) - } - - val client = WrappedOpenAIClient.fromEnv() - val openTelemetry: OpenTelemetry = io.opentelemetry.api.GlobalOpenTelemetry.get() - val tracer: Tracer = openTelemetry.getTracer("langsmith-kotlin-openai-example") - - val workflowSpan = tracer.spanBuilder("openai_agent_workflow") - .setSpanKind(SpanKind.INTERNAL) - .setAttribute("gen_ai.operation.name", "agent_workflow") - .setAttribute("langsmith.span.kind", "chain") - .setAttribute("langsmith.trace.name", "OpenAI Agent with Tools") - .startSpan() - - try { - workflowSpan.makeCurrent().use { _ -> - val span = workflowSpan - println(SEPARATOR) - println("Agent Workflow: Chat with Tool Calls") - println(SEPARATOR) - - val locationProperty = mapOf( - "type" to com.openai.core.JsonValue.from("string"), - "description" to com.openai.core.JsonValue.from("The city and state, e.g., San Francisco, CA") - ) - val properties = mapOf("location" to com.openai.core.JsonValue.from(locationProperty)) - val parametersJson = mapOf( - "type" to com.openai.core.JsonValue.from("object"), - "properties" to com.openai.core.JsonValue.from(properties), - "required" to com.openai.core.JsonValue.from(listOf("location")) - ) - - val initialUserMessage = "What is the capital of France and what's the current weather there?" - val params = ChatCompletionCreateParams.builder() - .model(ChatModel.GPT_4O_MINI) - .addUserMessage(initialUserMessage) - .tools( - listOf( - ChatCompletionTool.ofFunction( - ChatCompletionFunctionTool.builder() - .function( - FunctionDefinition.builder() - .name("get_weather") - .description("Get the current weather for a given location") - .parameters(FunctionParameters.builder().putAllAdditionalProperties(parametersJson).build()) - .build() - ) - .build() - ) - ) - ) - .toolChoice(ChatCompletionToolChoiceOption.ofAuto(ChatCompletionToolChoiceOption.Auto.AUTO)) - .build() - - span.setAttribute(AttributeKey.stringKey("gen_ai.prompt"), initialUserMessage) - - println("\n1. Making initial API call with tool definitions...") - var completion = client.chat().completions().create(params) - val message = completion.choices()[0].message() - val toolCallsOpt = message.toolCalls() - - val finalContent = if (toolCallsOpt.isPresent && toolCallsOpt.get().isNotEmpty()) { - println(" ✓ Tool calls detected in response!") - val toolCalls = toolCallsOpt.get() - val messages = mutableListOf() - messages.add(params.messages()[0]) - messages.add( - ChatCompletionMessageParam.ofAssistant( - ChatCompletionAssistantMessageParam.builder() - .content(message.content().orElse("")) - .toolCalls(toolCalls) - .build() - ) - ) - - println("\n2. Executing tool calls...") - for (toolCall in toolCalls) { - if (toolCall.isFunction()) { - val functionToolCall = toolCall.asFunction() - val toolName = functionToolCall.function().name() - val toolArguments = functionToolCall.function().arguments() - val toolCallId = functionToolCall.id() - - println(" - Tool: $toolName | Args: $toolArguments") - - val toolExecutionSpan = tracer.spanBuilder("tool_execution $toolName") - .setSpanKind(SpanKind.INTERNAL) - .setAttribute(AttributeKey.stringKey("gen_ai.operation.name"), "tool") - .setAttribute(AttributeKey.stringKey("gen_ai.tool.name"), toolName) - .setAttribute(AttributeKey.stringKey("gen_ai.tool.call.id"), toolCallId) - .setAttribute(AttributeKey.stringKey("gen_ai.tool.arguments"), toolArguments) - .setAttribute(AttributeKey.stringKey("langsmith.span.kind"), "tool") - .setAttribute(AttributeKey.stringKey("gen_ai.prompt"), toolArguments) - .startSpan() - - val toolResult = try { - toolExecutionSpan.makeCurrent().use { - val result = executeTool(toolName, toolArguments) - println(" - Result: $result") - toolExecutionSpan.setAttribute(AttributeKey.stringKey("gen_ai.completion"), result) - toolExecutionSpan.setStatus(StatusCode.OK) - result - } - } catch (e: Exception) { - toolExecutionSpan.recordException(e) - toolExecutionSpan.setStatus(StatusCode.ERROR) - "{\"error\": \"${e.message}\"}" - } finally { - toolExecutionSpan.end() - } - - messages.add( - ChatCompletionMessageParam.ofTool( - ChatCompletionToolMessageParam.builder() - .toolCallId(functionToolCall.id()) - .content(toolResult) - .build() - ) - ) - } - } - - println("\n3. Sending follow-up request with tool results...") - val followUpParams = ChatCompletionCreateParams.builder() - .model(ChatModel.GPT_4O_MINI) - .messages(messages) - .build() - completion = client.chat().completions().create(followUpParams) - completion.choices()[0].message().content().orElse("No content") - } else { - message.content().orElse("No content") - } - - println("\n$SEPARATOR") - println("Final Response:") - println(finalContent) - println(SEPARATOR) - - completion.usage().ifPresent { usage -> - println("\nTotal Token Usage:") - println(" Input: ${usage.promptTokens()}") - println(" Output: ${usage.completionTokens()}") - println(" Total: ${usage.totalTokens()}") - } - - span.setAttribute(AttributeKey.stringKey("gen_ai.completion"), finalContent) - span.setAttribute("response.content", finalContent) - span.setStatus(StatusCode.OK) - } - } catch (e: Exception) { - workflowSpan.recordException(e) - System.err.println("\n✗ Error during API call: ${e.message}") - e.printStackTrace() - workflowSpan.recordException(e) - workflowSpan.setStatus(StatusCode.ERROR) - } finally { - workflowSpan.end() - } - - client.close() - - println("\n$SEPARATOR") - println("Flushing traces to LangSmith...") - val flushed = OpenTelemetryConfig.flush(10, TimeUnit.SECONDS) - - if (flushed) { - println("✓ Traces sent successfully!") - println("\nView your traces at:") - println(" https://smith.langchain.com/projects/$projectName") - } else { - System.err.println("✗ Warning: Flush may not have completed successfully") - } - - println(SEPARATOR) - println("\nNote: Check the trace waterfall in LangSmith UI to see:") - println(" - Parent workflow span (chain)") - println(" - Child LLM spans (automatically created)") - println(" - Tool call spans (automatically created by wrapper)") -} - -private fun executeTool(toolName: String, arguments: String): String { - return try { - val mapper = ObjectMapper() - val args = mapper.readTree(arguments) - - if (toolName == "get_weather") { - val location = if (args.has("location")) args.get("location").asText() else "unknown" - val result = mapOf( - "location" to location, - "temperature" to "18°C", - "condition" to "Partly Cloudy", - "humidity" to "65%", - "wind" to "15 km/h" - ) - mapper.writeValueAsString(result) - } else { - val errorMap = mapOf("error" to "Unknown tool: $toolName") - mapper.writeValueAsString(errorMap) - } - } catch (e: Exception) { - "{\"error\": \"${e.message}\"}" - } -} - From 0c914884473e1de2877708cd92db30fdc8fc10aa Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 30 Mar 2026 20:13:50 +0000 Subject: [PATCH 28/35] feat(api): api update --- .stats.yml | 4 +- .../models/commits/CommitCreateParams.kt | 79 +++++++++++++++++-- .../models/commits/CommitRetrieveResponse.kt | 48 ++++++++++- .../smith/models/commits/CommitWithLookups.kt | 41 +++++++++- .../models/commits/CommitCreateParamsTest.kt | 3 + .../commits/CommitCreateResponseTest.kt | 3 + .../commits/CommitListPageResponseTest.kt | 3 + .../commits/CommitRetrieveResponseTest.kt | 3 + .../models/commits/CommitWithLookupsTest.kt | 3 + .../services/async/CommitServiceAsyncTest.kt | 1 + .../services/blocking/CommitServiceTest.kt | 1 + 11 files changed, 179 insertions(+), 10 deletions(-) diff --git a/.stats.yml b/.stats.yml index 45de7173b..9dc077b9c 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 103 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-c8cfbe86e6def6ed237572671330ab268d0f4482ca206d46523a504d5202c78a.yml -openapi_spec_hash: e3c416da737cb6f4fb8945ca8010443d +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-4d7b0427f9ed66e112fcc2f2a3a91e7f2c8113eb6386910c48b52ef7a605b282.yml +openapi_spec_hash: 601517cba6d1a4f06c494f42f11e3f96 config_hash: c217b34d458f1b65f260715693d447f9 diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitCreateParams.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitCreateParams.kt index 4cc18e316..13e9d2848 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitCreateParams.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitCreateParams.kt @@ -36,6 +36,12 @@ private constructor( fun repo(): Optional = Optional.ofNullable(repo) + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = body.description() + /** * This arbitrary value can be deserialized into a custom type using the `convert` method: * ```java @@ -61,6 +67,13 @@ private constructor( */ fun _skipWebhooks(): JsonValue = body._skipWebhooks() + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + fun _description(): JsonField = body._description() + /** * Returns the raw JSON value of [parentCommit]. * @@ -121,12 +134,24 @@ private constructor( * * This is generally only useful if you are already constructing the body separately. * Otherwise, it's more convenient to use the top-level setters instead: + * - [description] * - [manifest] * - [parentCommit] * - [skipWebhooks] */ fun body(body: Body) = apply { this.body = body.toBuilder() } + fun description(description: String) = apply { body.description(description) } + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { body.description(description) } + fun manifest(manifest: JsonValue) = apply { body.manifest(manifest) } fun parentCommit(parentCommit: String) = apply { body.parentCommit(parentCommit) } @@ -303,6 +328,7 @@ private constructor( class Body @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( + private val description: JsonField, private val manifest: JsonValue, private val parentCommit: JsonField, private val skipWebhooks: JsonValue, @@ -311,6 +337,9 @@ private constructor( @JsonCreator private constructor( + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), @JsonProperty("manifest") @ExcludeMissing manifest: JsonValue = JsonMissing.of(), @JsonProperty("parent_commit") @ExcludeMissing @@ -318,7 +347,13 @@ private constructor( @JsonProperty("skip_webhooks") @ExcludeMissing skipWebhooks: JsonValue = JsonMissing.of(), - ) : this(manifest, parentCommit, skipWebhooks, mutableMapOf()) + ) : this(description, manifest, parentCommit, skipWebhooks, mutableMapOf()) + + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if + * the server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") /** * This arbitrary value can be deserialized into a custom type using the `convert` method: @@ -345,6 +380,15 @@ private constructor( */ @JsonProperty("skip_webhooks") @ExcludeMissing fun _skipWebhooks(): JsonValue = skipWebhooks + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") + @ExcludeMissing + fun _description(): JsonField = description + /** * Returns the raw JSON value of [parentCommit]. * @@ -376,6 +420,7 @@ private constructor( /** A builder for [Body]. */ class Builder internal constructor() { + private var description: JsonField = JsonMissing.of() private var manifest: JsonValue = JsonMissing.of() private var parentCommit: JsonField = JsonMissing.of() private var skipWebhooks: JsonValue = JsonMissing.of() @@ -383,12 +428,26 @@ private constructor( @JvmSynthetic internal fun from(body: Body) = apply { + description = body.description manifest = body.manifest parentCommit = body.parentCommit skipWebhooks = body.skipWebhooks additionalProperties = body.additionalProperties.toMutableMap() } + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. + */ + fun description(description: JsonField) = apply { + this.description = description + } + fun manifest(manifest: JsonValue) = apply { this.manifest = manifest } fun parentCommit(parentCommit: String) = parentCommit(JsonField.of(parentCommit)) @@ -435,7 +494,13 @@ private constructor( * Further updates to this [Builder] will not mutate the returned instance. */ fun build(): Body = - Body(manifest, parentCommit, skipWebhooks, additionalProperties.toMutableMap()) + Body( + description, + manifest, + parentCommit, + skipWebhooks, + additionalProperties.toMutableMap(), + ) } private var validated: Boolean = false @@ -445,6 +510,7 @@ private constructor( return@apply } + description() parentCommit() validated = true } @@ -464,7 +530,9 @@ private constructor( * Used for best match union deserialization. */ @JvmSynthetic - internal fun validity(): Int = (if (parentCommit.asKnown().isPresent) 1 else 0) + internal fun validity(): Int = + (if (description.asKnown().isPresent) 1 else 0) + + (if (parentCommit.asKnown().isPresent) 1 else 0) override fun equals(other: Any?): Boolean { if (this === other) { @@ -472,6 +540,7 @@ private constructor( } return other is Body && + description == other.description && manifest == other.manifest && parentCommit == other.parentCommit && skipWebhooks == other.skipWebhooks && @@ -479,13 +548,13 @@ private constructor( } private val hashCode: Int by lazy { - Objects.hash(manifest, parentCommit, skipWebhooks, additionalProperties) + Objects.hash(description, manifest, parentCommit, skipWebhooks, additionalProperties) } override fun hashCode(): Int = hashCode override fun toString() = - "Body{manifest=$manifest, parentCommit=$parentCommit, skipWebhooks=$skipWebhooks, additionalProperties=$additionalProperties}" + "Body{description=$description, manifest=$manifest, parentCommit=$parentCommit, skipWebhooks=$skipWebhooks, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponse.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponse.kt index e2fe4eb7b..5ed8330bb 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponse.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponse.kt @@ -22,6 +22,7 @@ class CommitRetrieveResponse @JsonCreator(mode = JsonCreator.Mode.DISABLED) private constructor( private val commitHash: JsonField, + private val description: JsonField, private val examples: JsonField>, private val isDraft: JsonField, private val manifest: JsonValue, @@ -35,6 +36,9 @@ private constructor( @JsonProperty("commit_hash") @ExcludeMissing commitHash: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), @JsonProperty("examples") @ExcludeMissing examples: JsonField> = JsonMissing.of(), @@ -44,7 +48,16 @@ private constructor( @JsonProperty("model_provider") @ExcludeMissing modelProvider: JsonField = JsonMissing.of(), - ) : this(commitHash, examples, isDraft, manifest, modelConfig, modelProvider, mutableMapOf()) + ) : this( + commitHash, + description, + examples, + isDraft, + manifest, + modelConfig, + modelProvider, + mutableMapOf(), + ) /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -52,6 +65,12 @@ private constructor( */ fun commitHash(): Optional = commitHash.getOptional("commit_hash") + /** + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). @@ -93,6 +112,13 @@ private constructor( */ @JsonProperty("commit_hash") @ExcludeMissing fun _commitHash(): JsonField = commitHash + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + /** * Returns the raw JSON value of [examples]. * @@ -138,6 +164,7 @@ private constructor( class Builder internal constructor() { private var commitHash: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() private var examples: JsonField>? = null private var isDraft: JsonField = JsonMissing.of() private var manifest: JsonValue = JsonMissing.of() @@ -148,6 +175,7 @@ private constructor( @JvmSynthetic internal fun from(commitRetrieveResponse: CommitRetrieveResponse) = apply { commitHash = commitRetrieveResponse.commitHash + description = commitRetrieveResponse.description examples = commitRetrieveResponse.examples.map { it.toMutableList() } isDraft = commitRetrieveResponse.isDraft manifest = commitRetrieveResponse.manifest @@ -167,6 +195,17 @@ private constructor( */ fun commitHash(commitHash: JsonField) = apply { this.commitHash = commitHash } + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { this.description = description } + fun examples(examples: List) = examples(JsonField.of(examples)) /** @@ -246,6 +285,7 @@ private constructor( fun build(): CommitRetrieveResponse = CommitRetrieveResponse( commitHash, + description, (examples ?: JsonMissing.of()).map { it.toImmutable() }, isDraft, manifest, @@ -263,6 +303,7 @@ private constructor( } commitHash() + description() examples().ifPresent { it.forEach { it.validate() } } isDraft() modelProvider() @@ -285,6 +326,7 @@ private constructor( @JvmSynthetic internal fun validity(): Int = (if (commitHash.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + (examples.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) + (if (isDraft.asKnown().isPresent) 1 else 0) + (if (modelProvider.asKnown().isPresent) 1 else 0) @@ -542,6 +584,7 @@ private constructor( return other is CommitRetrieveResponse && commitHash == other.commitHash && + description == other.description && examples == other.examples && isDraft == other.isDraft && manifest == other.manifest && @@ -553,6 +596,7 @@ private constructor( private val hashCode: Int by lazy { Objects.hash( commitHash, + description, examples, isDraft, manifest, @@ -565,5 +609,5 @@ private constructor( override fun hashCode(): Int = hashCode override fun toString() = - "CommitRetrieveResponse{commitHash=$commitHash, examples=$examples, isDraft=$isDraft, manifest=$manifest, modelConfig=$modelConfig, modelProvider=$modelProvider, additionalProperties=$additionalProperties}" + "CommitRetrieveResponse{commitHash=$commitHash, description=$description, examples=$examples, isDraft=$isDraft, manifest=$manifest, modelConfig=$modelConfig, modelProvider=$modelProvider, additionalProperties=$additionalProperties}" } diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitWithLookups.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitWithLookups.kt index 3027af234..df0436e2a 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitWithLookups.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/commits/CommitWithLookups.kt @@ -25,6 +25,7 @@ private constructor( private val id: JsonField, private val commitHash: JsonField, private val createdAt: JsonField, + private val description: JsonField, private val exampleRunIds: JsonField>, private val fullName: JsonField, private val manifest: JsonValue, @@ -47,6 +48,9 @@ private constructor( @JsonProperty("created_at") @ExcludeMissing createdAt: JsonField = JsonMissing.of(), + @JsonProperty("description") + @ExcludeMissing + description: JsonField = JsonMissing.of(), @JsonProperty("example_run_ids") @ExcludeMissing exampleRunIds: JsonField> = JsonMissing.of(), @@ -71,6 +75,7 @@ private constructor( id, commitHash, createdAt, + description, exampleRunIds, fullName, manifest, @@ -108,6 +113,14 @@ private constructor( */ fun createdAt(): Optional = createdAt.getOptional("created_at") + /** + * Optional human-readable description for the commit + * + * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the + * server responded with an unexpected value). + */ + fun description(): Optional = description.getOptional("description") + /** * Example run IDs associated with the commit * @@ -213,6 +226,13 @@ private constructor( @ExcludeMissing fun _createdAt(): JsonField = createdAt + /** + * Returns the raw JSON value of [description]. + * + * Unlike [description], this method doesn't throw if the JSON field has an unexpected type. + */ + @JsonProperty("description") @ExcludeMissing fun _description(): JsonField = description + /** * Returns the raw JSON value of [exampleRunIds]. * @@ -311,6 +331,7 @@ private constructor( private var id: JsonField = JsonMissing.of() private var commitHash: JsonField = JsonMissing.of() private var createdAt: JsonField = JsonMissing.of() + private var description: JsonField = JsonMissing.of() private var exampleRunIds: JsonField>? = null private var fullName: JsonField = JsonMissing.of() private var manifest: JsonValue = JsonMissing.of() @@ -328,6 +349,7 @@ private constructor( id = commitWithLookups.id commitHash = commitWithLookups.commitHash createdAt = commitWithLookups.createdAt + description = commitWithLookups.description exampleRunIds = commitWithLookups.exampleRunIds.map { it.toMutableList() } fullName = commitWithLookups.fullName manifest = commitWithLookups.manifest @@ -376,6 +398,18 @@ private constructor( */ fun createdAt(createdAt: JsonField) = apply { this.createdAt = createdAt } + /** Optional human-readable description for the commit */ + fun description(description: String) = description(JsonField.of(description)) + + /** + * Sets [Builder.description] to an arbitrary JSON value. + * + * You should usually call [Builder.description] with a well-typed [String] value instead. + * This method is primarily for setting the field to an undocumented or not yet supported + * value. + */ + fun description(description: JsonField) = apply { this.description = description } + /** Example run IDs associated with the commit */ fun exampleRunIds(exampleRunIds: List) = exampleRunIds(JsonField.of(exampleRunIds)) @@ -543,6 +577,7 @@ private constructor( id, commitHash, createdAt, + description, (exampleRunIds ?: JsonMissing.of()).map { it.toImmutable() }, fullName, manifest, @@ -567,6 +602,7 @@ private constructor( id() commitHash() createdAt() + description() exampleRunIds() fullName() manifestSha() @@ -597,6 +633,7 @@ private constructor( (if (id.asKnown().isPresent) 1 else 0) + (if (commitHash.asKnown().isPresent) 1 else 0) + (if (createdAt.asKnown().isPresent) 1 else 0) + + (if (description.asKnown().isPresent) 1 else 0) + (exampleRunIds.asKnown().getOrNull()?.size ?: 0) + (if (fullName.asKnown().isPresent) 1 else 0) + (manifestSha.asKnown().getOrNull()?.size ?: 0) + @@ -616,6 +653,7 @@ private constructor( id == other.id && commitHash == other.commitHash && createdAt == other.createdAt && + description == other.description && exampleRunIds == other.exampleRunIds && fullName == other.fullName && manifest == other.manifest && @@ -634,6 +672,7 @@ private constructor( id, commitHash, createdAt, + description, exampleRunIds, fullName, manifest, @@ -651,5 +690,5 @@ private constructor( override fun hashCode(): Int = hashCode override fun toString() = - "CommitWithLookups{id=$id, commitHash=$commitHash, createdAt=$createdAt, exampleRunIds=$exampleRunIds, fullName=$fullName, manifest=$manifest, manifestSha=$manifestSha, numDownloads=$numDownloads, numViews=$numViews, parentCommitHash=$parentCommitHash, parentId=$parentId, repoId=$repoId, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" + "CommitWithLookups{id=$id, commitHash=$commitHash, createdAt=$createdAt, description=$description, exampleRunIds=$exampleRunIds, fullName=$fullName, manifest=$manifest, manifestSha=$manifestSha, numDownloads=$numDownloads, numViews=$numViews, parentCommitHash=$parentCommitHash, parentId=$parentId, repoId=$repoId, updatedAt=$updatedAt, additionalProperties=$additionalProperties}" } diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitCreateParamsTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitCreateParamsTest.kt index 3d5254306..e0a3b527e 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitCreateParamsTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitCreateParamsTest.kt @@ -13,6 +13,7 @@ internal class CommitCreateParamsTest { CommitCreateParams.builder() .owner("owner") .repo("repo") + .description("description") .manifest(JsonValue.from(mapOf())) .parentCommit("parent_commit") .skipWebhooks(JsonValue.from(mapOf())) @@ -35,6 +36,7 @@ internal class CommitCreateParamsTest { CommitCreateParams.builder() .owner("owner") .repo("repo") + .description("description") .manifest(JsonValue.from(mapOf())) .parentCommit("parent_commit") .skipWebhooks(JsonValue.from(mapOf())) @@ -42,6 +44,7 @@ internal class CommitCreateParamsTest { val body = params._body() + assertThat(body.description()).contains("description") assertThat(body._manifest()).isEqualTo(JsonValue.from(mapOf())) assertThat(body.parentCommit()).contains("parent_commit") assertThat(body._skipWebhooks()).isEqualTo(JsonValue.from(mapOf())) diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitCreateResponseTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitCreateResponseTest.kt index 13641b6c4..2abf9f9df 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitCreateResponseTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitCreateResponseTest.kt @@ -20,6 +20,7 @@ internal class CommitCreateResponseTest { .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .commitHash("commit_hash") .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") .addExampleRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .fullName("full_name") .manifest(JsonValue.from(mapOf())) @@ -40,6 +41,7 @@ internal class CommitCreateResponseTest { .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .commitHash("commit_hash") .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") .addExampleRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .fullName("full_name") .manifest(JsonValue.from(mapOf())) @@ -64,6 +66,7 @@ internal class CommitCreateResponseTest { .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .commitHash("commit_hash") .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") .addExampleRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .fullName("full_name") .manifest(JsonValue.from(mapOf())) diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitListPageResponseTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitListPageResponseTest.kt index 8e62d143e..d949c68b5 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitListPageResponseTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitListPageResponseTest.kt @@ -21,6 +21,7 @@ internal class CommitListPageResponseTest { .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .commitHash("commit_hash") .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") .addExampleRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .fullName("full_name") .manifest(JsonValue.from(mapOf())) @@ -42,6 +43,7 @@ internal class CommitListPageResponseTest { .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .commitHash("commit_hash") .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") .addExampleRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .fullName("full_name") .manifest(JsonValue.from(mapOf())) @@ -67,6 +69,7 @@ internal class CommitListPageResponseTest { .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .commitHash("commit_hash") .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") .addExampleRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .fullName("full_name") .manifest(JsonValue.from(mapOf())) diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponseTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponseTest.kt index 1e441a4aa..c608ccfab 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponseTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitRetrieveResponseTest.kt @@ -16,6 +16,7 @@ internal class CommitRetrieveResponseTest { val commitRetrieveResponse = CommitRetrieveResponse.builder() .commitHash("commit_hash") + .description("description") .addExample( CommitRetrieveResponse.Example.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") @@ -32,6 +33,7 @@ internal class CommitRetrieveResponseTest { .build() assertThat(commitRetrieveResponse.commitHash()).contains("commit_hash") + assertThat(commitRetrieveResponse.description()).contains("description") assertThat(commitRetrieveResponse.examples().getOrNull()) .containsExactly( CommitRetrieveResponse.Example.builder() @@ -56,6 +58,7 @@ internal class CommitRetrieveResponseTest { val commitRetrieveResponse = CommitRetrieveResponse.builder() .commitHash("commit_hash") + .description("description") .addExample( CommitRetrieveResponse.Example.builder() .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitWithLookupsTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitWithLookupsTest.kt index d8a9a955d..604dfe4b2 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitWithLookupsTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/commits/CommitWithLookupsTest.kt @@ -19,6 +19,7 @@ internal class CommitWithLookupsTest { .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .commitHash("commit_hash") .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") .addExampleRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .fullName("full_name") .manifest(JsonValue.from(mapOf())) @@ -35,6 +36,7 @@ internal class CommitWithLookupsTest { assertThat(commitWithLookups.commitHash()).contains("commit_hash") assertThat(commitWithLookups.createdAt()) .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + assertThat(commitWithLookups.description()).contains("description") assertThat(commitWithLookups.exampleRunIds().getOrNull()) .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(commitWithLookups.fullName()).contains("full_name") @@ -57,6 +59,7 @@ internal class CommitWithLookupsTest { .id("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .commitHash("commit_hash") .createdAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) + .description("description") .addExampleRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .fullName("full_name") .manifest(JsonValue.from(mapOf())) diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/CommitServiceAsyncTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/CommitServiceAsyncTest.kt index 369f0c614..a7505526e 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/CommitServiceAsyncTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/async/CommitServiceAsyncTest.kt @@ -28,6 +28,7 @@ internal class CommitServiceAsyncTest { CommitCreateParams.builder() .owner("owner") .repo("repo") + .description("description") .manifest(JsonValue.from(mapOf())) .parentCommit("parent_commit") .skipWebhooks(JsonValue.from(mapOf())) diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/CommitServiceTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/CommitServiceTest.kt index 34b77f808..4e74aa247 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/CommitServiceTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/services/blocking/CommitServiceTest.kt @@ -28,6 +28,7 @@ internal class CommitServiceTest { CommitCreateParams.builder() .owner("owner") .repo("repo") + .description("description") .manifest(JsonValue.from(mapOf())) .parentCommit("parent_commit") .skipWebhooks(JsonValue.from(mapOf())) From 9182ef84e304c602899c73b6865473d3ade4953f Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Mon, 30 Mar 2026 22:13:42 +0000 Subject: [PATCH 29/35] feat(api): api update --- .stats.yml | 4 +- .../RunSchemaWithAnnotationQueueInfo.kt | 117 +++++++++++------- .../RunSchemaWithAnnotationQueueInfoTest.kt | 14 ++- 3 files changed, 80 insertions(+), 55 deletions(-) diff --git a/.stats.yml b/.stats.yml index 9dc077b9c..19fccdd09 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 103 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-4d7b0427f9ed66e112fcc2f2a3a91e7f2c8113eb6386910c48b52ef7a605b282.yml -openapi_spec_hash: 601517cba6d1a4f06c494f42f11e3f96 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-eb465fc8d3cc8b7ba8c49bc30a90458a2fe02b4d5612c035eec9fb398246f107.yml +openapi_spec_hash: 6bd1e295b4d88bc902572b946f3706b6 config_hash: c217b34d458f1b65f260715693d447f9 diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfo.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfo.kt index d1d7f66ce..e61af0f5e 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfo.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfo.kt @@ -37,7 +37,7 @@ private constructor( private val traceId: JsonField, private val addedAt: JsonField, private val childRunIds: JsonField>, - private val completedCount: JsonField, + private val completedBy: JsonField>, private val completionCost: JsonField, private val completionCostDetails: JsonField, private val completionTokenDetails: JsonField, @@ -72,7 +72,7 @@ private constructor( private val promptTokens: JsonField, private val referenceDatasetId: JsonField, private val referenceExampleId: JsonField, - private val reservationCount: JsonField, + private val reservedBy: JsonField>, private val s3Urls: JsonField, private val serialized: JsonField, private val shareToken: JsonField, @@ -113,9 +113,9 @@ private constructor( @JsonProperty("child_run_ids") @ExcludeMissing childRunIds: JsonField> = JsonMissing.of(), - @JsonProperty("completed_count") + @JsonProperty("completed_by") @ExcludeMissing - completedCount: JsonField = JsonMissing.of(), + completedBy: JsonField> = JsonMissing.of(), @JsonProperty("completion_cost") @ExcludeMissing completionCost: JsonField = JsonMissing.of(), @@ -208,9 +208,9 @@ private constructor( @JsonProperty("reference_example_id") @ExcludeMissing referenceExampleId: JsonField = JsonMissing.of(), - @JsonProperty("reservation_count") + @JsonProperty("reserved_by") @ExcludeMissing - reservationCount: JsonField = JsonMissing.of(), + reservedBy: JsonField> = JsonMissing.of(), @JsonProperty("s3_urls") @ExcludeMissing s3Urls: JsonField = JsonMissing.of(), @JsonProperty("serialized") @ExcludeMissing @@ -255,7 +255,7 @@ private constructor( traceId, addedAt, childRunIds, - completedCount, + completedBy, completionCost, completionCostDetails, completionTokenDetails, @@ -290,7 +290,7 @@ private constructor( promptTokens, referenceDatasetId, referenceExampleId, - reservationCount, + reservedBy, s3Urls, serialized, shareToken, @@ -380,7 +380,7 @@ private constructor( * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun completedCount(): Optional = completedCount.getOptional("completed_count") + fun completedBy(): Optional> = completedBy.getOptional("completed_by") /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -599,7 +599,7 @@ private constructor( * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the * server responded with an unexpected value). */ - fun reservationCount(): Optional = reservationCount.getOptional("reservation_count") + fun reservedBy(): Optional> = reservedBy.getOptional("reserved_by") /** * @throws LangChainInvalidDataException if the JSON field has an unexpected type (e.g. if the @@ -770,13 +770,13 @@ private constructor( fun _childRunIds(): JsonField> = childRunIds /** - * Returns the raw JSON value of [completedCount]. + * Returns the raw JSON value of [completedBy]. * - * Unlike [completedCount], this method doesn't throw if the JSON field has an unexpected type. + * Unlike [completedBy], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("completed_count") + @JsonProperty("completed_by") @ExcludeMissing - fun _completedCount(): JsonField = completedCount + fun _completedBy(): JsonField> = completedBy /** * Returns the raw JSON value of [completionCost]. @@ -1075,14 +1075,13 @@ private constructor( fun _referenceExampleId(): JsonField = referenceExampleId /** - * Returns the raw JSON value of [reservationCount]. + * Returns the raw JSON value of [reservedBy]. * - * Unlike [reservationCount], this method doesn't throw if the JSON field has an unexpected - * type. + * Unlike [reservedBy], this method doesn't throw if the JSON field has an unexpected type. */ - @JsonProperty("reservation_count") + @JsonProperty("reserved_by") @ExcludeMissing - fun _reservationCount(): JsonField = reservationCount + fun _reservedBy(): JsonField> = reservedBy /** * Returns the raw JSON value of [s3Urls]. @@ -1245,7 +1244,7 @@ private constructor( private var traceId: JsonField? = null private var addedAt: JsonField = JsonMissing.of() private var childRunIds: JsonField>? = null - private var completedCount: JsonField = JsonMissing.of() + private var completedBy: JsonField>? = null private var completionCost: JsonField = JsonMissing.of() private var completionCostDetails: JsonField = JsonMissing.of() private var completionTokenDetails: JsonField = JsonMissing.of() @@ -1280,7 +1279,7 @@ private constructor( private var promptTokens: JsonField = JsonMissing.of() private var referenceDatasetId: JsonField = JsonMissing.of() private var referenceExampleId: JsonField = JsonMissing.of() - private var reservationCount: JsonField = JsonMissing.of() + private var reservedBy: JsonField>? = null private var s3Urls: JsonField = JsonMissing.of() private var serialized: JsonField = JsonMissing.of() private var shareToken: JsonField = JsonMissing.of() @@ -1312,7 +1311,8 @@ private constructor( addedAt = runSchemaWithAnnotationQueueInfo.addedAt childRunIds = runSchemaWithAnnotationQueueInfo.childRunIds.map { it.toMutableList() } - completedCount = runSchemaWithAnnotationQueueInfo.completedCount + completedBy = + runSchemaWithAnnotationQueueInfo.completedBy.map { it.toMutableList() } completionCost = runSchemaWithAnnotationQueueInfo.completionCost completionCostDetails = runSchemaWithAnnotationQueueInfo.completionCostDetails completionTokenDetails = runSchemaWithAnnotationQueueInfo.completionTokenDetails @@ -1349,7 +1349,7 @@ private constructor( promptTokens = runSchemaWithAnnotationQueueInfo.promptTokens referenceDatasetId = runSchemaWithAnnotationQueueInfo.referenceDatasetId referenceExampleId = runSchemaWithAnnotationQueueInfo.referenceExampleId - reservationCount = runSchemaWithAnnotationQueueInfo.reservationCount + reservedBy = runSchemaWithAnnotationQueueInfo.reservedBy.map { it.toMutableList() } s3Urls = runSchemaWithAnnotationQueueInfo.s3Urls serialized = runSchemaWithAnnotationQueueInfo.serialized shareToken = runSchemaWithAnnotationQueueInfo.shareToken @@ -1505,17 +1505,29 @@ private constructor( } } - fun completedCount(completedCount: Long) = completedCount(JsonField.of(completedCount)) + fun completedBy(completedBy: List) = completedBy(JsonField.of(completedBy)) /** - * Sets [Builder.completedCount] to an arbitrary JSON value. + * Sets [Builder.completedBy] to an arbitrary JSON value. * - * You should usually call [Builder.completedCount] with a well-typed [Long] value instead. - * This method is primarily for setting the field to an undocumented or not yet supported - * value. + * You should usually call [Builder.completedBy] with a well-typed `List` value + * instead. This method is primarily for setting the field to an undocumented or not yet + * supported value. */ - fun completedCount(completedCount: JsonField) = apply { - this.completedCount = completedCount + fun completedBy(completedBy: JsonField>) = apply { + this.completedBy = completedBy.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [Builder.completedBy]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addCompletedBy(completedBy: String) = apply { + this.completedBy = + (this.completedBy ?: JsonField.of(mutableListOf())).also { + checkKnown("completedBy", it).add(completedBy) + } } fun completionCost(completionCost: String?) = @@ -2134,18 +2146,29 @@ private constructor( this.referenceExampleId = referenceExampleId } - fun reservationCount(reservationCount: Long) = - reservationCount(JsonField.of(reservationCount)) + fun reservedBy(reservedBy: List) = reservedBy(JsonField.of(reservedBy)) /** - * Sets [Builder.reservationCount] to an arbitrary JSON value. + * Sets [Builder.reservedBy] to an arbitrary JSON value. * - * You should usually call [Builder.reservationCount] with a well-typed [Long] value + * You should usually call [Builder.reservedBy] with a well-typed `List` value * instead. This method is primarily for setting the field to an undocumented or not yet * supported value. */ - fun reservationCount(reservationCount: JsonField) = apply { - this.reservationCount = reservationCount + fun reservedBy(reservedBy: JsonField>) = apply { + this.reservedBy = reservedBy.map { it.toMutableList() } + } + + /** + * Adds a single [String] to [Builder.reservedBy]. + * + * @throws IllegalStateException if the field was previously set to a non-list. + */ + fun addReservedBy(reservedBy: String) = apply { + this.reservedBy = + (this.reservedBy ?: JsonField.of(mutableListOf())).also { + checkKnown("reservedBy", it).add(reservedBy) + } } fun s3Urls(s3Urls: S3Urls?) = s3Urls(JsonField.ofNullable(s3Urls)) @@ -2419,7 +2442,7 @@ private constructor( checkRequired("traceId", traceId), addedAt, (childRunIds ?: JsonMissing.of()).map { it.toImmutable() }, - completedCount, + (completedBy ?: JsonMissing.of()).map { it.toImmutable() }, completionCost, completionCostDetails, completionTokenDetails, @@ -2454,7 +2477,7 @@ private constructor( promptTokens, referenceDatasetId, referenceExampleId, - reservationCount, + (reservedBy ?: JsonMissing.of()).map { it.toImmutable() }, s3Urls, serialized, shareToken, @@ -2491,7 +2514,7 @@ private constructor( traceId() addedAt() childRunIds() - completedCount() + completedBy() completionCost() completionCostDetails().ifPresent { it.validate() } completionTokenDetails().ifPresent { it.validate() } @@ -2526,7 +2549,7 @@ private constructor( promptTokens() referenceDatasetId() referenceExampleId() - reservationCount() + reservedBy() s3Urls().ifPresent { it.validate() } serialized().ifPresent { it.validate() } shareToken() @@ -2570,7 +2593,7 @@ private constructor( (if (traceId.asKnown().isPresent) 1 else 0) + (if (addedAt.asKnown().isPresent) 1 else 0) + (childRunIds.asKnown().getOrNull()?.size ?: 0) + - (if (completedCount.asKnown().isPresent) 1 else 0) + + (completedBy.asKnown().getOrNull()?.size ?: 0) + (if (completionCost.asKnown().isPresent) 1 else 0) + (completionCostDetails.asKnown().getOrNull()?.validity() ?: 0) + (completionTokenDetails.asKnown().getOrNull()?.validity() ?: 0) + @@ -2605,7 +2628,7 @@ private constructor( (if (promptTokens.asKnown().isPresent) 1 else 0) + (if (referenceDatasetId.asKnown().isPresent) 1 else 0) + (if (referenceExampleId.asKnown().isPresent) 1 else 0) + - (if (reservationCount.asKnown().isPresent) 1 else 0) + + (reservedBy.asKnown().getOrNull()?.size ?: 0) + (s3Urls.asKnown().getOrNull()?.validity() ?: 0) + (serialized.asKnown().getOrNull()?.validity() ?: 0) + (if (shareToken.asKnown().isPresent) 1 else 0) + @@ -4163,7 +4186,7 @@ private constructor( traceId == other.traceId && addedAt == other.addedAt && childRunIds == other.childRunIds && - completedCount == other.completedCount && + completedBy == other.completedBy && completionCost == other.completionCost && completionCostDetails == other.completionCostDetails && completionTokenDetails == other.completionTokenDetails && @@ -4198,7 +4221,7 @@ private constructor( promptTokens == other.promptTokens && referenceDatasetId == other.referenceDatasetId && referenceExampleId == other.referenceExampleId && - reservationCount == other.reservationCount && + reservedBy == other.reservedBy && s3Urls == other.s3Urls && serialized == other.serialized && shareToken == other.shareToken && @@ -4229,7 +4252,7 @@ private constructor( traceId, addedAt, childRunIds, - completedCount, + completedBy, completionCost, completionCostDetails, completionTokenDetails, @@ -4264,7 +4287,7 @@ private constructor( promptTokens, referenceDatasetId, referenceExampleId, - reservationCount, + reservedBy, s3Urls, serialized, shareToken, @@ -4286,5 +4309,5 @@ private constructor( override fun hashCode(): Int = hashCode override fun toString() = - "RunSchemaWithAnnotationQueueInfo{id=$id, appPath=$appPath, dottedOrder=$dottedOrder, name=$name, queueRunId=$queueRunId, runType=$runType, sessionId=$sessionId, status=$status, traceId=$traceId, addedAt=$addedAt, childRunIds=$childRunIds, completedCount=$completedCount, completionCost=$completionCost, completionCostDetails=$completionCostDetails, completionTokenDetails=$completionTokenDetails, completionTokens=$completionTokens, directChildRunIds=$directChildRunIds, effectiveAddedAt=$effectiveAddedAt, endTime=$endTime, error=$error, events=$events, executionOrder=$executionOrder, extra=$extra, feedbackStats=$feedbackStats, firstTokenTime=$firstTokenTime, inDataset=$inDataset, inputs=$inputs, inputsPreview=$inputsPreview, inputsS3Urls=$inputsS3Urls, lastQueuedAt=$lastQueuedAt, lastReviewedTime=$lastReviewedTime, manifestId=$manifestId, manifestS3Id=$manifestS3Id, messages=$messages, outputs=$outputs, outputsPreview=$outputsPreview, outputsS3Urls=$outputsS3Urls, parentRunId=$parentRunId, parentRunIds=$parentRunIds, priceModelId=$priceModelId, promptCost=$promptCost, promptCostDetails=$promptCostDetails, promptTokenDetails=$promptTokenDetails, promptTokens=$promptTokens, referenceDatasetId=$referenceDatasetId, referenceExampleId=$referenceExampleId, reservationCount=$reservationCount, s3Urls=$s3Urls, serialized=$serialized, shareToken=$shareToken, startTime=$startTime, tags=$tags, threadId=$threadId, totalCost=$totalCost, totalTokens=$totalTokens, traceFirstReceivedAt=$traceFirstReceivedAt, traceMaxStartTime=$traceMaxStartTime, traceMinStartTime=$traceMinStartTime, traceTier=$traceTier, traceUpgrade=$traceUpgrade, ttlSeconds=$ttlSeconds, additionalProperties=$additionalProperties}" + "RunSchemaWithAnnotationQueueInfo{id=$id, appPath=$appPath, dottedOrder=$dottedOrder, name=$name, queueRunId=$queueRunId, runType=$runType, sessionId=$sessionId, status=$status, traceId=$traceId, addedAt=$addedAt, childRunIds=$childRunIds, completedBy=$completedBy, completionCost=$completionCost, completionCostDetails=$completionCostDetails, completionTokenDetails=$completionTokenDetails, completionTokens=$completionTokens, directChildRunIds=$directChildRunIds, effectiveAddedAt=$effectiveAddedAt, endTime=$endTime, error=$error, events=$events, executionOrder=$executionOrder, extra=$extra, feedbackStats=$feedbackStats, firstTokenTime=$firstTokenTime, inDataset=$inDataset, inputs=$inputs, inputsPreview=$inputsPreview, inputsS3Urls=$inputsS3Urls, lastQueuedAt=$lastQueuedAt, lastReviewedTime=$lastReviewedTime, manifestId=$manifestId, manifestS3Id=$manifestS3Id, messages=$messages, outputs=$outputs, outputsPreview=$outputsPreview, outputsS3Urls=$outputsS3Urls, parentRunId=$parentRunId, parentRunIds=$parentRunIds, priceModelId=$priceModelId, promptCost=$promptCost, promptCostDetails=$promptCostDetails, promptTokenDetails=$promptTokenDetails, promptTokens=$promptTokens, referenceDatasetId=$referenceDatasetId, referenceExampleId=$referenceExampleId, reservedBy=$reservedBy, s3Urls=$s3Urls, serialized=$serialized, shareToken=$shareToken, startTime=$startTime, tags=$tags, threadId=$threadId, totalCost=$totalCost, totalTokens=$totalTokens, traceFirstReceivedAt=$traceFirstReceivedAt, traceMaxStartTime=$traceMaxStartTime, traceMinStartTime=$traceMinStartTime, traceTier=$traceTier, traceUpgrade=$traceUpgrade, ttlSeconds=$ttlSeconds, additionalProperties=$additionalProperties}" } diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfoTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfoTest.kt index 6137258f1..2d839c2fc 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfoTest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/models/annotationqueues/RunSchemaWithAnnotationQueueInfoTest.kt @@ -28,7 +28,7 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .traceId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .addedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .addChildRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .completedCount(0L) + .addCompletedBy("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .completionCost("completion_cost") .completionCostDetails( RunSchemaWithAnnotationQueueInfo.CompletionCostDetails.builder() @@ -111,7 +111,7 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .promptTokens(0L) .referenceDatasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .referenceExampleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .reservationCount(0L) + .addReservedBy("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .s3Urls( RunSchemaWithAnnotationQueueInfo.S3Urls.builder() .putAdditionalProperty("foo", JsonValue.from("bar")) @@ -153,7 +153,8 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .contains(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) assertThat(runSchemaWithAnnotationQueueInfo.childRunIds().getOrNull()) .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(runSchemaWithAnnotationQueueInfo.completedCount()).contains(0L) + assertThat(runSchemaWithAnnotationQueueInfo.completedBy().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(runSchemaWithAnnotationQueueInfo.completionCost()).contains("completion_cost") assertThat(runSchemaWithAnnotationQueueInfo.completionCostDetails()) .contains( @@ -261,7 +262,8 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(runSchemaWithAnnotationQueueInfo.referenceExampleId()) .contains("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - assertThat(runSchemaWithAnnotationQueueInfo.reservationCount()).contains(0L) + assertThat(runSchemaWithAnnotationQueueInfo.reservedBy().getOrNull()) + .containsExactly("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") assertThat(runSchemaWithAnnotationQueueInfo.s3Urls()) .contains( RunSchemaWithAnnotationQueueInfo.S3Urls.builder() @@ -310,7 +312,7 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .traceId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .addedAt(OffsetDateTime.parse("2019-12-27T18:11:19.117Z")) .addChildRunId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .completedCount(0L) + .addCompletedBy("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .completionCost("completion_cost") .completionCostDetails( RunSchemaWithAnnotationQueueInfo.CompletionCostDetails.builder() @@ -393,7 +395,7 @@ internal class RunSchemaWithAnnotationQueueInfoTest { .promptTokens(0L) .referenceDatasetId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .referenceExampleId("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") - .reservationCount(0L) + .addReservedBy("182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e") .s3Urls( RunSchemaWithAnnotationQueueInfo.S3Urls.builder() .putAdditionalProperty("foo", JsonValue.from("bar")) From dfe092c51ab27c3131b81785321664a75d584764 Mon Sep 17 00:00:00 2001 From: John Kennedy <65985482+jkennedyvz@users.noreply.github.com> Date: Mon, 30 Mar 2026 17:52:49 -0700 Subject: [PATCH 30/35] =?UTF-8?q?fix:=20patch=20security=20alerts=20?= =?UTF-8?q?=E2=80=94=20bump=20Jackson=20and=20constrain=20vulnerable=20tra?= =?UTF-8?q?nsitive=20deps=20(#119)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps Jackson 2.18.2→2.18.6 in published api deps and adds version constraints for vulnerable transitive dependencies in test and example scopes (Tomcat 9.0.115, Jetty 9.4.57, logback 1.2.13, commons-fileupload 1.6.0, commons-io 2.14.0, json-smart 2.4.9, snakeyaml 1.31, spring-web 5.3.34). Addresses alerts: #75 (jackson-core), #82/#81/#80/#79/#78/#72/#70/#69 /#68/#66/#65/#60/#59/#54/#52/#51/#48/#46/#45/#44/#43/#35/#34/#29/#31 (tomcat/jetty/logback/commons). Co-authored-by: Claude Sonnet 4.6 --- langsmith-java-core/build.gradle.kts | 30 ++++++++++++++++++++----- langsmith-java-example/build.gradle.kts | 20 +++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/langsmith-java-core/build.gradle.kts b/langsmith-java-core/build.gradle.kts index 0252bfe75..9adbe725b 100644 --- a/langsmith-java-core/build.gradle.kts +++ b/langsmith-java-core/build.gradle.kts @@ -35,14 +35,14 @@ configurations.all { } dependencies { - api("com.fasterxml.jackson.core:jackson-core:2.18.2") - api("com.fasterxml.jackson.core:jackson-databind:2.18.2") + api("com.fasterxml.jackson.core:jackson-core:2.18.6") + api("com.fasterxml.jackson.core:jackson-databind:2.18.6") api("com.google.errorprone:error_prone_annotations:2.33.0") - implementation("com.fasterxml.jackson.core:jackson-annotations:2.18.2") - implementation("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.18.2") - implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.18.2") - implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.18.2") + implementation("com.fasterxml.jackson.core:jackson-annotations:2.18.6") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.18.6") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.18.6") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.18.6") implementation("org.apache.httpcomponents.core5:httpcore5:5.2.4") implementation("org.apache.httpcomponents.client5:httpclient5:5.3.1") @@ -66,6 +66,24 @@ dependencies { compileOnly("com.anthropic:anthropic-java:2.18.0") testImplementation("com.anthropic:anthropic-java:2.18.0") + // Security: constrain vulnerable transitive test dependencies (from wiremock-jre8). + // These constraints apply to the test scope only and do not affect published artifacts. + constraints { + // CVE-2024-13009, CVE-2025-5115, CVE-2024-22201, CVE-2023-36478 + testImplementation("org.eclipse.jetty:jetty-server") { version { require("9.4.57.v20241219") } } + testImplementation("org.eclipse.jetty.http2:http2-common") { version { require("9.4.57.v20241219") } } + testImplementation("org.eclipse.jetty.http2:http2-hpack") { version { require("9.4.57.v20241219") } } + // CVE-2023-6481, CVE-2023-6378 + testImplementation("ch.qos.logback:logback-core") { version { require("1.2.13") } } + testImplementation("ch.qos.logback:logback-classic") { version { require("1.2.13") } } + // CVE-2025-48976, CVE-2023-24998 + testImplementation("commons-fileupload:commons-fileupload") { version { require("1.6.0") } } + // CVE-2024-47554 + testImplementation("commons-io:commons-io") { version { require("2.14.0") } } + // CVE-2023-1370 + testImplementation("net.minidev:json-smart") { version { require("2.4.9") } } + } + testImplementation(kotlin("test")) // Simple logging for tests only testImplementation("org.slf4j:slf4j-simple:2.0.17") diff --git a/langsmith-java-example/build.gradle.kts b/langsmith-java-example/build.gradle.kts index a7e4cf4ac..b7e8f9bc6 100644 --- a/langsmith-java-example/build.gradle.kts +++ b/langsmith-java-example/build.gradle.kts @@ -26,6 +26,26 @@ dependencies { implementation(platform("org.springframework.boot:spring-boot-dependencies:2.7.18")) implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter") + + // Security: constrain vulnerable transitive dependencies from Spring Boot 2.7.18. + // Spring Boot 2.7.x is EOL; these constraints override the managed versions in-place. + // None of these affect published artifacts (this is a non-published example module). + constraints { + // CVE-2025-24813 (CRITICAL), CVE-2026-24734, CVE-2025-55752, CVE-2025-53506, + // CVE-2025-52520, CVE-2025-48989, CVE-2025-48988, CVE-2024-56337, CVE-2024-50379, CVE-2024-34750 + // Remove this constraint when upgrading to Spring Boot 3.x (which manages Tomcat 10+). + implementation("org.apache.tomcat.embed:tomcat-embed-core") { version { require("9.0.115") } } + implementation("org.apache.tomcat.embed:tomcat-embed-websocket") { version { require("9.0.115") } } + // CVE-2024-22243, CVE-2024-22259, CVE-2024-22262 + // Note: CVE-2016-1000027 (CRITICAL) requires spring-web 6.0.0 — needs Spring Boot 3.x upgrade. + implementation("org.springframework:spring-web") { version { require("5.3.34") } } + implementation("org.springframework:spring-webmvc") { version { require("5.3.34") } } + // CVE-2023-6481, CVE-2023-6378 + implementation("ch.qos.logback:logback-core") { version { require("1.2.13") } } + implementation("ch.qos.logback:logback-classic") { version { require("1.2.13") } } + // CVE-2022-25857 (note: CVE-2022-1471 requires snakeyaml 2.0 which is incompatible with Spring Boot 2.7.x) + implementation("org.yaml:snakeyaml") { version { require("1.31") } } + } } tasks.withType().configureEach { From 33366fbe35e308a887b5a9d2353007b6de19f70c Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 31 Mar 2026 03:13:38 +0000 Subject: [PATCH 31/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index 19fccdd09..9e37cfcb4 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 103 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-eb465fc8d3cc8b7ba8c49bc30a90458a2fe02b4d5612c035eec9fb398246f107.yml -openapi_spec_hash: 6bd1e295b4d88bc902572b946f3706b6 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-0d8988252ebbab57e837f2244ab60f9f9619b40c0e6076f473cae774e25b79ab.yml +openapi_spec_hash: 28f0aa62583efe5ffc3d37c70f552572 config_hash: c217b34d458f1b65f260715693d447f9 From 32b3feebebabd97abe67b7b7efba9f76cedbb660 Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 31 Mar 2026 05:13:40 +0000 Subject: [PATCH 32/35] codegen metadata --- .stats.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.stats.yml b/.stats.yml index 9e37cfcb4..aa8a8810f 100644 --- a/.stats.yml +++ b/.stats.yml @@ -1,4 +1,4 @@ configured_endpoints: 103 -openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-0d8988252ebbab57e837f2244ab60f9f9619b40c0e6076f473cae774e25b79ab.yml -openapi_spec_hash: 28f0aa62583efe5ffc3d37c70f552572 +openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/langsmith%2Flangsmith-api-9b9d7777d6a9aab968ca5e1c90d7dda257754fd6542e44483976ad91d2841499.yml +openapi_spec_hash: 83f2642863f2042a3c091ef10d3207e0 config_hash: c217b34d458f1b65f260715693d447f9 From 0217521b852c70dba4795b145b3eb7b16fd2d10f Mon Sep 17 00:00:00 2001 From: Jacob Lee Date: Tue, 31 Mar 2026 10:13:54 -0700 Subject: [PATCH 33/35] feat: Adds support for tracing streams with traceable (#117) * Adds support for tracing streams with traceable * Polish * Make stream tracing opt-in * Rework to use a passthrough instead of a proxy * Record stream cancellations as errors * Feedback * Format and add to AGENTS.md --- AGENTS.md | 22 +- .../langchain/smith/tracing/TraceProcessIO.kt | 47 ++++- .../com/langchain/smith/tracing/Traceable.kt | 77 +++++++ .../smith/tracing/TraceableStreamingTest.kt | 196 ++++++++++++++++++ 4 files changed, 336 insertions(+), 6 deletions(-) create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableStreamingTest.kt diff --git a/AGENTS.md b/AGENTS.md index a17ffbf54..d4228db47 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -91,6 +91,25 @@ override fun toString(): String = "}" ``` +### Prefer extension functions over type casts + +When adding behavior to a type you don't own, use a `private` extension function instead of casting to an implementation type: + +```kotlin +// Good — extension function, no cast needed +private fun Stream<*>.withErrorTracking( + errorRef: AtomicReference, + exhaustedRef: AtomicBoolean, +): Stream { ... } + +val instrumented = result.withErrorTracking(iterationError, streamExhausted) + +// Bad — casting to implementation type +val instrumented = wrapStreamWithErrorCapture(result, iterationError, streamExhausted) +// or worse: +(runs as? RunServiceImpl)?.flush() +``` + ### Use `partition` instead of double `filter` ```kotlin @@ -211,7 +230,7 @@ Tests skip gracefully via `assumeTrue` if keys are missing. ## Code style - `toString()` should be single-line, following the `ClassName{field=value, field=value}` convention used by the rest of the SDK. -- Avoid `@Suppress("UNCHECKED_CAST")` — restructure code to use safe patterns (`as? String`, `is Map<*, *>` with `entries.associate`, etc). +- Avoid `@Suppress("UNCHECKED_CAST")` — restructure code to use safe patterns (`as? String`, `is Map<*, *>` with `entries.associate`, etc). When unavoidable (e.g. generic type erasure after an `is` check), add a comment explaining why the cast is safe. - Use named arguments for constructor/function calls with 2+ parameters, especially when types could be confused: ```kotlin // Good @@ -224,6 +243,7 @@ Tests skip gracefully via `assumeTrue` if keys are missing. // Bad — positional args are ambiguous PromptMessage(PromptMessage.Role.HUMAN, template, templateFormat = templateFormat) ``` +- Name functions from the caller's perspective — describe what the caller gets, not what the function does internally. Prefer `stream.withErrorTracking()` over `wrapStreamWithErrorCapture(stream)`. - When an `Optional` has a fallback default, use `orElse(default)` directly instead of `orElse(null) ?: default`: ```kotlin // Good — default goes straight into orElse diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt index 4af01a810..beecd5447 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/TraceProcessIO.kt @@ -13,10 +13,12 @@ import java.util.function.Function * - **0-arg** ([traceSupplier]): `Map` (empty map) * - **2-arg** ([traceBiFunction]): `Pair` * - **3-arg** ([traceTriFunction]): `Triple` - * - [PO] — the type passed to `processOutputs`. This is always the raw output type of the traced - * function. + * - [PO] — the type passed to `processOutputs`. For non-streaming functions, this is the raw return + * type. For streaming functions (when [aggregator] is set), this is the **aggregated output + * type** returned by the aggregator — not the stream type itself. * - * When [inputs] is set, it replaces the default input serialization entirely. Same for [outputs]. + * When `processInputs` is set, it replaces the default input serialization entirely. Same for + * `processOutputs`. * * ## Example (Kotlin) * @@ -47,12 +49,32 @@ import java.util.function.Function class TraceProcessIO( processInputs: Function>? = null, processOutputs: Function>? = null, + aggregator: Function, Any?>? = null, ) { // Store erased wrappers so traceable overloads can call these without casts. // erase() converts Function to Function — safe because T erases to Object. internal val inputsFn: Function>? = processInputs?.erase() internal val outputsFn: Function>? = processOutputs?.erase() + /** + * Aggregator for streaming results. Setting this opts into stream tracing. + * + * When set and the traced function returns a [java.util.stream.Stream], `traceable` will: + * 1. Tee the stream via `peek()` to collect elements as the caller iterates + * 2. Register an `onClose()` handler that calls this aggregator with the collected chunks + * 3. Pass the aggregated result through [processOutputs] and record it as run output + * + * The caller gets back a real [java.util.stream.Stream] — no proxy, no type changes. + * + * Without an aggregator, `Stream` return values are treated normally — the run is completed + * immediately on return, same as any other value. + * + * **Lifecycle:** The run is finalized when the stream's `onClose` handler runs. Callers must + * close the stream (via `use {}` in Kotlin or try-with-resources in Java) to ensure the run is + * completed. Abandoned streams will leave runs open. + */ + internal val aggregatorFn: Function, Any?>? = aggregator + companion object { /** Creates a new [Builder]. */ @JvmStatic fun builder() = Builder() @@ -82,6 +104,7 @@ class TraceProcessIO( class Builder internal constructor() { private var processInputs: Function>? = null private var processOutputs: Function>? = null + private var aggregator: Function, Any?>? = null /** Callback to transform the input before it is recorded on the run. */ fun processInputs(processInputs: Function>) = apply { @@ -93,9 +116,23 @@ class TraceProcessIO( this.processOutputs = processOutputs } + /** + * Aggregator for streaming results. Reduces collected chunks into a single output that is + * then passed through [processOutputs]. + */ + fun aggregator(aggregator: Function, Any?>) = apply { + this.aggregator = aggregator + } + /** Builds the [TraceProcessIO]. */ - fun build() = TraceProcessIO(processInputs = processInputs, processOutputs = processOutputs) + fun build() = + TraceProcessIO( + processInputs = processInputs, + processOutputs = processOutputs, + aggregator = aggregator, + ) } - override fun toString(): String = "TraceProcessIO{inputs=$inputsFn, outputs=$outputsFn}" + override fun toString(): String = + "TraceProcessIO{inputs=$inputsFn, outputs=$outputsFn, aggregator=$aggregatorFn}" } diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt index 3a4dcb7e9..2982feccf 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/tracing/Traceable.kt @@ -686,6 +686,54 @@ private fun executeTraced(config: TraceConfig, inputs: Map?, b return CURRENT_RUN.runWith(run) { try { val result = block() + + // If the result is a java.util.stream.Stream and an aggregator is configured, + // instrument it: collect chunks via peek(), finalize the run via onClose(). + val aggregator = config.processTracedIO?.aggregatorFn + if (aggregator != null && result is java.util.stream.Stream<*>) { + val chunks = mutableListOf() + val iterationError = java.util.concurrent.atomic.AtomicReference(null) + val streamExhausted = java.util.concurrent.atomic.AtomicBoolean(false) + val instrumented = + result + .withErrorTracking(iterationError, streamExhausted) + .peek { chunks.add(it) } + .onClose { + try { + // Always try to aggregate whatever chunks we have + var aggregationError: Throwable? = null + if (chunks.isNotEmpty()) { + try { + val output = aggregator.apply(chunks) + run.outputs = + applyProcessOutputs(config, output) + ?: toOutputMap(output) + } catch (e: Throwable) { + aggregationError = e + } + } + + val error = iterationError.get() + run.endTime = nowIso() + if (error != null) { + run.error = error.stackTraceToString() + } else if (!streamExhausted.get()) { + run.error = "Stream cancelled" + } else if (aggregationError != null) { + run.error = aggregationError.stackTraceToString() + } + run.patchRun() + } catch (e: Throwable) { + run.endTime = nowIso() + run.error = e.stackTraceToString() + run.patchRun() + } + } + // Safe: T is Stream, instrumented is Stream — same erasure. + @Suppress("UNCHECKED_CAST") + return@runWith instrumented as T + } + run.endTime = nowIso() run.outputs = applyProcessOutputs(config, result) ?: toOutputMap(result) run.patchRun() @@ -698,3 +746,32 @@ private fun executeTraced(config: TraceConfig, inputs: Map?, b } } } + +/** + * Returns a new [java.util.stream.Stream] that captures exceptions during iteration into [errorRef] + * before rethrowing them. This lets the `onClose` handler record the real error instead of + * attempting aggregation on partial data. + */ +private fun java.util.stream.Stream<*>.withErrorTracking( + errorRef: java.util.concurrent.atomic.AtomicReference, + exhaustedRef: java.util.concurrent.atomic.AtomicBoolean, +): java.util.stream.Stream { + val delegate = this.spliterator() + val capturing = + object : java.util.Spliterator { + override fun tryAdvance(action: java.util.function.Consumer): Boolean = + try { + delegate.tryAdvance(action).also { if (!it) exhaustedRef.set(true) } + } catch (e: Throwable) { + errorRef.compareAndSet(null, e) + throw e + } + + override fun trySplit(): java.util.Spliterator? = null + + override fun estimateSize(): Long = delegate.estimateSize() + + override fun characteristics(): Int = delegate.characteristics() + } + return java.util.stream.StreamSupport.stream(capturing, false).onClose { this.close() } +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableStreamingTest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableStreamingTest.kt new file mode 100644 index 000000000..ff067c4d3 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/tracing/TraceableStreamingTest.kt @@ -0,0 +1,196 @@ +package com.langchain.smith.tracing + +import java.util.stream.Collectors +import java.util.stream.Stream +import org.assertj.core.api.Assertions.assertThat +import org.junit.jupiter.api.Test + +/** Unit tests for streaming support in [traceable]. */ +internal class TraceableStreamingTest { + + private fun parentRun() = RunTree(name = "parent", runType = RunType.CHAIN) + + private fun configWithAggregator(): TraceConfig = + TraceConfig.builder() + .name("stream-test") + .tracingEnabled(true) + .processTracedIO( + TraceProcessIO( + aggregator = java.util.function.Function { chunks -> chunks.joinToString("") } + ) + ) + .build() + + /** Traces a function returning a Stream, capturing the child RunTree for inspection. */ + private fun traceCapturingRun( + config: TraceConfig, + streamFactory: () -> Stream, + ): Pair<(String) -> Stream, () -> RunTree?> { + var childRun: RunTree? = null + val traced = + traceable( + { _: String -> + childRun = getCurrentRunTree() + streamFactory() + }, + config, + ) + return traced to { childRun } + } + + @Test + fun `stream passthrough when tracing disabled`() { + val config = TraceConfig.builder().name("test").tracingEnabled(false).build() + val traced = traceable({ _: String -> Stream.of("a", "b", "c") }, config) + + val collected = traced("input").collect(Collectors.toList()) + + assertThat(collected).isEqualTo(listOf("a", "b", "c")) + } + + @Test + fun `non-stream return is not affected by aggregator`() { + val config = + TraceConfig.builder() + .name("non-stream") + .tracingEnabled(true) + .processTracedIO( + TraceProcessIO(aggregator = java.util.function.Function { it }) + ) + .build() + + withParent(parentRun()) { + val traced = traceable({ input: String -> input.uppercase() }, config) + val result = traced("hello") + + assertThat(result).isEqualTo("HELLO") + } + } + + @Test + fun `stream is instrumented and aggregated on close`() { + val config = configWithAggregator() + + withParent(parentRun()) { + val (traced, getRun) = traceCapturingRun(config) { Stream.of("x", "y", "z") } + val stream = traced("input") + val collected = stream.collect(Collectors.toList()) + stream.close() + + assertThat(collected).isEqualTo(listOf("x", "y", "z")) + + val run = getRun()!! + assertThat(run.endTime).isNotNull() + assertThat(run.outputs).isNotNull() + assertThat(run.outputs!!["outputs"]).isEqualTo("xyz") + assertThat(run.error).isNull() + } + } + + @Test + fun `aggregator error is captured on run`() { + val config = + TraceConfig.builder() + .name("bad-agg") + .tracingEnabled(true) + .processTracedIO( + TraceProcessIO( + aggregator = + java.util.function.Function { throw RuntimeException("agg failed") } + ) + ) + .build() + + withParent(parentRun()) { + val (traced, getRun) = traceCapturingRun(config) { Stream.of("a") } + val stream = traced("input") + stream.collect(Collectors.toList()) + stream.close() + + val run = getRun()!! + assertThat(run.endTime).isNotNull() + assertThat(run.error).contains("agg failed") + } + } + + @Test + fun `iteration error is recorded on run`() { + val config = configWithAggregator() + + withParent(parentRun()) { + val (traced, getRun) = + traceCapturingRun(config) { + Stream.of("ok", "boom").map { + if (it == "boom") throw RuntimeException("stream failed") + it + } + } + val stream = traced("input") + try { + stream.collect(Collectors.toList()) + } catch (_: RuntimeException) {} + stream.close() + + val run = getRun()!! + assertThat(run.endTime).isNotNull() + assertThat(run.error).contains("stream failed") + } + } + + @Test + fun `return type is a real Stream not a proxy`() { + val config = configWithAggregator() + + withParent(parentRun()) { + val traced = traceable({ _: String -> Stream.of("a") }, config) + val result = traced("input") + + assertThat(result).isInstanceOf(Stream::class.java) + assertThat(java.lang.reflect.Proxy.isProxyClass(result::class.java)).isFalse() + + result.collect(Collectors.toList()) + result.close() + } + } + + @Test + fun `early close records partial chunks`() { + val config = configWithAggregator() + + withParent(parentRun()) { + val (traced, getRun) = traceCapturingRun(config) { Stream.of("a", "b", "c", "d", "e") } + val stream = traced("input") + + // Consume only first 2 elements then close + val iter = stream.iterator() + val partial = listOf(iter.next(), iter.next()) + stream.close() + + assertThat(partial).isEqualTo(listOf("a", "b")) + + val run = getRun()!! + assertThat(run.endTime).isNotNull() + assertThat(run.error).isEqualTo("Stream cancelled") + // Partial output is still aggregated + assertThat(run.outputs!!["outputs"]).isEqualTo("ab") + } + } + + @Test + fun `without aggregator stream return completes run immediately`() { + val config = TraceConfig.builder().name("no-agg").tracingEnabled(true).build() + + withParent(parentRun()) { + val (traced, getRun) = traceCapturingRun(config) { Stream.of("a", "b") } + val stream = traced("input") + + // Run should be completed immediately (no deferred close) + val run = getRun()!! + assertThat(run.endTime).isNotNull() + + // Stream still works + val collected = stream.collect(Collectors.toList()) + assertThat(collected).isEqualTo(listOf("a", "b")) + } + } +} From aae9d2c0dc7f7dae40960113154d9ddff3bd0e06 Mon Sep 17 00:00:00 2001 From: Jacob Lee Date: Tue, 31 Mar 2026 10:37:42 -0700 Subject: [PATCH 34/35] feat: Adds streaming support for wrapOpenAI (#118) * Adds support for tracing streams with traceable * Polish * Make stream tracing opt-in * Rework to use a passthrough instead of a proxy * Adds streaming support for wrapOpenAI * Record stream cancellations as errors * Adds streaming example * Allow empty config default, add example * Fix --- .../smith/wrappers/openai/WrapOpenAI.kt | 177 +++++++-- .../testutils/CapturingLangsmithClient.kt | 91 +++++ .../smith/wrappers/openai/WrapOpenAITest.kt | 356 +++++++++++++----- .../smith/example/WrapOpenAIAgentExample.kt | 141 +++++++ .../example/WrapOpenAIStreamingExample.kt | 54 +++ 5 files changed, 693 insertions(+), 126 deletions(-) create mode 100644 langsmith-java-core/src/test/kotlin/com/langchain/smith/testutils/CapturingLangsmithClient.kt create mode 100644 langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIAgentExample.kt create mode 100644 langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIStreamingExample.kt diff --git a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAI.kt b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAI.kt index 6f3cc799c..f006dbcee 100644 --- a/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAI.kt +++ b/langsmith-java-core/src/main/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAI.kt @@ -10,10 +10,15 @@ import com.langchain.smith.tracing.traceable import com.openai.client.OpenAIClient import com.openai.core.ClientOptions import com.openai.core.RequestOptions +import com.openai.core.http.StreamResponse +import com.openai.helpers.ChatCompletionAccumulator +import com.openai.helpers.ResponseAccumulator import com.openai.models.chat.completions.ChatCompletion +import com.openai.models.chat.completions.ChatCompletionChunk import com.openai.models.chat.completions.ChatCompletionCreateParams import com.openai.models.responses.Response import com.openai.models.responses.ResponseCreateParams +import com.openai.models.responses.ResponseStreamEvent import com.openai.services.blocking.ChatService import com.openai.services.blocking.ResponseService import com.openai.services.blocking.chat.ChatCompletionService @@ -23,11 +28,10 @@ import java.util.function.Function /** * Wraps an [OpenAIClient] with LangSmith tracing. * - * The returned client traces `chat().completions().create()` and `responses().create()` calls using - * [traceable], recording inputs and outputs as JSON maps. All other methods — including - * `createStreaming()` — pass through to the delegate unchanged. - * - * // TODO: Trace `createStreaming()` for both chat completions and responses. + * The returned client traces `chat().completions().create()`, `responses().create()`, and their + * streaming counterparts (`createStreaming()`) using [traceable], recording inputs and outputs as + * JSON maps. Streaming calls aggregate chunks using the SDK's built-in accumulators and record the + * final aggregated result when the stream closes. * * The [config] is used as the base configuration for all traced calls — the wrapper overrides * [TraceConfig.name] and [TraceConfig.runType] per operation. @@ -55,7 +59,8 @@ import java.util.function.Function * @param config base tracing configuration (client, project, tags, etc.) * @return a wrapped [OpenAIClient] that traces LLM calls to LangSmith */ -fun wrapOpenAI(client: OpenAIClient, config: TraceConfig): OpenAIClient = +@JvmOverloads +fun wrapOpenAI(client: OpenAIClient, config: TraceConfig = TraceConfig()): OpenAIClient = TracedOpenAIClient(client, config) private class TracedOpenAIClient( @@ -90,41 +95,42 @@ private class TracedChatService( } /** - * Builds the traced `create` functions (1-arg and 2-arg) for an OpenAI service. + * Builds the traced `create` and `createStreaming` functions for an OpenAI service. * * Both [TracedChatCompletionService] and [TracedResponseService] follow the same pattern — this * extracts the shared tracing plumbing so each service only provides the type-specific bits. * * @param P the params type (e.g. [ChatCompletionCreateParams]) * @param R the response type (e.g. [ChatCompletion]) - * @param config base tracing configuration - * @param paramsToMap serializes params to a map for recording as run inputs - * @param useResponsesApi whether this is the responses API (affects metadata) - * @param createOne calls the underlying service's `create(params)` method - * @param createTwo calls the underlying service's `create(params, requestOptions)` method + * @param C the chunk/event type for streaming (e.g. [ChatCompletionChunk]) */ -private class TracedOpenAIClientCreate( +private class TracedOpenAIClientCreate( config: TraceConfig, - paramsToMap: (P) -> Map, - useResponsesApi: Boolean, + private val paramsToMap: (P) -> Map, + private val useResponsesApi: Boolean, createOne: (P) -> R, createTwo: (P, RequestOptions) -> R, + private val streamOne: (P) -> StreamResponse, + private val streamTwo: (P, RequestOptions) -> StreamResponse, + private val aggregator: java.util.function.Function, Any?>, ) { + private val tracedConfig = config.toBuilder().name("ChatOpenAI").runType(RunType.LLM).build() + + private val outputProcessor = + Function> { response -> processChatCompletionOutput(toMap(response)) } + val oneArg: Function = traceable( - Function { - setInvocationParams(paramsToMap(it), useResponsesApi = useResponsesApi) - createOne(it) + Function { p -> + setInvocationParams(paramsToMap(p), useResponsesApi = useResponsesApi) + createOne(p) }, - config + tracedConfig .toBuilder() - .name("ChatOpenAI") - .runType(RunType.LLM) .processTracedIO( TraceProcessIO( processInputs = Function { params -> paramsToMap(params) }, - processOutputs = - Function { response -> processChatCompletionOutput(toMap(response)) }, + processOutputs = outputProcessor, ) ) .build(), @@ -136,22 +142,77 @@ private class TracedOpenAIClientCreate( setInvocationParams(paramsToMap(params), useResponsesApi = useResponsesApi) createTwo(params, opts) }, - config + tracedConfig .toBuilder() - .name("ChatOpenAI") - .runType(RunType.LLM) .processTracedIO( TraceProcessIO, R>( processInputs = Function { (params, opts) -> paramsToMap(params) + ("request_options" to toGenericMap(opts)) }, - processOutputs = - Function { response -> processChatCompletionOutput(toMap(response)) }, + processOutputs = outputProcessor, ) ) .build(), ) + + private val streamOutputProcessor = + Function> { processChatCompletionOutput(toMap(it!!)) } + + /** + * Traces a streaming call. The traced function returns the inner [java.util.stream.Stream] + * (which `traceable` instruments via `peek` + `onClose`), then we rewrap it in a + * [StreamResponse] that delegates `close()` to both the instrumented stream and the original + * response. + */ + fun streamOneArg(params: P): StreamResponse { + val response = streamOne(params) + val tracedStreamFn = + traceable( + Function> { p -> + setInvocationParams(paramsToMap(p), useResponsesApi = useResponsesApi) + response.stream() + }, + tracedConfig + .toBuilder() + .processTracedIO( + TraceProcessIO( + processInputs = Function { p -> paramsToMap(p) }, + processOutputs = streamOutputProcessor, + aggregator = aggregator, + ) + ) + .build(), + ) + val tracedStream = tracedStreamFn.apply(params) + return TracedStreamResponse(tracedStream, response) + } + + fun streamTwoArg(params: P, opts: RequestOptions): StreamResponse { + val response = streamTwo(params, opts) + val tracedStreamFn = + traceable( + Function> { p -> + setInvocationParams(paramsToMap(p), useResponsesApi = useResponsesApi) + response.stream() + }, + tracedConfig + .toBuilder() + .processTracedIO( + TraceProcessIO( + processInputs = + Function { p -> + paramsToMap(p) + ("request_options" to toGenericMap(opts)) + }, + processOutputs = streamOutputProcessor, + aggregator = aggregator, + ) + ) + .build(), + ) + val tracedStream = tracedStreamFn.apply(params) + return TracedStreamResponse(tracedStream, response) + } } private class TracedChatCompletionService( @@ -166,6 +227,9 @@ private class TracedChatCompletionService( useResponsesApi = false, createOne = delegate::create, createTwo = delegate::create, + streamOne = delegate::createStreaming, + streamTwo = delegate::createStreaming, + aggregator = CHAT_COMPLETION_AGGREGATOR, ) override fun create(params: ChatCompletionCreateParams): ChatCompletion = @@ -176,6 +240,15 @@ private class TracedChatCompletionService( requestOptions: RequestOptions, ): ChatCompletion = traced.twoArg.apply(params, requestOptions) + override fun createStreaming( + params: ChatCompletionCreateParams + ): StreamResponse = traced.streamOneArg(params) + + override fun createStreaming( + params: ChatCompletionCreateParams, + requestOptions: RequestOptions, + ): StreamResponse = traced.streamTwoArg(params, requestOptions) + override fun withOptions(modifier: Consumer): ChatCompletionService = TracedChatCompletionService(delegate.withOptions(modifier), config) } @@ -192,6 +265,9 @@ private class TracedResponseService( useResponsesApi = true, createOne = delegate::create, createTwo = delegate::create, + streamOne = delegate::createStreaming, + streamTwo = delegate::createStreaming, + aggregator = RESPONSES_AGGREGATOR, ) override fun create(params: ResponseCreateParams): Response = traced.oneArg.apply(params) @@ -199,6 +275,51 @@ private class TracedResponseService( override fun create(params: ResponseCreateParams, requestOptions: RequestOptions): Response = traced.twoArg.apply(params, requestOptions) + override fun createStreaming( + params: ResponseCreateParams + ): StreamResponse = traced.streamOneArg(params) + + override fun createStreaming( + params: ResponseCreateParams, + requestOptions: RequestOptions, + ): StreamResponse = traced.streamTwoArg(params, requestOptions) + override fun withOptions(modifier: Consumer): ResponseService = TracedResponseService(delegate.withOptions(modifier), config) } + +/** + * A [StreamResponse] that returns an instrumented [java.util.stream.Stream] (with tracing + * peek/onClose handlers) and delegates [close] to the original response. + */ +private class TracedStreamResponse( + private val tracedStream: java.util.stream.Stream, + private val original: StreamResponse, +) : StreamResponse { + + override fun stream(): java.util.stream.Stream = tracedStream + + override fun close() { + try { + tracedStream.close() + } finally { + original.close() + } + } +} + +/** Aggregator that uses the SDK's [ChatCompletionAccumulator] to reassemble chunks. */ +private val CHAT_COMPLETION_AGGREGATOR = + java.util.function.Function, Any?> { chunks -> + val acc = ChatCompletionAccumulator.create() + chunks.filterIsInstance().forEach { acc.accumulate(it) } + acc.chatCompletion() + } + +/** Aggregator that uses the SDK's [ResponseAccumulator] to reassemble events. */ +private val RESPONSES_AGGREGATOR = + java.util.function.Function, Any?> { events -> + val acc = ResponseAccumulator.create() + events.filterIsInstance().forEach { acc.accumulate(it) } + acc.response() + } diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/testutils/CapturingLangsmithClient.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/testutils/CapturingLangsmithClient.kt new file mode 100644 index 000000000..6305b41e0 --- /dev/null +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/testutils/CapturingLangsmithClient.kt @@ -0,0 +1,91 @@ +package com.langchain.smith.testutils + +import com.langchain.smith.client.LangsmithClient +import com.langchain.smith.client.okhttp.LangsmithOkHttpClient +import com.langchain.smith.models.runs.Run +import com.langchain.smith.models.runs.RunIngestBatchParams +import com.langchain.smith.models.runs.RunIngestBatchResponse +import com.langchain.smith.services.blocking.RunService +import java.lang.reflect.Proxy + +/** + * A test [LangsmithClient] that captures [Run] data from `ingestBatch` calls for assertion. + * + * If `LANGSMITH_API_KEY` is set, runs are also forwarded to the real LangSmith server. + */ +internal class CapturingLangsmithClient { + + val postedRuns = mutableListOf() + val patchedRuns = mutableListOf() + + private val realClient: LangsmithClient? = + if (!System.getenv("LANGSMITH_API_KEY").isNullOrBlank()) { + LangsmithOkHttpClient.fromEnv() + } else { + null + } + + fun awaitAndGetPostedRuns(delayMs: Long = 500): List { + Thread.sleep(delayMs) + return postedRuns.toList() + } + + fun awaitAndGetPatchedRuns(delayMs: Long = 500): List { + Thread.sleep(delayMs) + return patchedRuns.toList() + } + + val client: LangsmithClient = createProxy() + + private fun createProxy(): LangsmithClient { + val runService = + Proxy.newProxyInstance( + RunService::class.java.classLoader, + arrayOf(RunService::class.java), + ) { _, method, args -> + if (method.name == "ingestBatch" && args != null && args.isNotEmpty()) { + val params = args[0] + if (params is RunIngestBatchParams) { + params.post().ifPresent { postedRuns.addAll(it) } + params.patch().ifPresent { patchedRuns.addAll(it) } + } + // Forward to real LangSmith if available + if (realClient != null) { + method.invoke(realClient.runs(), *args) + } else { + RunIngestBatchResponse.builder().build() + } + } else if (method.name == "withRawResponse" || method.name == "withOptions") { + throw NotImplementedError() + } else { + // Forward unknown methods to real client if available + if (realClient != null && args != null) { + method.invoke(realClient.runs(), *args) + } else if (realClient != null) { + method.invoke(realClient.runs()) + } else { + throw NotImplementedError( + "CapturingLangsmithClient: ${method.name} not supported without LANGSMITH_API_KEY" + ) + } + } + } as RunService + + return Proxy.newProxyInstance( + LangsmithClient::class.java.classLoader, + arrayOf(LangsmithClient::class.java), + ) { _, method, _ -> + when (method.name) { + "runs" -> runService + "close" -> { + realClient?.close() + Unit + } + else -> + throw NotImplementedError( + "CapturingLangsmithClient only supports runs() and close()" + ) + } + } as LangsmithClient + } +} diff --git a/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAITest.kt b/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAITest.kt index 78b23ea53..92daf7470 100644 --- a/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAITest.kt +++ b/langsmith-java-core/src/test/kotlin/com/langchain/smith/wrappers/openai/WrapOpenAITest.kt @@ -1,160 +1,313 @@ package com.langchain.smith.wrappers.openai -import com.langchain.smith.client.okhttp.LangsmithOkHttpClient +import com.langchain.smith.testutils.CapturingLangsmithClient import com.langchain.smith.tracing.RunType import com.langchain.smith.tracing.TraceConfig import com.langchain.smith.tracing.getCurrentRunTree import com.langchain.smith.tracing.traceable +import com.openai.client.OpenAIClient import com.openai.client.okhttp.OpenAIOkHttpClient import com.openai.models.ChatModel import com.openai.models.chat.completions.ChatCompletionCreateParams import com.openai.models.chat.completions.ChatCompletionMessageParam import com.openai.models.chat.completions.ChatCompletionToolMessageParam import com.openai.models.responses.ResponseCreateParams +import java.util.stream.Stream import kotlin.jvm.optionals.getOrNull import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assumptions.assumeTrue import org.junit.jupiter.api.BeforeAll -import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.MethodSource /** * Integration tests for [wrapOpenAI]. * - * Requires `LANGSMITH_API_KEY` and `OPENAI_API_KEY` to be set. Tests are skipped if either is - * missing. - * - * Run with: - * ```bash - * ./gradlew :langsmith-java-core:test --tests "com.langchain.smith.wrappers.openai.WrapOpenAITest" - * ``` + * Requires `OPENAI_API_KEY` to be set. Tests are skipped if missing. Uses + * [CapturingLangsmithClient] to capture and assert on traced run data without requiring a real + * LangSmith server. */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) internal class WrapOpenAITest { - private lateinit var langsmith: com.langchain.smith.client.LangsmithClient - - private fun awaitPendingRuns() = Thread.sleep(2000) - - private fun baseConfig() = - TraceConfig(client = langsmith, projectName = "wrapOpenAI-tests", tracingEnabled = true) - @BeforeAll fun setUp() { - assumeTrue( - !System.getenv("LANGSMITH_API_KEY").isNullOrBlank(), - "Skipping: LANGSMITH_API_KEY must be set", - ) assumeTrue( !System.getenv("OPENAI_API_KEY").isNullOrBlank(), "Skipping: OPENAI_API_KEY must be set", ) - langsmith = LangsmithOkHttpClient.fromEnv() } - @Test - fun chatCompletions_tracedWithInputsAndOutputs() { - val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), baseConfig()) + /** Abstracts over Chat Completions vs Responses API for parameterized tests. */ + sealed interface ApiMode { + val name: String + + fun create(client: OpenAIClient): String + + fun createStreaming(client: OpenAIClient): Pair + + fun createNested(client: OpenAIClient, config: TraceConfig): Pair + } - val completion = - openai + class ChatCompletionsMode : ApiMode { + override val name = "chat completions" + + override fun create(client: OpenAIClient): String = + client .chat() .completions() - .create( - ChatCompletionCreateParams.builder() - .model(ChatModel.GPT_4_1_MINI) - .addUserMessage("What is 2+2? Answer in one word.") - .maxCompletionTokens(10) - .build() + .create(chatParams()) + .choices()[0] + .message() + .content() + .getOrNull() ?: "" + + override fun createStreaming(client: OpenAIClient): Pair { + val chunks = mutableListOf() + client.chat().completions().createStreaming(chatParams(streaming = true)).use { stream + -> + stream.stream().forEach { chunk -> + chunk.choices().firstOrNull()?.delta()?.content()?.ifPresent { chunks.add(it) } + } + } + return chunks.joinToString("") to chunks.size + } + + override fun createNested( + client: OpenAIClient, + config: TraceConfig, + ): Pair { + var parentRunId: String? = null + val agent = + traceable( + { question: String -> + parentRunId = getCurrentRunTree()?.id + client + .chat() + .completions() + .create( + ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .addUserMessage("$question Answer in one word.") + .maxCompletionTokens(10) + .build() + ) + .choices()[0] + .message() + .content() + .getOrNull() ?: "" + }, + config, ) + return agent("What is 2+2?") to parentRunId + } - val answer = completion.choices()[0].message().content().getOrNull() ?: "" - assertThat(answer).isNotBlank() - println("[wrapOpenAI chat] Result: $answer") - awaitPendingRuns() + private fun chatParams(streaming: Boolean = false) = + ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .addUserMessage("What is 2+2? Answer in one word.") + .maxCompletionTokens(10) + .apply { + if (streaming) { + streamOptions( + com.openai.models.chat.completions.ChatCompletionStreamOptions.builder() + .includeUsage(true) + .build() + ) + } + } + .build() + + override fun toString() = name } - @Test - fun responses_tracedWithInputsAndOutputs() { - val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), baseConfig()) - - val response = - openai - .responses() - .create( - ResponseCreateParams.builder() - .model(ChatModel.GPT_4_1_MINI) - .input("What is the capital of France? Answer in one word.") - .build() - ) + class ResponsesMode : ApiMode { + override val name = "responses" - val answer = - response.output().firstNotNullOfOrNull { item -> + override fun create(client: OpenAIClient): String { + val response = client.responses().create(responsesParams()) + return response.output().firstNotNullOfOrNull { item -> item.message().getOrNull()?.content()?.firstNotNullOfOrNull { block -> block.outputText().getOrNull()?.text() } } ?: "" - assertThat(answer).containsIgnoringCase("Paris") - println("[wrapOpenAI responses] Result: $answer") - awaitPendingRuns() + } + + override fun createStreaming(client: OpenAIClient): Pair { + var eventCount = 0 + client.responses().createStreaming(responsesParams()).use { stream -> + stream.stream().forEach { eventCount++ } + } + return "($eventCount events)" to eventCount + } + + override fun createNested( + client: OpenAIClient, + config: TraceConfig, + ): Pair { + var parentRunId: String? = null + val agent = + traceable( + { _: String -> + parentRunId = getCurrentRunTree()?.id + val response = client.responses().create(responsesParams()) + response.output().firstNotNullOfOrNull { item -> + item.message().getOrNull()?.content()?.firstNotNullOfOrNull { block -> + block.outputText().getOrNull()?.text() + } + } ?: "" + }, + config, + ) + return agent("question") to parentRunId + } + + private fun responsesParams() = + ResponseCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .input("What is the capital of France? Answer in one word.") + .build() + + override fun toString() = name } - @Test - fun chatCompletions_nestsUnderParentTrace() { - val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), baseConfig()) + companion object { + @JvmStatic + fun apiModes(): Stream = Stream.of(ChatCompletionsMode(), ResponsesMode()) + } - var parentRunId: String? = null + @ParameterizedTest(name = "{0}") + @MethodSource("apiModes") + fun tracedWithInputsAndOutputs(mode: ApiMode) { + val capture = CapturingLangsmithClient() + val config = + TraceConfig( + client = capture.client, + projectName = "wrapOpenAI-tests", + tracingEnabled = true, + ) + val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), config) + val answer = mode.create(openai) - val agent = - traceable( - { question: String -> - parentRunId = getCurrentRunTree()?.id - openai - .chat() - .completions() - .create( - ChatCompletionCreateParams.builder() - .model(ChatModel.GPT_4_1_MINI) - .addUserMessage("$question Answer in one word.") - .maxCompletionTokens(10) - .build() - ) - .choices()[0] - .message() - .content() - .getOrNull() ?: "" - }, - TraceConfig( - name = "agent", - client = langsmith, - projectName = "wrapOpenAI-tests", - tracingEnabled = true, - ), + assertThat(answer).isNotBlank() + + val posted = capture.awaitAndGetPostedRuns() + assertThat(posted).isNotEmpty() + val postedRun = posted[0] + assertThat(postedRun.name().orElse(null)).isEqualTo("ChatOpenAI") + assertThat(postedRun.runType().orElse(null)?.asString()).isEqualTo("llm") + + // Inputs should contain model and messages/input + val inputs = postedRun.inputs().get()._additionalProperties() + assertThat(inputs).containsKey("model") + + val patched = capture.awaitAndGetPatchedRuns() + assertThat(patched).isNotEmpty() + val patchedRun = patched[0] + + // Outputs should contain choices/output and usage_metadata + val outputs = patchedRun.outputs().get()._additionalProperties() + assertThat(outputs).isNotEmpty() + assertThat(outputs).containsKey("usage_metadata") + + // Extra should contain metadata with ls_provider, ls_model_name + val extra = patchedRun.extra().get()._additionalProperties() + val metadata = extra["metadata"] + assertThat(metadata).isNotNull() + + println("[wrapOpenAI ${mode.name}] Result: $answer") + } + + @ParameterizedTest(name = "{0}") + @MethodSource("apiModes") + fun streamingTracedWithAggregatedOutput(mode: ApiMode) { + val capture = CapturingLangsmithClient() + val config = + TraceConfig( + client = capture.client, + projectName = "wrapOpenAI-tests", + tracingEnabled = true, + ) + val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), config) + val (answer, count) = mode.createStreaming(openai) + + assertThat(answer).isNotBlank() + assertThat(count).isGreaterThan(0) + + val posted = capture.awaitAndGetPostedRuns() + assertThat(posted).isNotEmpty() + val postedRun = posted[0] + assertThat(postedRun.name().orElse(null)).isEqualTo("ChatOpenAI") + assertThat(postedRun.runType().orElse(null)?.asString()).isEqualTo("llm") + + // Inputs should contain model + val inputs = postedRun.inputs().get()._additionalProperties() + assertThat(inputs).containsKey("model") + + val patched = capture.awaitAndGetPatchedRuns() + assertThat(patched).isNotEmpty() + val patchedRun = patched[0] + + // Outputs should have aggregated result with usage_metadata + val outputs = patchedRun.outputs().get()._additionalProperties() + assertThat(outputs).isNotEmpty() + assertThat(outputs).containsKey("usage_metadata") + + println("[wrapOpenAI streaming ${mode.name}] Result: $answer ($count chunks/events)") + } + + @ParameterizedTest(name = "{0}") + @MethodSource("apiModes") + fun nestsUnderParentTrace(mode: ApiMode) { + val capture = CapturingLangsmithClient() + val config = + TraceConfig( + name = "agent", + client = capture.client, + projectName = "wrapOpenAI-tests", + tracingEnabled = true, ) + val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), config) + val (result, parentRunId) = mode.createNested(openai, config) - val result = agent("What is 2+2?") assertThat(result).isNotBlank() assertThat(parentRunId).isNotNull() - println("[wrapOpenAI nested] Result: $result") - awaitPendingRuns() + + // Should have at least 2 posted runs: the parent agent + the child LLM call + val posted = capture.awaitAndGetPostedRuns() + assertThat(posted.size).isGreaterThanOrEqualTo(2) + + println("[wrapOpenAI nested ${mode.name}] Result: $result") } - @Test + @org.junit.jupiter.api.Test fun chatCompletions_toolCallLoop() { - val openai = wrapOpenAI(OpenAIOkHttpClient.fromEnv(), baseConfig()) - - val executeTool = - traceable( - { _: String -> """{"location":"San Francisco","temp_f":72,"condition":"sunny"}""" }, + val capture = CapturingLangsmithClient() + val toolConfig = + TraceConfig( + name = "get_weather", + client = capture.client, + projectName = "wrapOpenAI-tests", + runType = RunType.TOOL, + tracingEnabled = true, + ) + val openai = + wrapOpenAI( + OpenAIOkHttpClient.fromEnv(), TraceConfig( - name = "get_weather", - client = langsmith, + client = capture.client, projectName = "wrapOpenAI-tests", - runType = RunType.TOOL, tracingEnabled = true, ), ) + val executeTool = + traceable( + { _: String -> """{"location":"San Francisco","temp_f":72,"condition":"sunny"}""" }, + toolConfig, + ) + val agent = traceable( { question: String -> @@ -240,7 +393,7 @@ internal class WrapOpenAITest { }, TraceConfig( name = "weather-agent", - client = langsmith, + client = capture.client, projectName = "wrapOpenAI-tests", tracingEnabled = true, ), @@ -248,7 +401,14 @@ internal class WrapOpenAITest { val result = agent("What is the weather in San Francisco?") assertThat(result).isNotBlank() - println("[wrapOpenAI tool loop] Result: $result") - awaitPendingRuns() + + // Should have: weather-agent + at least 1 ChatOpenAI + at least 1 get_weather + val posted = capture.awaitAndGetPostedRuns() + val runNames = posted.mapNotNull { it.name().orElse(null) } + assertThat(runNames).contains("weather-agent") + assertThat(runNames).contains("ChatOpenAI") + assertThat(runNames).contains("get_weather") + + println("[wrapOpenAI tool loop] Result: $result, runs: $runNames") } } diff --git a/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIAgentExample.kt b/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIAgentExample.kt new file mode 100644 index 000000000..cf1171505 --- /dev/null +++ b/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIAgentExample.kt @@ -0,0 +1,141 @@ +package com.langchain.smith.example + +import com.langchain.smith.tracing.RunType +import com.langchain.smith.tracing.TraceConfig +import com.langchain.smith.tracing.traceable +import com.langchain.smith.wrappers.openai.wrapOpenAI +import com.openai.client.okhttp.OpenAIOkHttpClient +import com.openai.core.JsonValue +import com.openai.models.ChatModel +import com.openai.models.FunctionDefinition +import com.openai.models.FunctionParameters +import com.openai.models.chat.completions.ChatCompletionCreateParams +import com.openai.models.chat.completions.ChatCompletionFunctionTool +import com.openai.models.chat.completions.ChatCompletionMessageParam +import com.openai.models.chat.completions.ChatCompletionToolMessageParam +import com.openai.models.chat.completions.ChatCompletionUserMessageParam +import kotlin.jvm.optionals.getOrNull + +/** + * Demonstrates a simple agent loop using [wrapOpenAI] plus a traced tool call. + * + * The OpenAI client traces LLM calls automatically, and the tool is traced explicitly with + * [traceable], so the final trace in LangSmith shows both the agent call and the tool call. + * + * ## Running + * ```bash + * export LANGSMITH_TRACING=true + * ./gradlew :langsmith-java-example:run -Pexample=WrapOpenAIAgent + * ``` + */ +fun main() { + println("=== wrapOpenAI Agent Example ===\n") + + val openai = wrapOpenAI( + OpenAIOkHttpClient.fromEnv() + ) + + val getWeather = + traceable( + { _: String -> + """{"location":"San Francisco","temp_f":72,"condition":"sunny"}""" + }, + TraceConfig.builder() + .name("get_weather") + .runType(RunType.TOOL) + .build(), + ) + + val weatherTool = + ChatCompletionFunctionTool.builder() + .function( + FunctionDefinition.builder() + .name("get_weather") + .description("Get weather for a location") + .parameters( + FunctionParameters.builder() + .putAdditionalProperty("type", JsonValue.from("object")) + .putAdditionalProperty( + "properties", + JsonValue.from( + mapOf( + "location" to + mapOf( + "type" to "string", + "description" to "City name", + ) + ) + ), + ) + .putAdditionalProperty("required", JsonValue.from(listOf("location"))) + .build(), + ) + .build(), + ) + .build() + + val messages = mutableListOf() + + val agent = + traceable( + { question: String -> + messages += + ChatCompletionMessageParam.ofUser( + ChatCompletionUserMessageParam.builder().content(question).build(), + ) + + var iterations = 0 + while (iterations < 10) { + iterations++ + + val completion = + openai + .chat() + .completions() + .create( + ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .messages(messages) + .addTool(weatherTool) + .build(), + ) + + val message = completion.choices()[0].message() + val toolCalls = message.toolCalls().getOrNull().orEmpty() + + if (toolCalls.isEmpty()) { + return@traceable message.content().getOrNull().orEmpty() + } + + messages += ChatCompletionMessageParam.ofAssistant(message.toParam()) + toolCalls.forEach { toolCall -> + val fn = toolCall.asFunction() + val toolResult = getWeather(fn.function().arguments()) + println(" Tool ${fn.function().name()} -> $toolResult") + messages += + ChatCompletionMessageParam.ofTool( + ChatCompletionToolMessageParam.builder() + .toolCallId(fn.id()) + .content(toolResult) + .build(), + ) + } + } + + error("Model did not finish tool loop within 10 iterations") + }, + TraceConfig.builder() + .name("weather-agent") + .projectName("wrapOpenAI-agent-example") + .build(), + ) + + println("Running agent...\n") + val answer = agent("What's the weather in San Francisco? Use the get_weather tool.") + println("\nFinal answer: $answer") + println("\nTrace recorded to LangSmith:") + println(" weather-agent (chain)") + println(" ├── ChatOpenAI (llm)") + println(" ├── get_weather (tool)") + println(" └── ChatOpenAI (llm)") +} diff --git a/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIStreamingExample.kt b/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIStreamingExample.kt new file mode 100644 index 000000000..c18833049 --- /dev/null +++ b/langsmith-java-example/src/main/kotlin/com/langchain/smith/example/WrapOpenAIStreamingExample.kt @@ -0,0 +1,54 @@ +package com.langchain.smith.example + +import com.langchain.smith.client.okhttp.LangsmithOkHttpClient +import com.langchain.smith.tracing.TraceConfig +import com.langchain.smith.wrappers.openai.wrapOpenAI +import com.openai.client.okhttp.OpenAIOkHttpClient +import com.openai.models.ChatModel +import com.openai.models.chat.completions.ChatCompletionCreateParams +import com.openai.models.chat.completions.ChatCompletionStreamOptions + +/** + * Demonstrates tracing OpenAI streaming calls with LangSmith. + * + * Streaming calls are automatically traced — chunks are aggregated and the final result is recorded + * when the stream closes. + * + * ## Prerequisites + * - `LANGSMITH_API_KEY`: Your LangSmith API key + * - `OPENAI_API_KEY`: Your OpenAI API key + * - `LANGSMITH_TRACING`: Set to "true" to enable tracing + * + * ## Running + * ```bash + * export LANGSMITH_TRACING=true + * ./gradlew :langsmith-java-example:run -Pexample=WrapOpenAIStreaming + * ``` + */ +fun main() { + println("=== wrapOpenAI Streaming Example ===\n") + + val langsmith = LangsmithOkHttpClient.fromEnv() + val openai = wrapOpenAI( + OpenAIOkHttpClient.fromEnv(), + TraceConfig.builder().client(langsmith).build(), + ) + + val params = ChatCompletionCreateParams.builder() + .model(ChatModel.GPT_4_1_MINI) + .addUserMessage("Tell me a short joke.") + .streamOptions(ChatCompletionStreamOptions.builder().includeUsage(true).build()) + .build() + + println("Streaming response:\n") + openai.chat().completions().createStreaming(params).use { stream -> + stream.stream().forEach { chunk -> + chunk.choices().firstOrNull()?.delta()?.content()?.ifPresent { print(it) } + } + } + + println("\n\nTrace recorded to LangSmith with aggregated output (check your dashboard)") + + // Wait for async run posting + Thread.sleep(2000) +} From dd07034ce9a58e7dc3698d7d508d7205548d5e5e Mon Sep 17 00:00:00 2001 From: "stainless-app[bot]" <142633134+stainless-app[bot]@users.noreply.github.com> Date: Tue, 31 Mar 2026 17:38:10 +0000 Subject: [PATCH 35/35] release: 0.1.0-alpha.25 --- .release-please-manifest.json | 2 +- CHANGELOG.md | 32 ++++++++++++++++++++++++++++++++ README.md | 10 +++++----- build.gradle.kts | 2 +- 4 files changed, 39 insertions(+), 7 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 380b6f913..3188cedb5 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.1.0-alpha.24" + ".": "0.1.0-alpha.25" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index c0df92411..ec46ff1b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,37 @@ # Changelog +## 0.1.0-alpha.25 (2026-03-31) + +Full Changelog: [v0.1.0-alpha.24...v0.1.0-alpha.25](https://github.com/langchain-ai/langsmith-java/compare/v0.1.0-alpha.24...v0.1.0-alpha.25) + +### Features + +* Add `traceable` function wrapper for LangSmith tracing ([#101](https://github.com/langchain-ai/langsmith-java/issues/101)) ([f3bf340](https://github.com/langchain-ai/langsmith-java/commit/f3bf3404fe56be9801806ea44f283eb586d96ce8)) +* Adds package version resource to build ([#100](https://github.com/langchain-ai/langsmith-java/issues/100)) ([31cc003](https://github.com/langchain-ai/langsmith-java/commit/31cc0037be79a336cd86f6d53c7093f6c3fb7034)) +* Adds processInputs and processOutputs to traceable ([#113](https://github.com/langchain-ai/langsmith-java/issues/113)) ([ee2991f](https://github.com/langchain-ai/langsmith-java/commit/ee2991f830703f29b3d0eddfd621109362a465e5)) +* Adds streaming support for wrapOpenAI ([#118](https://github.com/langchain-ai/langsmith-java/issues/118)) ([aae9d2c](https://github.com/langchain-ai/langsmith-java/commit/aae9d2c0dc7f7dae40960113154d9ddff3bd0e06)) +* Adds support for tracing streams with traceable ([#117](https://github.com/langchain-ai/langsmith-java/issues/117)) ([0217521](https://github.com/langchain-ai/langsmith-java/commit/0217521b852c70dba4795b145b3eb7b16fd2d10f)) +* **api:** api update ([9182ef8](https://github.com/langchain-ai/langsmith-java/commit/9182ef84e304c602899c73b6865473d3ade4953f)) +* **api:** api update ([0c91488](https://github.com/langchain-ai/langsmith-java/commit/0c914884473e1de2877708cd92db30fdc8fc10aa)) +* **api:** api update ([efa16fc](https://github.com/langchain-ai/langsmith-java/commit/efa16fcb5974fbd5500714936cb52a6e930a6181)) +* **api:** api update ([979e8af](https://github.com/langchain-ai/langsmith-java/commit/979e8af2b6f01444bcea33e1e09d1acbc986a6be)) +* **api:** api update ([cd9f555](https://github.com/langchain-ai/langsmith-java/commit/cd9f555e525172d5ba0bcb0cd033dc045a9026bd)) +* **api:** api update ([af93e09](https://github.com/langchain-ai/langsmith-java/commit/af93e09dc9dd8597454b2a02b1ed37de4e71fde4)) +* **api:** manual updates ([493d5e9](https://github.com/langchain-ai/langsmith-java/commit/493d5e9b2844ff160598b87602c9f91733722fe4)) +* Rework wrapOpenAI ([#114](https://github.com/langchain-ai/langsmith-java/issues/114)) ([63e0bdc](https://github.com/langchain-ai/langsmith-java/commit/63e0bdc5c893185399065c2c602ed0d5c46bbc68)) + + +### Bug Fixes + +* Fix format detection when pulling legacy prompts ([#115](https://github.com/langchain-ai/langsmith-java/issues/115)) ([ea6c3d2](https://github.com/langchain-ai/langsmith-java/commit/ea6c3d29d7c726b7b8455e6e93ec3322330ea5e7)) +* patch security alerts — bump Jackson and constrain vulnerable transitive deps ([#119](https://github.com/langchain-ai/langsmith-java/issues/119)) ([dfe092c](https://github.com/langchain-ai/langsmith-java/commit/dfe092c51ab27c3131b81785321664a75d584764)) + + +### Chores + +* **deps:** bump gradle/actions from 5 to 6 in the all-actions group ([#99](https://github.com/langchain-ai/langsmith-java/issues/99)) ([4ba75e7](https://github.com/langchain-ai/langsmith-java/commit/4ba75e7776499833eddb1959b194b71eb847840f)) +* fix dependabot.yml posture issues ([#105](https://github.com/langchain-ai/langsmith-java/issues/105)) ([a0e5441](https://github.com/langchain-ai/langsmith-java/commit/a0e544170d0c62e340a6250c32b6b521f818eaa4)) + ## 0.1.0-alpha.24 (2026-03-25) Full Changelog: [v0.1.0-alpha.23...v0.1.0-alpha.24](https://github.com/langchain-ai/langsmith-java/compare/v0.1.0-alpha.23...v0.1.0-alpha.24) diff --git a/README.md b/README.md index 27a9835c8..950e7b969 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ -[![Maven Central](https://img.shields.io/maven-central/v/com.langchain.smith/langsmith-java)](https://central.sonatype.com/artifact/com.langchain.smith/langsmith-java/0.1.0-alpha.24) -[![javadoc](https://javadoc.io/badge2/com.langchain.smith/langsmith-java/0.1.0-alpha.24/javadoc.svg)](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.24) +[![Maven Central](https://img.shields.io/maven-central/v/com.langchain.smith/langsmith-java)](https://central.sonatype.com/artifact/com.langchain.smith/langsmith-java/0.1.0-alpha.25) +[![javadoc](https://javadoc.io/badge2/com.langchain.smith/langsmith-java/0.1.0-alpha.25/javadoc.svg)](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.25) @@ -13,7 +13,7 @@ To learn more about LangSmith, check out the [docs](https://docs.smith.langchain -The REST API documentation can be found on [docs.smith.langchain.com](https://docs.smith.langchain.com/). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.24). +The REST API documentation can be found on [docs.smith.langchain.com](https://docs.smith.langchain.com/). Javadocs are available on [javadoc.io](https://javadoc.io/doc/com.langchain.smith/langsmith-java/0.1.0-alpha.25). @@ -24,7 +24,7 @@ The REST API documentation can be found on [docs.smith.langchain.com](https://do ### Gradle ```kotlin -implementation("com.langchain.smith:langsmith-java:0.1.0-alpha.24") +implementation("com.langchain.smith:langsmith-java:0.1.0-alpha.25") ``` ### Maven @@ -33,7 +33,7 @@ implementation("com.langchain.smith:langsmith-java:0.1.0-alpha.24") com.langchain.smith langsmith-java - 0.1.0-alpha.24 + 0.1.0-alpha.25 ``` diff --git a/build.gradle.kts b/build.gradle.kts index 4c1f4f2c0..f37a138e9 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -8,7 +8,7 @@ repositories { allprojects { group = "com.langchain.smith" - version = "0.1.0-alpha.24" // x-release-please-version + version = "0.1.0-alpha.25" // x-release-please-version } subprojects {