Merge branch 'langchain-ai:master' into master

This commit is contained in:
Dhiru Pandey 2025-07-28 11:21:14 -07:00 committed by GitHub
commit b19010c769
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
529 changed files with 2612 additions and 1965 deletions

View File

@ -5,26 +5,31 @@ This project includes a [dev container](https://containers.dev/), which lets you
You can use the dev container configuration in this folder to build and run the app without needing to install any of its tools locally! You can use it in [GitHub Codespaces](https://github.com/features/codespaces) or the [VS Code Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers).
## GitHub Codespaces
[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/langchain-ai/langchain)
You may use the button above, or follow these steps to open this repo in a Codespace:
1. Click the **Code** drop-down menu at the top of https://github.com/langchain-ai/langchain.
1. Click the **Code** drop-down menu at the top of <https://github.com/langchain-ai/langchain>.
1. Click on the **Codespaces** tab.
1. Click **Create codespace on master**.
For more info, check out the [GitHub documentation](https://docs.github.com/en/free-pro-team@latest/github/developing-online-with-codespaces/creating-a-codespace#creating-a-codespace).
## VS Code Dev Containers
[![Open in Dev Containers](https://img.shields.io/static/v1?label=Dev%20Containers&message=Open&color=blue&logo=visualstudiocode)](https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/langchain-ai/langchain)
Note: If you click the link above you will open the main repo (langchain-ai/langchain) and not your local cloned repo. This is fine if you only want to run and test the library, but if you want to contribute you can use the link below and replace with your username and cloned repo name:
```
https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/<yourusername>/<yourclonedreponame>
> [!NOTE]
> If you click the link above you will open the main repo (`langchain-ai/langchain`) and *not* your local cloned repo. This is fine if you only want to run and test the library, but if you want to contribute you can use the link below and replace with your username and cloned repo name:
```txt
https://vscode.dev/redirect?url=vscode://ms-vscode-remote.remote-containers/cloneInVolume?url=https://github.com/&lt;YOUR_USERNAME&gt;/&lt;YOUR_CLONED_REPO_NAME&gt;
```
Then you will have a local cloned repo where you can contribute and then create pull requests.
If you already have VS Code and Docker installed, you can use the button above to get started. This will cause VS Code to automatically install the Dev Containers extension if needed, clone the source code into a container volume, and spin up a dev container for use.
If you already have VS Code and Docker installed, you can use the button above to get started. This will use VSCode to automatically install the Dev Containers extension if needed, clone the source code into a container volume, and spin up a dev container for use.
Alternatively you can also follow these steps to open this repo in a container using the VS Code Dev Containers extension:
@ -40,5 +45,5 @@ You can learn more in the [Dev Containers documentation](https://code.visualstud
## Tips and tricks
* If you are working with the same repository folder in a container and Windows, you'll want consistent line endings (otherwise you may see hundreds of changes in the SCM view). The `.gitattributes` file in the root of this repo will disable line ending conversion and should prevent this. See [tips and tricks](https://code.visualstudio.com/docs/devcontainers/tips-and-tricks#_resolving-git-line-ending-issues-in-containers-resulting-in-many-modified-files) for more info.
* If you'd like to review the contents of the image used in this dev container, you can check it out in the [devcontainers/images](https://github.com/devcontainers/images/tree/main/src/python) repo.
- If you are working with the same repository folder in a container and Windows, you'll want consistent line endings (otherwise you may see hundreds of changes in the SCM view). The `.gitattributes` file in the root of this repo will disable line ending conversion and should prevent this. See [tips and tricks](https://code.visualstudio.com/docs/devcontainers/tips-and-tricks#_resolving-git-line-ending-issues-in-containers-resulting-in-many-modified-files) for more info.
- If you'd like to review the contents of the image used in this dev container, you can check it out in the [devcontainers/images](https://github.com/devcontainers/images/tree/main/src/python) repo.

View File

@ -3,34 +3,56 @@
{
// Name for the dev container
"name": "langchain",
// Point to a Docker Compose file
"dockerComposeFile": "./docker-compose.yaml",
// Required when using Docker Compose. The name of the service to connect to once running
"service": "langchain",
// The optional 'workspaceFolder' property is the path VS Code should open by default when
// connected. This is typically a file mount in .devcontainer/docker-compose.yml
"workspaceFolder": "/workspaces/langchain",
"mounts": [
"source=langchain-workspaces,target=/workspaces/langchain,type=volume"
],
// Prevent the container from shutting down
"overrideCommand": true
"overrideCommand": true,
// Features to add to the dev container. More info: https://containers.dev/features
// "features": {
// "ghcr.io/devcontainers-contrib/features/poetry:2": {}
// }
"features": {
"ghcr.io/devcontainers/features/git:1": {},
"ghcr.io/devcontainers/features/github-cli:1": {}
},
"containerEnv": {
"UV_LINK_MODE": "copy"
},
// Use 'forwardPorts' to make a list of ports inside the container available locally.
// "forwardPorts": [],
// Uncomment the next line to run commands after the container is created.
// "postCreateCommand": "cat /etc/os-release",
// Run commands after the container is created
"postCreateCommand": "uv sync && echo 'LangChain (Python) dev environment ready!'",
// Configure tool-specific properties.
// "customizations": {},
"customizations": {
"vscode": {
"extensions": [
"ms-python.python",
"ms-python.debugpy",
"ms-python.mypy-type-checker",
"ms-python.isort",
"unifiedjs.vscode-mdx",
"davidanson.vscode-markdownlint",
"ms-toolsai.jupyter",
"GitHub.copilot",
"GitHub.copilot-chat"
],
"settings": {
"python.defaultInterpreterPath": ".venv/bin/python",
"python.formatting.provider": "none",
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
}
}
}
// Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root.
// "remoteUser": "root"
}

View File

@ -4,26 +4,9 @@ services:
build:
dockerfile: libs/langchain/dev.Dockerfile
context: ..
volumes:
# Update this to wherever you want VS Code to mount the folder of your project
- ..:/workspaces/langchain:cached
networks:
- langchain-network
# environment:
# MONGO_ROOT_USERNAME: root
# MONGO_ROOT_PASSWORD: example123
# depends_on:
# - mongo
# mongo:
# image: mongo
# restart: unless-stopped
# environment:
# MONGO_INITDB_ROOT_USERNAME: root
# MONGO_INITDB_ROOT_PASSWORD: example123
# ports:
# - "27017:27017"
# networks:
# - langchain-network
networks:
langchain-network:

52
.editorconfig Normal file
View File

@ -0,0 +1,52 @@
# top-most EditorConfig file
root = true
# All files
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
# Python files
[*.py]
indent_style = space
indent_size = 4
max_line_length = 88
# JSON files
[*.json]
indent_style = space
indent_size = 2
# YAML files
[*.{yml,yaml}]
indent_style = space
indent_size = 2
# Markdown files
[*.md]
indent_style = space
indent_size = 2
trim_trailing_whitespace = false
# Configuration files
[*.{toml,ini,cfg}]
indent_style = space
indent_size = 4
# Shell scripts
[*.sh]
indent_style = space
indent_size = 2
# Makefile
[Makefile]
indent_style = tab
indent_size = 4
# Jupyter notebooks
[*.ipynb]
# Jupyter may include trailing whitespace in cell
# outputs that's semantically meaningful
trim_trailing_whitespace = false

View File

@ -1,4 +1,4 @@
name: compile-integration-test
name: '🔗 Compile Integration Tests'
on:
workflow_call:
@ -25,24 +25,24 @@ jobs:
working-directory: ${{ inputs.working-directory }}
runs-on: ubuntu-latest
timeout-minutes: 20
name: "uv run pytest -m compile tests/integration_tests #${{ inputs.python-version }}"
name: 'Python ${{ inputs.python-version }}'
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ inputs.python-version }} + uv
- name: '🐍 Set up Python ${{ inputs.python-version }} + UV'
uses: "./.github/actions/uv_setup"
with:
python-version: ${{ inputs.python-version }}
- name: Install integration dependencies
- name: '📦 Install Integration Dependencies'
shell: bash
run: uv sync --group test --group test_integration
- name: Check integration tests compile
- name: '🔗 Check Integration Tests Compile'
shell: bash
run: uv run pytest -m compile tests/integration_tests
- name: Ensure the tests did not create any additional files
- name: '🧹 Verify Clean Working Directory'
shell: bash
run: |
set -eu

View File

@ -1,4 +1,4 @@
name: Integration Tests
name: '🚀 Integration Tests'
on:
workflow_dispatch:
@ -24,20 +24,20 @@ jobs:
run:
working-directory: ${{ inputs.working-directory }}
runs-on: ubuntu-latest
name: Python ${{ inputs.python-version }}
name: '🚀 Integration Tests (Python ${{ inputs.python-version }})'
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ inputs.python-version }} + uv
- name: '🐍 Set up Python ${{ inputs.python-version }} + UV'
uses: "./.github/actions/uv_setup"
with:
python-version: ${{ inputs.python-version }}
- name: Install dependencies
- name: '📦 Install Integration Dependencies'
shell: bash
run: uv sync --group test --group test_integration
- name: Run integration tests
- name: '🚀 Run Integration Tests'
shell: bash
env:
AI21_API_KEY: ${{ secrets.AI21_API_KEY }}

View File

@ -1,4 +1,6 @@
name: lint
name: '🧹 Code Linting'
# Runs code quality checks using ruff, mypy, and other linting tools
# Checks both package code and test code for consistency
on:
workflow_call:
@ -24,19 +26,21 @@ env:
UV_FROZEN: "true"
jobs:
# Linting job - runs quality checks on package and test code
build:
name: "make lint #${{ inputs.python-version }}"
name: 'Python ${{ inputs.python-version }}'
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- name: '📋 Checkout Code'
uses: actions/checkout@v4
- name: Set up Python ${{ inputs.python-version }} + uv
- name: '🐍 Set up Python ${{ inputs.python-version }} + UV'
uses: "./.github/actions/uv_setup"
with:
python-version: ${{ inputs.python-version }}
- name: Install dependencies
- name: '📦 Install Lint & Typing Dependencies'
# Also installs dev/lint/test/typing dependencies, to ensure we have
# type hints for as many of our libraries as possible.
# This helps catch errors that require dependencies to be spotted, for example:
@ -49,12 +53,12 @@ jobs:
run: |
uv sync --group lint --group typing
- name: Analysing the code with our lint
- name: '🔍 Analyze Package Code with Linters'
working-directory: ${{ inputs.working-directory }}
run: |
make lint_package
- name: Install unit test dependencies
- name: '📦 Install Unit Test Dependencies'
# Also installs dev/lint/test/typing dependencies, to ensure we have
# type hints for as many of our libraries as possible.
# This helps catch errors that require dependencies to be spotted, for example:
@ -67,13 +71,13 @@ jobs:
working-directory: ${{ inputs.working-directory }}
run: |
uv sync --inexact --group test
- name: Install unit+integration test dependencies
- name: '📦 Install Unit + Integration Test Dependencies'
if: ${{ startsWith(inputs.working-directory, 'libs/partners/') }}
working-directory: ${{ inputs.working-directory }}
run: |
uv sync --inexact --group test --group test_integration
- name: Analysing the code with our lint
- name: '🔍 Analyze Test Code with Linters'
working-directory: ${{ inputs.working-directory }}
run: |
make lint_tests

View File

@ -1,5 +1,5 @@
name: Release
run-name: Release ${{ inputs.working-directory }} by @${{ github.actor }}
name: '🚀 Package Release'
run-name: '🚀 Release ${{ inputs.working-directory }} by @${{ github.actor }}'
on:
workflow_call:
inputs:
@ -18,7 +18,7 @@ on:
required: false
type: boolean
default: false
description: "Release from a non-master branch (danger!)"
description: "Release from a non-master branch (danger!) - Only use for hotfixes"
env:
PYTHON_VERSION: "3.11"
@ -26,6 +26,8 @@ env:
UV_NO_SYNC: "true"
jobs:
# Build the distribution package and extract version info
# Runs in isolated environment with minimal permissions for security
build:
if: github.ref == 'refs/heads/master' || inputs.dangerous-nonmaster-release
environment: Scheduled testing

View File

@ -1,4 +1,6 @@
name: test
name: '🧪 Unit Testing'
# Runs unit tests with both current and minimum supported dependency versions
# to ensure compatibility across the supported range
on:
workflow_call:
@ -20,31 +22,33 @@ env:
UV_NO_SYNC: "true"
jobs:
# Main test job - runs unit tests with current deps, then retests with minimum versions
build:
defaults:
run:
working-directory: ${{ inputs.working-directory }}
runs-on: ubuntu-latest
timeout-minutes: 20
name: "make test #${{ inputs.python-version }}"
name: 'Python ${{ inputs.python-version }}'
steps:
- uses: actions/checkout@v4
- name: '📋 Checkout Code'
uses: actions/checkout@v4
- name: Set up Python ${{ inputs.python-version }} + uv
- name: '🐍 Set up Python ${{ inputs.python-version }} + UV'
uses: "./.github/actions/uv_setup"
id: setup-python
with:
python-version: ${{ inputs.python-version }}
- name: Install dependencies
- name: '📦 Install Test Dependencies'
shell: bash
run: uv sync --group test --dev
- name: Run core tests
- name: '🧪 Run Core Unit Tests'
shell: bash
run: |
make test
- name: Get minimum versions
- name: '🔍 Calculate Minimum Dependency Versions'
working-directory: ${{ inputs.working-directory }}
id: min-version
shell: bash
@ -55,7 +59,7 @@ jobs:
echo "min-versions=$min_versions" >> "$GITHUB_OUTPUT"
echo "min-versions=$min_versions"
- name: Run unit tests with minimum dependency versions
- name: '🧪 Run Tests with Minimum Dependencies'
if: ${{ steps.min-version.outputs.min-versions != '' }}
env:
MIN_VERSIONS: ${{ steps.min-version.outputs.min-versions }}
@ -64,7 +68,7 @@ jobs:
make tests
working-directory: ${{ inputs.working-directory }}
- name: Ensure the tests did not create any additional files
- name: '🧹 Verify Clean Working Directory'
shell: bash
run: |
set -eu

View File

@ -1,4 +1,4 @@
name: test_doc_imports
name: '📑 Documentation Import Testing'
on:
workflow_call:
@ -18,29 +18,30 @@ jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 20
name: "check doc imports #${{ inputs.python-version }}"
name: '🔍 Check Doc Imports (Python ${{ inputs.python-version }})'
steps:
- uses: actions/checkout@v4
- name: '📋 Checkout Code'
uses: actions/checkout@v4
- name: Set up Python ${{ inputs.python-version }} + uv
- name: '🐍 Set up Python ${{ inputs.python-version }} + UV'
uses: "./.github/actions/uv_setup"
with:
python-version: ${{ inputs.python-version }}
- name: Install dependencies
- name: '📦 Install Test Dependencies'
shell: bash
run: uv sync --group test
- name: Install langchain editable
- name: '📦 Install LangChain in Editable Mode'
run: |
VIRTUAL_ENV=.venv uv pip install langchain-experimental langchain-community -e libs/core libs/langchain
- name: Check doc imports
- name: '🔍 Validate Documentation Import Statements'
shell: bash
run: |
uv run python docs/scripts/check_imports.py
- name: Ensure the test did not create any additional files
- name: '🧹 Verify Clean Working Directory'
shell: bash
run: |
set -eu

View File

@ -1,4 +1,4 @@
name: test pydantic intermediate versions
name: '🐍 Pydantic Version Testing'
on:
workflow_call:
@ -31,29 +31,30 @@ jobs:
working-directory: ${{ inputs.working-directory }}
runs-on: ubuntu-latest
timeout-minutes: 20
name: "make test # pydantic: ~=${{ inputs.pydantic-version }}, python: ${{ inputs.python-version }}, "
name: 'Pydantic ~=${{ inputs.pydantic-version }}'
steps:
- uses: actions/checkout@v4
- name: '📋 Checkout Code'
uses: actions/checkout@v4
- name: Set up Python ${{ inputs.python-version }} + uv
- name: '🐍 Set up Python ${{ inputs.python-version }} + UV'
uses: "./.github/actions/uv_setup"
with:
python-version: ${{ inputs.python-version }}
- name: Install dependencies
- name: '📦 Install Test Dependencies'
shell: bash
run: uv sync --group test
- name: Overwrite pydantic version
- name: '🔄 Install Specific Pydantic Version'
shell: bash
run: VIRTUAL_ENV=.venv uv pip install pydantic~=${{ inputs.pydantic-version }}
- name: Run core tests
- name: '🧪 Run Core Tests'
shell: bash
run: |
make test
- name: Ensure the tests did not create any additional files
- name: '🧹 Verify Clean Working Directory'
shell: bash
run: |
set -eu

View File

@ -1,4 +1,4 @@
name: test-release
name: '🧪 Test Release Package'
on:
workflow_call:
@ -29,7 +29,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Set up Python + uv
- name: '🐍 Set up Python + UV'
uses: "./.github/actions/uv_setup"
with:
python-version: ${{ env.PYTHON_VERSION }}
@ -45,17 +45,17 @@ jobs:
# > It is strongly advised to separate jobs for building [...]
# > from the publish job.
# https://github.com/pypa/gh-action-pypi-publish#non-goals
- name: Build project for distribution
- name: '📦 Build Project for Distribution'
run: uv build
working-directory: ${{ inputs.working-directory }}
- name: Upload build
- name: '⬆️ Upload Build Artifacts'
uses: actions/upload-artifact@v4
with:
name: test-dist
path: ${{ inputs.working-directory }}/dist/
- name: Check Version
- name: '🔍 Extract Version Information'
id: check-version
shell: python
working-directory: ${{ inputs.working-directory }}

View File

@ -1,13 +1,15 @@
name: API Docs Build
name: '📚 API Documentation Build'
# Runs daily or can be triggered manually for immediate updates
on:
workflow_dispatch:
schedule:
- cron: '0 13 * * *'
- cron: '0 13 * * *' # Daily at 1PM UTC
env:
PYTHON_VERSION: "3.11"
jobs:
# Only runs on main repository to prevent unnecessary builds on forks
build:
if: github.repository == 'langchain-ai/langchain' || github.event_name != 'schedule'
runs-on: ubuntu-latest
@ -23,7 +25,7 @@ jobs:
path: langchain-api-docs-html
token: ${{ secrets.TOKEN_GITHUB_API_DOCS_HTML }}
- name: Get repos with yq
- name: '📋 Extract Repository List with yq'
id: get-unsorted-repos
uses: mikefarah/yq@master
with:
@ -42,7 +44,7 @@ jobs:
| .repo
' langchain/libs/packages.yml
- name: Parse YAML and checkout repos
- name: '📋 Parse YAML & Checkout Repositories'
env:
REPOS_UNSORTED: ${{ steps.get-unsorted-repos.outputs.result }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@ -70,39 +72,39 @@ jobs:
git clone --depth 1 https://github.com/$repo.git $REPO_NAME
done
- name: Setup Python ${{ env.PYTHON_VERSION }}
- name: '🐍 Setup Python ${{ env.PYTHON_VERSION }}'
uses: actions/setup-python@v5
id: setup-python
with:
python-version: ${{ env.PYTHON_VERSION }}
- name: Install initial py deps
- name: '📦 Install Initial Python Dependencies'
working-directory: langchain
run: |
python -m pip install -U uv
python -m uv pip install --upgrade --no-cache-dir pip setuptools pyyaml
- name: Move libs
- name: '📦 Organize Library Directories'
run: python langchain/.github/scripts/prep_api_docs_build.py
- name: Rm old html
- name: '🧹 Remove Old HTML Files'
run:
rm -rf langchain-api-docs-html/api_reference_build/html
- name: Install dependencies
- name: '📦 Install Documentation Dependencies'
working-directory: langchain
run: |
python -m uv pip install $(ls ./libs/partners | xargs -I {} echo "./libs/partners/{}") --overrides ./docs/vercel_overrides.txt
python -m uv pip install libs/core libs/langchain libs/text-splitters libs/community libs/experimental libs/standard-tests
python -m uv pip install -r docs/api_reference/requirements.txt
- name: Set Git config
- name: '🔧 Configure Git Settings'
working-directory: langchain
run: |
git config --local user.email "actions@github.com"
git config --local user.name "Github Actions"
- name: Build docs
- name: '📚 Build API Documentation'
working-directory: langchain
run: |
python docs/api_reference/create_api_rst.py

View File

@ -1,4 +1,4 @@
name: Check Broken Links
name: '🔗 Check Broken Links'
on:
workflow_dispatch:
@ -14,15 +14,15 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Node.js 18.x
- name: '🟢 Setup Node.js 18.x'
uses: actions/setup-node@v4
with:
node-version: 18.x
cache: "yarn"
cache-dependency-path: ./docs/yarn.lock
- name: Install dependencies
- name: '📦 Install Node Dependencies'
run: yarn install --immutable --mode=skip-build
working-directory: ./docs
- name: Check broken links
- name: '🔍 Scan Documentation for Broken Links'
run: yarn check-broken-links
working-directory: ./docs

View File

@ -1,4 +1,6 @@
name: Check `core` Version Equality
name: '🔍 Check `core` Version Equality'
# Ensures version numbers in pyproject.toml and version.py stay in sync
# Prevents releases with mismatched version numbers
on:
pull_request:
@ -16,7 +18,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Check version equality
- name: '✅ Verify pyproject.toml & version.py Match'
run: |
PYPROJECT_VERSION=$(grep -Po '(?<=^version = ")[^"]*' libs/core/pyproject.toml)
VERSION_PY_VERSION=$(grep -Po '(?<=^VERSION = ")[^"]*' libs/core/langchain_core/version.py)

View File

@ -1,4 +1,4 @@
name: CI
name: '🔧 CI'
on:
push:
@ -6,6 +6,7 @@ on:
pull_request:
merge_group:
# Optimizes CI performance by canceling redundant workflow runs
# If another push to the same PR or branch happens while this workflow is still running,
# cancel the earlier run in favor of the next run.
#
@ -24,16 +25,23 @@ env:
UV_NO_SYNC: "true"
jobs:
# This job analyzes which files changed and creates a dynamic test matrix
# to only run tests/lints for the affected packages, improving CI efficiency
build:
name: 'Detect Changes & Set Matrix'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- name: '📋 Checkout Code'
uses: actions/checkout@v4
- name: '🐍 Setup Python 3.11'
uses: actions/setup-python@v5
with:
python-version: '3.11'
- id: files
- name: '📂 Get Changed Files'
id: files
uses: Ana06/get-changed-files@v2.3.0
- id: set-matrix
- name: '🔍 Analyze Changed Files & Generate Build Matrix'
id: set-matrix
run: |
python -m pip install packaging requests
python .github/scripts/check_diff.py ${{ steps.files.outputs.all }} >> $GITHUB_OUTPUT
@ -45,8 +53,8 @@ jobs:
dependencies: ${{ steps.set-matrix.outputs.dependencies }}
test-doc-imports: ${{ steps.set-matrix.outputs.test-doc-imports }}
test-pydantic: ${{ steps.set-matrix.outputs.test-pydantic }}
# Run linting only on packages that have changed files
lint:
name: cd ${{ matrix.job-configs.working-directory }}
needs: [ build ]
if: ${{ needs.build.outputs.lint != '[]' }}
strategy:
@ -59,8 +67,8 @@ jobs:
python-version: ${{ matrix.job-configs.python-version }}
secrets: inherit
# Run unit tests only on packages that have changed files
test:
name: cd ${{ matrix.job-configs.working-directory }}
needs: [ build ]
if: ${{ needs.build.outputs.test != '[]' }}
strategy:
@ -73,8 +81,8 @@ jobs:
python-version: ${{ matrix.job-configs.python-version }}
secrets: inherit
# Test compatibility with different Pydantic versions for affected packages
test-pydantic:
name: cd ${{ matrix.job-configs.working-directory }}
needs: [ build ]
if: ${{ needs.build.outputs.test-pydantic != '[]' }}
strategy:
@ -95,12 +103,12 @@ jobs:
job-configs: ${{ fromJson(needs.build.outputs.test-doc-imports) }}
fail-fast: false
uses: ./.github/workflows/_test_doc_imports.yml
secrets: inherit
with:
python-version: ${{ matrix.job-configs.python-version }}
secrets: inherit
# Verify integration tests compile without actually running them (faster feedback)
compile-integration-tests:
name: cd ${{ matrix.job-configs.working-directory }}
needs: [ build ]
if: ${{ needs.build.outputs.compile-integration-tests != '[]' }}
strategy:
@ -113,8 +121,9 @@ jobs:
python-version: ${{ matrix.job-configs.python-version }}
secrets: inherit
# Run extended test suites that require additional dependencies
extended-tests:
name: "cd ${{ matrix.job-configs.working-directory }} / make extended_tests #${{ matrix.job-configs.python-version }}"
name: 'Extended Tests'
needs: [ build ]
if: ${{ needs.build.outputs.extended-tests != '[]' }}
strategy:
@ -130,12 +139,12 @@ jobs:
steps:
- uses: actions/checkout@v4
- name: Set up Python ${{ matrix.job-configs.python-version }} + uv
- name: '🐍 Set up Python ${{ matrix.job-configs.python-version }} + UV'
uses: "./.github/actions/uv_setup"
with:
python-version: ${{ matrix.job-configs.python-version }}
- name: Install dependencies and run extended tests
- name: '📦 Install Dependencies & Run Extended Tests'
shell: bash
run: |
echo "Running extended tests, installing dependencies with uv..."
@ -144,7 +153,7 @@ jobs:
VIRTUAL_ENV=.venv uv pip install -r extended_testing_deps.txt
VIRTUAL_ENV=.venv make extended_tests
- name: Ensure the tests did not create any additional files
- name: '🧹 Verify Clean Working Directory'
shell: bash
run: |
set -eu
@ -156,8 +165,9 @@ jobs:
# and `set -e` above will cause the step to fail.
echo "$STATUS" | grep 'nothing to commit, working tree clean'
# Final status check - ensures all required jobs passed before allowing merge
ci_success:
name: "CI Success"
name: '✅ CI Success'
needs: [build, lint, test, compile-integration-tests, extended-tests, test-doc-imports, test-pydantic]
if: |
always()
@ -167,7 +177,7 @@ jobs:
RESULTS_JSON: ${{ toJSON(needs.*.result) }}
EXIT_CODE: ${{!contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && '0' || '1'}}
steps:
- name: "CI Success"
- name: '🎉 All Checks Passed'
run: |
echo $JOBS_JSON
echo $RESULTS_JSON

View File

@ -1,4 +1,4 @@
name: Integration Docs Lint
name: '📑 Integration Docs Lint'
on:
push:
@ -33,6 +33,6 @@ jobs:
*.ipynb
*.md
*.mdx
- name: Check new docs
- name: '🔍 Check New Documentation Templates'
run: |
python docs/scripts/check_templates.py ${{ steps.files.outputs.added }}

View File

@ -1,35 +0,0 @@
name: CI / cd . / make spell_check
on:
push:
branches: [master, v0.1, v0.2]
pull_request:
permissions:
contents: read
jobs:
codespell:
name: (Check for spelling errors)
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Dependencies
run: |
pip install toml
- name: Extract Ignore Words List
run: |
# Use a Python script to extract the ignore words list from pyproject.toml
python .github/workflows/extract_ignored_words_list.py
id: extract_ignore_words
# - name: Codespell
# uses: codespell-project/actions-codespell@v2
# with:
# skip: guide_imports.json,*.ambr,./cookbook/data/imdb_top_1000.csv,*.lock
# ignore_words_list: ${{ steps.extract_ignore_words.outputs.ignore_words_list }}
# exclude_file: ./.github/workflows/codespell-exclude

View File

@ -1,4 +1,4 @@
name: CodSpeed
name: '⚡ CodSpeed'
on:
push:
@ -18,7 +18,7 @@ env:
jobs:
codspeed:
name: Run benchmarks
name: 'Benchmark'
runs-on: ubuntu-latest
strategy:
matrix:
@ -38,7 +38,7 @@ jobs:
- uses: actions/checkout@v4
# We have to use 3.12 as 3.13 is not yet supported
- name: Install uv
- name: '📦 Install UV Package Manager'
uses: astral-sh/setup-uv@v6
with:
python-version: "3.12"
@ -47,11 +47,11 @@ jobs:
with:
python-version: "3.12"
- name: Install dependencies
- name: '📦 Install Test Dependencies'
run: uv sync --group test
working-directory: ${{ matrix.working-directory }}
- name: Run benchmarks ${{ matrix.working-directory }}
- name: '⚡ Run Benchmarks: ${{ matrix.working-directory }}'
uses: CodSpeedHQ/action@v3
with:
token: ${{ secrets.CODSPEED_TOKEN }}

View File

@ -1,4 +1,4 @@
name: LangChain People
name: '👥 LangChain People'
on:
schedule:
@ -14,13 +14,13 @@ jobs:
permissions:
contents: write
steps:
- name: Dump GitHub context
- name: '📋 Dump GitHub Context'
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v4
# Ref: https://github.com/actions/runner/issues/2033
- name: Fix git safe.directory in container
- name: '🔧 Fix Git Safe Directory in Container'
run: mkdir -p /home/runner/work/_temp/_github_home && printf "[safe]\n\tdirectory = /github/workspace" > /home/runner/work/_temp/_github_home/.gitconfig
- uses: ./.github/actions/people
with:

View File

@ -4,6 +4,7 @@
# Purpose:
# Enforces Conventional Commits format for pull request titles to maintain a
# clear, consistent, and machine-readable change history across our repository.
# This helps with automated changelog generation and semantic versioning.
#
# Enforced Commit Message Format (Conventional Commits 1.0.0):
# <type>[optional scope]: <description>
@ -45,7 +46,7 @@
# • Conventional Commits spec: https://www.conventionalcommits.org/en/v1.0.0/
# -----------------------------------------------------------------------------
name: PR Title Lint
name: '🏷️ PR Title Lint'
permissions:
pull-requests: read
@ -55,11 +56,12 @@ on:
types: [opened, edited, synchronize]
jobs:
# Validates that PR title follows Conventional Commits specification
lint-pr-title:
name: Validate PR Title
name: 'Validate PR Title Format'
runs-on: ubuntu-latest
steps:
- name: Validate PR Title
- name: '✅ Validate Conventional Commits Format'
uses: amannn/action-semantic-pull-request@v5
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@ -1,4 +1,4 @@
name: Run Notebooks
name: '📝 Run Documentation Notebooks'
on:
workflow_dispatch:
@ -24,43 +24,43 @@ jobs:
build:
runs-on: ubuntu-latest
if: github.repository == 'langchain-ai/langchain' || github.event_name != 'schedule'
name: "Test docs"
name: '📑 Test Documentation Notebooks'
steps:
- uses: actions/checkout@v4
- name: Set up Python + uv
- name: '🐍 Set up Python + UV'
uses: "./.github/actions/uv_setup"
with:
python-version: ${{ github.event.inputs.python_version || '3.11' }}
- name: 'Authenticate to Google Cloud'
- name: '🔐 Authenticate to Google Cloud'
id: 'auth'
uses: google-github-actions/auth@v2
with:
credentials_json: '${{ secrets.GOOGLE_CREDENTIALS }}'
- name: Configure AWS Credentials
- name: '🔐 Configure AWS Credentials'
uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ secrets.AWS_REGION }}
- name: Install dependencies
- name: '📦 Install Dependencies'
run: |
uv sync --group dev --group test
- name: Pre-download files
- name: '📦 Pre-download Test Files'
run: |
uv run python docs/scripts/cache_data.py
curl -s https://raw.githubusercontent.com/lerocha/chinook-database/master/ChinookDatabase/DataSources/Chinook_Sqlite.sql | sqlite3 docs/docs/how_to/Chinook.db
cp docs/docs/how_to/Chinook.db docs/docs/tutorials/Chinook.db
- name: Prepare notebooks
- name: '🔧 Prepare Notebooks for CI'
run: |
uv run python docs/scripts/prepare_notebooks_for_ci.py --comment-install-cells --working-directory ${{ github.event.inputs.working-directory || 'all' }}
- name: Run notebooks
- name: '🚀 Execute Notebooks'
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
FIREWORKS_API_KEY: ${{ secrets.FIREWORKS_API_KEY }}

View File

@ -1,7 +1,7 @@
name: Scheduled Tests
name: '⏰ Scheduled Integration Tests'
on:
workflow_dispatch: # Allows to trigger the workflow manually in GitHub UI
workflow_dispatch: # Allows maintainers to trigger the workflow manually in GitHub UI
inputs:
working-directory-force:
type: string
@ -10,7 +10,7 @@ on:
type: string
description: "Python version to use - defaults to 3.9 and 3.11 in matrix - example value: 3.9"
schedule:
- cron: '0 13 * * *'
- cron: '0 13 * * *' # Runs daily at 1PM UTC (9AM EDT/6AM PDT)
permissions:
contents: read
@ -22,14 +22,16 @@ env:
POETRY_LIBS: ("libs/partners/google-vertexai" "libs/partners/google-genai" "libs/partners/aws")
jobs:
# Generate dynamic test matrix based on input parameters or defaults
# Only runs on the main repo (for scheduled runs) or when manually triggered
compute-matrix:
if: github.repository_owner == 'langchain-ai' || github.event_name != 'schedule'
runs-on: ubuntu-latest
name: Compute matrix
name: '📋 Compute Test Matrix'
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- name: Set matrix
- name: '🔢 Generate Python & Library Matrix'
id: set-matrix
env:
DEFAULT_LIBS: ${{ env.DEFAULT_LIBS }}
@ -50,9 +52,11 @@ jobs:
matrix="{\"python-version\": $python_version, \"working-directory\": $working_directory}"
echo $matrix
echo "matrix=$matrix" >> $GITHUB_OUTPUT
# Run integration tests against partner libraries with live API credentials
# Tests are run with both Poetry and UV depending on the library's setup
build:
if: github.repository_owner == 'langchain-ai' || github.event_name != 'schedule'
name: Python ${{ matrix.python-version }} - ${{ matrix.working-directory }}
name: '🐍 Python ${{ matrix.python-version }}: ${{ matrix.working-directory }}'
runs-on: ubuntu-latest
needs: [compute-matrix]
timeout-minutes: 20
@ -75,7 +79,7 @@ jobs:
repository: langchain-ai/langchain-aws
path: langchain-aws
- name: Move libs
- name: '📦 Organize External Libraries'
run: |
rm -rf \
langchain/libs/partners/google-genai \
@ -84,7 +88,7 @@ jobs:
mv langchain-google/libs/vertexai langchain/libs/partners/google-vertexai
mv langchain-aws/libs/aws langchain/libs/partners/aws
- name: Set up Python ${{ matrix.python-version }} with poetry
- name: '🐍 Set up Python ${{ matrix.python-version }} + Poetry'
if: contains(env.POETRY_LIBS, matrix.working-directory)
uses: "./langchain/.github/actions/poetry_setup"
with:
@ -93,40 +97,40 @@ jobs:
working-directory: langchain/${{ matrix.working-directory }}
cache-key: scheduled
- name: Set up Python ${{ matrix.python-version }} + uv
- name: '🐍 Set up Python ${{ matrix.python-version }} + UV'
if: "!contains(env.POETRY_LIBS, matrix.working-directory)"
uses: "./langchain/.github/actions/uv_setup"
with:
python-version: ${{ matrix.python-version }}
- name: 'Authenticate to Google Cloud'
- name: '🔐 Authenticate to Google Cloud'
id: 'auth'
uses: google-github-actions/auth@v2
with:
credentials_json: '${{ secrets.GOOGLE_CREDENTIALS }}'
- name: Configure AWS Credentials
- name: '🔐 Configure AWS Credentials'
uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ secrets.AWS_REGION }}
- name: Install dependencies (poetry)
- name: '📦 Install Dependencies (Poetry)'
if: contains(env.POETRY_LIBS, matrix.working-directory)
run: |
echo "Running scheduled tests, installing dependencies with poetry..."
cd langchain/${{ matrix.working-directory }}
poetry install --with=test_integration,test
- name: Install dependencies (uv)
- name: '📦 Install Dependencies (UV)'
if: "!contains(env.POETRY_LIBS, matrix.working-directory)"
run: |
echo "Running scheduled tests, installing dependencies with uv..."
cd langchain/${{ matrix.working-directory }}
uv sync --group test --group test_integration
- name: Run integration tests
- name: '🚀 Run Integration Tests'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
@ -155,14 +159,15 @@ jobs:
cd langchain/${{ matrix.working-directory }}
make integration_tests
- name: Remove external libraries
- name: '🧹 Clean up External Libraries'
# Clean up external libraries to avoid affecting git status check
run: |
rm -rf \
langchain/libs/partners/google-genai \
langchain/libs/partners/google-vertexai \
langchain/libs/partners/aws
- name: Ensure tests did not create additional files
- name: '🧹 Verify Clean Working Directory'
working-directory: langchain
run: |
set -eu

1
.gitignore vendored
View File

@ -1,5 +1,4 @@
.vs/
.vscode/
.idea/
# Byte-compiled / optimized / DLL files
__pycache__/

14
.markdownlint.json Normal file
View File

@ -0,0 +1,14 @@
{
"MD013": false,
"MD024": {
"siblings_only": true
},
"MD025": false,
"MD033": false,
"MD034": false,
"MD036": false,
"MD041": false,
"MD046": {
"style": "fenced"
}
}

21
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,21 @@
{
"recommendations": [
"ms-python.python",
"charliermarsh.ruff",
"ms-python.mypy-type-checker",
"ms-toolsai.jupyter",
"ms-toolsai.jupyter-keymap",
"ms-toolsai.jupyter-renderers",
"ms-toolsai.vscode-jupyter-cell-tags",
"ms-toolsai.vscode-jupyter-slideshow",
"yzhang.markdown-all-in-one",
"davidanson.vscode-markdownlint",
"bierner.markdown-mermaid",
"bierner.markdown-preview-github-styles",
"eamodio.gitlens",
"github.vscode-pull-request-github",
"github.vscode-github-actions",
"redhat.vscode-yaml",
"editorconfig.editorconfig",
],
}

80
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,80 @@
{
"python.analysis.include": [
"libs/**",
"docs/**",
"cookbook/**"
],
"python.analysis.exclude": [
"**/node_modules",
"**/__pycache__",
"**/.pytest_cache",
"**/.*",
"_dist/**",
"docs/_build/**",
"docs/api_reference/_build/**"
],
"python.analysis.autoImportCompletions": true,
"python.analysis.typeCheckingMode": "basic",
"python.testing.cwd": "${workspaceFolder}",
"python.linting.enabled": true,
"python.linting.ruffEnabled": true,
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit",
"source.fixAll": "explicit"
},
"editor.defaultFormatter": "charliermarsh.ruff"
},
"editor.rulers": [
88
],
"editor.tabSize": 4,
"editor.insertSpaces": true,
"editor.trimAutoWhitespace": true,
"files.trimTrailingWhitespace": true,
"files.insertFinalNewline": true,
"files.exclude": {
"**/__pycache__": true,
"**/.pytest_cache": true,
"**/*.pyc": true,
"**/.mypy_cache": true,
"**/.ruff_cache": true,
"_dist/**": true,
"docs/_build/**": true,
"docs/api_reference/_build/**": true,
"**/node_modules": true,
"**/.git": false
},
"search.exclude": {
"**/__pycache__": true,
"**/*.pyc": true,
"_dist/**": true,
"docs/_build/**": true,
"docs/api_reference/_build/**": true,
"**/node_modules": true,
"**/.git": true,
"uv.lock": true,
"yarn.lock": true
},
"git.autofetch": true,
"git.enableSmartCommit": true,
"jupyter.askForKernelRestart": false,
"jupyter.interactiveWindow.textEditor.executeSelection": true,
"[markdown]": {
"editor.wordWrap": "on",
"editor.quickSuggestions": {
"comments": "off",
"strings": "off",
"other": "off"
}
},
"[yaml]": {
"editor.tabSize": 2,
"editor.insertSpaces": true
},
"[json]": {
"editor.tabSize": 2,
"editor.insertSpaces": true
},
}

View File

@ -41,6 +41,7 @@ docs_linkcheck:
## api_docs_build: Build the API Reference documentation.
api_docs_build: clean
@echo "📖 Building API Reference documentation..."
uv pip install -e libs/cli
uv run --group docs python docs/api_reference/create_api_rst.py
cd docs/api_reference && uv run --group docs make html
uv run --group docs python docs/api_reference/scripts/custom_formatter.py docs/api_reference/_build/html/

View File

@ -11,6 +11,7 @@ When building such applications developers should remember to follow good securi
* [**Defense in Depth**](https://en.wikipedia.org/wiki/Defense_in_depth_(computing)): No security technique is perfect. Fine-tuning and good chain design can reduce, but not eliminate, the odds that a Large Language Model (LLM) may make a mistake. It's best to combine multiple layered security approaches rather than relying on any single layer of defense to ensure security. For example: use both read-only permissions and sandboxing to ensure that LLMs are only able to access data that is explicitly meant for them to use.
Risks of not doing so include, but are not limited to:
* Data corruption or loss.
* Unauthorized access to confidential information.
* Compromised performance or availability of critical resources.
@ -45,39 +46,39 @@ Before reporting a vulnerability, please review:
The following packages and repositories are eligible for bug bounties:
- langchain-core
- langchain (see exceptions)
- langchain-community (see exceptions)
- langgraph
- langserve
* langchain-core
* langchain (see exceptions)
* langchain-community (see exceptions)
* langgraph
* langserve
### Out of Scope Targets
All out of scope targets defined by huntr as well as:
- **langchain-experimental**: This repository is for experimental code and is not
* **langchain-experimental**: This repository is for experimental code and is not
eligible for bug bounties (see [package warning](https://pypi.org/project/langchain-experimental/)), bug reports to it will be marked as interesting or waste of
time and published with no bounty attached.
- **tools**: Tools in either langchain or langchain-community are not eligible for bug
* **tools**: Tools in either langchain or langchain-community are not eligible for bug
bounties. This includes the following directories
- libs/langchain/langchain/tools
- libs/community/langchain_community/tools
- Please review the [Best Practices](#best-practices)
* libs/langchain/langchain/tools
* libs/community/langchain_community/tools
* Please review the [Best Practices](#best-practices)
for more details, but generally tools interact with the real world. Developers are
expected to understand the security implications of their code and are responsible
for the security of their tools.
- Code documented with security notices. This will be decided on a case by
* Code documented with security notices. This will be decided on a case by
case basis, but likely will not be eligible for a bounty as the code is already
documented with guidelines for developers that should be followed for making their
application secure.
- Any LangSmith related repositories or APIs (see [Reporting LangSmith Vulnerabilities](#reporting-langsmith-vulnerabilities)).
* Any LangSmith related repositories or APIs (see [Reporting LangSmith Vulnerabilities](#reporting-langsmith-vulnerabilities)).
## Reporting LangSmith Vulnerabilities
Please report security vulnerabilities associated with LangSmith by email to `security@langchain.dev`.
- LangSmith site: https://smith.langchain.com
- SDK client: https://github.com/langchain-ai/langsmith-sdk
* LangSmith site: [https://smith.langchain.com](https://smith.langchain.com)
* SDK client: [https://github.com/langchain-ai/langsmith-sdk](https://github.com/langchain-ai/langsmith-sdk)
### Other Security Concerns

View File

@ -34,7 +34,7 @@
"tools = [multiply, exponentiate, add]\n",
"\n",
"gpt35 = ChatOpenAI(model=\"gpt-3.5-turbo-0125\", temperature=0).bind_tools(tools)\n",
"claude3 = ChatAnthropic(model=\"claude-3-sonnet-20240229\").bind_tools(tools)\n",
"claude3 = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\").bind_tools(tools)\n",
"llm_with_tools = gpt35.configurable_alternatives(\n",
" ConfigurableField(id=\"llm\"), default_key=\"gpt35\", claude3=claude3\n",
")"
@ -113,14 +113,15 @@
{
"data": {
"text/plain": [
"{'messages': [HumanMessage(content=\"what's 3 plus 5 raised to the 2.743. also what's 17.24 - 918.1241\"),\n",
" AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_6yMU2WsS4Bqgi1WxFHxtfJRc', 'function': {'arguments': '{\"x\": 8, \"y\": 2.743}', 'name': 'exponentiate'}, 'type': 'function'}, {'id': 'call_GAL3dQiKFF9XEV0RrRLPTvVp', 'function': {'arguments': '{\"x\": 17.24, \"y\": -918.1241}', 'name': 'add'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 58, 'prompt_tokens': 168, 'total_tokens': 226}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': 'fp_b28b39ffa8', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-528302fc-7acf-4c11-82c4-119ccf40c573-0', tool_calls=[{'name': 'exponentiate', 'args': {'x': 8, 'y': 2.743}, 'id': 'call_6yMU2WsS4Bqgi1WxFHxtfJRc'}, {'name': 'add', 'args': {'x': 17.24, 'y': -918.1241}, 'id': 'call_GAL3dQiKFF9XEV0RrRLPTvVp'}]),\n",
" ToolMessage(content='300.03770462067547', tool_call_id='call_6yMU2WsS4Bqgi1WxFHxtfJRc'),\n",
" ToolMessage(content='-900.8841', tool_call_id='call_GAL3dQiKFF9XEV0RrRLPTvVp'),\n",
" AIMessage(content='The result of \\\\(3 + 5^{2.743}\\\\) is approximately 300.04, and the result of \\\\(17.24 - 918.1241\\\\) is approximately -900.88.', response_metadata={'token_usage': {'completion_tokens': 44, 'prompt_tokens': 251, 'total_tokens': 295}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': 'fp_b28b39ffa8', 'finish_reason': 'stop', 'logprobs': None}, id='run-d1161669-ed09-4b18-94bd-6d8530df5aa8-0')]}"
"{'messages': [HumanMessage(content=\"what's 3 plus 5 raised to the 2.743. also what's 17.24 - 918.1241\", additional_kwargs={}, response_metadata={}),\n",
" AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_xuNXwm2P6U2Pp2pAbC1sdIBz', 'function': {'arguments': '{\"x\": 3, \"y\": 5}', 'name': 'add'}, 'type': 'function'}, {'id': 'call_0pImUJUDlYa5zfBcxxuvWyYS', 'function': {'arguments': '{\"x\": 8, \"y\": 2.743}', 'name': 'exponentiate'}, 'type': 'function'}, {'id': 'call_yaownQ9TZK0dkqD1KSFyax4H', 'function': {'arguments': '{\"x\": 17.24, \"y\": -918.1241}', 'name': 'add'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 75, 'prompt_tokens': 131, 'total_tokens': 206, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': None, 'id': 'chatcmpl-ByJm2qxSWU3oTTSZQv64J4XQKZhA6', 'service_tier': 'default', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run--35fad027-47f7-44d3-aa8b-99f4fc24098c-0', tool_calls=[{'name': 'add', 'args': {'x': 3, 'y': 5}, 'id': 'call_xuNXwm2P6U2Pp2pAbC1sdIBz', 'type': 'tool_call'}, {'name': 'exponentiate', 'args': {'x': 8, 'y': 2.743}, 'id': 'call_0pImUJUDlYa5zfBcxxuvWyYS', 'type': 'tool_call'}, {'name': 'add', 'args': {'x': 17.24, 'y': -918.1241}, 'id': 'call_yaownQ9TZK0dkqD1KSFyax4H', 'type': 'tool_call'}], usage_metadata={'input_tokens': 131, 'output_tokens': 75, 'total_tokens': 206, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}),\n",
" ToolMessage(content='8.0', tool_call_id='call_xuNXwm2P6U2Pp2pAbC1sdIBz'),\n",
" ToolMessage(content='300.03770462067547', tool_call_id='call_0pImUJUDlYa5zfBcxxuvWyYS'),\n",
" ToolMessage(content='-900.8841', tool_call_id='call_yaownQ9TZK0dkqD1KSFyax4H'),\n",
" AIMessage(content='The results are:\\n1. 3 plus 5 is 8.\\n2. 5 raised to the power of 2.743 is approximately 300.04.\\n3. 17.24 minus 918.1241 is approximately -900.88.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 55, 'prompt_tokens': 236, 'total_tokens': 291, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-3.5-turbo-0125', 'system_fingerprint': None, 'id': 'chatcmpl-ByJm345MYnpowGS90iAZAlSs7haed', 'service_tier': 'default', 'finish_reason': 'stop', 'logprobs': None}, id='run--5fa66d47-d80e-45d0-9c32-31348c735d72-0', usage_metadata={'input_tokens': 236, 'output_tokens': 55, 'total_tokens': 291, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})]}"
]
},
"execution_count": 4,
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
@ -146,17 +147,17 @@
{
"data": {
"text/plain": [
"{'messages': [HumanMessage(content=\"what's 3 plus 5 raised to the 2.743. also what's 17.24 - 918.1241\"),\n",
" AIMessage(content=[{'text': \"Okay, let's break this down into two parts:\", 'type': 'text'}, {'id': 'toolu_01DEhqcXkXTtzJAiZ7uMBeDC', 'input': {'x': 3, 'y': 5}, 'name': 'add', 'type': 'tool_use'}], response_metadata={'id': 'msg_01AkLGH8sxMHaH15yewmjwkF', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 450, 'output_tokens': 81}}, id='run-f35bfae8-8ded-4f8a-831b-0940d6ad16b6-0', tool_calls=[{'name': 'add', 'args': {'x': 3, 'y': 5}, 'id': 'toolu_01DEhqcXkXTtzJAiZ7uMBeDC'}]),\n",
" ToolMessage(content='8.0', tool_call_id='toolu_01DEhqcXkXTtzJAiZ7uMBeDC'),\n",
" AIMessage(content=[{'id': 'toolu_013DyMLrvnrto33peAKMGMr1', 'input': {'x': 8.0, 'y': 2.743}, 'name': 'exponentiate', 'type': 'tool_use'}], response_metadata={'id': 'msg_015Fmp8aztwYcce2JDAFfce3', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 545, 'output_tokens': 75}}, id='run-48aaeeeb-a1e5-48fd-a57a-6c3da2907b47-0', tool_calls=[{'name': 'exponentiate', 'args': {'x': 8.0, 'y': 2.743}, 'id': 'toolu_013DyMLrvnrto33peAKMGMr1'}]),\n",
" ToolMessage(content='300.03770462067547', tool_call_id='toolu_013DyMLrvnrto33peAKMGMr1'),\n",
" AIMessage(content=[{'text': 'So 3 plus 5 raised to the 2.743 power is 300.04.\\n\\nFor the second part:', 'type': 'text'}, {'id': 'toolu_01UTmMrGTmLpPrPCF1rShN46', 'input': {'x': 17.24, 'y': -918.1241}, 'name': 'add', 'type': 'tool_use'}], response_metadata={'id': 'msg_015TkhfRBENPib2RWAxkieH6', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'input_tokens': 638, 'output_tokens': 105}}, id='run-45fb62e3-d102-4159-881d-241c5dbadeed-0', tool_calls=[{'name': 'add', 'args': {'x': 17.24, 'y': -918.1241}, 'id': 'toolu_01UTmMrGTmLpPrPCF1rShN46'}]),\n",
" ToolMessage(content='-900.8841', tool_call_id='toolu_01UTmMrGTmLpPrPCF1rShN46'),\n",
" AIMessage(content='Therefore, 17.24 - 918.1241 = -900.8841', response_metadata={'id': 'msg_01LgKnRuUcSyADCpxv9tPoYD', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 759, 'output_tokens': 24}}, id='run-1008254e-ccd1-497c-8312-9550dd77bd08-0')]}"
"{'messages': [HumanMessage(content=\"what's 3 plus 5 raised to the 2.743. also what's 17.24 - 918.1241\", additional_kwargs={}, response_metadata={}),\n",
" AIMessage(content=[{'text': \"I'll solve these calculations for you.\\n\\nFor the first part, I need to calculate 3 plus 5 raised to the power of 2.743.\\n\\nLet me break this down:\\n1) First, I'll calculate 5 raised to the power of 2.743\\n2) Then add 3 to the result\", 'type': 'text'}, {'id': 'toolu_01L1mXysBQtpPLQ2AZTaCGmE', 'input': {'x': 5, 'y': 2.743}, 'name': 'exponentiate', 'type': 'tool_use'}], additional_kwargs={}, response_metadata={'id': 'msg_01HCbDmuzdg9ATMyKbnecbEE', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 563, 'output_tokens': 146, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--9f6469fb-bcbb-4c1c-9eec-79f6979c38e6-0', tool_calls=[{'name': 'exponentiate', 'args': {'x': 5, 'y': 2.743}, 'id': 'toolu_01L1mXysBQtpPLQ2AZTaCGmE', 'type': 'tool_call'}], usage_metadata={'input_tokens': 563, 'output_tokens': 146, 'total_tokens': 709, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}),\n",
" ToolMessage(content='82.65606421491815', tool_call_id='toolu_01L1mXysBQtpPLQ2AZTaCGmE'),\n",
" AIMessage(content=[{'text': \"Now I'll add 3 to this result:\", 'type': 'text'}, {'id': 'toolu_01NARC83e9obV35mZ6jYzBiN', 'input': {'x': 3, 'y': 82.65606421491815}, 'name': 'add', 'type': 'tool_use'}], additional_kwargs={}, response_metadata={'id': 'msg_01ELwyCtVLeGC685PUFqmdz2', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 727, 'output_tokens': 87, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--d5af3d7c-e8b7-4cc2-997a-ad2dafd08751-0', tool_calls=[{'name': 'add', 'args': {'x': 3, 'y': 82.65606421491815}, 'id': 'toolu_01NARC83e9obV35mZ6jYzBiN', 'type': 'tool_call'}], usage_metadata={'input_tokens': 727, 'output_tokens': 87, 'total_tokens': 814, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}),\n",
" ToolMessage(content='85.65606421491815', tool_call_id='toolu_01NARC83e9obV35mZ6jYzBiN'),\n",
" AIMessage(content=[{'text': \"For the second part, you asked for 17.24 - 918.1241. I don't have a subtraction function available, but I can rewrite this as adding a negative number: 17.24 + (-918.1241)\", 'type': 'text'}, {'id': 'toolu_01Q6fLcZkBWZpMPCZ55WXR3N', 'input': {'x': 17.24, 'y': -918.1241}, 'name': 'add', 'type': 'tool_use'}], additional_kwargs={}, response_metadata={'id': 'msg_01WkmDwUxWjjaKGnTtdLGJnN', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'tool_use', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 832, 'output_tokens': 130, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--39a6fbda-4c81-47a6-b361-524bd4ee5823-0', tool_calls=[{'name': 'add', 'args': {'x': 17.24, 'y': -918.1241}, 'id': 'toolu_01Q6fLcZkBWZpMPCZ55WXR3N', 'type': 'tool_call'}], usage_metadata={'input_tokens': 832, 'output_tokens': 130, 'total_tokens': 962, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}),\n",
" ToolMessage(content='-900.8841', tool_call_id='toolu_01Q6fLcZkBWZpMPCZ55WXR3N'),\n",
" AIMessage(content='So, the answers are:\\n1) 3 plus 5 raised to the 2.743 = 85.65606421491815\\n2) 17.24 - 918.1241 = -900.8841', additional_kwargs={}, response_metadata={'id': 'msg_015Yoc62CvdJbANGFouiQ6AQ', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 978, 'output_tokens': 58, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--174c0882-6180-47ea-8f63-d7b747302327-0', usage_metadata={'input_tokens': 978, 'output_tokens': 58, 'total_tokens': 1036, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})]}"
]
},
"execution_count": 5,
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
@ -177,7 +178,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -191,7 +192,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.4"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -202,6 +202,12 @@ def _load_package_modules(
if file_path.name.startswith("_"):
continue
if "integration_template" in file_path.parts:
continue
if "project_template" in file_path.parts:
continue
relative_module_name = file_path.relative_to(package_path)
# Skip if any module part starts with an underscore
@ -495,16 +501,7 @@ def _package_namespace(package_name: str) -> str:
def _package_dir(package_name: str = "langchain") -> Path:
"""Return the path to the directory containing the documentation."""
if package_name in (
"langchain",
"langchain_v1",
"experimental",
"community",
"core",
"cli",
"text-splitters",
"standard-tests",
):
if (ROOT_DIR / "libs" / package_name).exists():
return ROOT_DIR / "libs" / package_name / _package_namespace(package_name)
else:
return (
@ -666,18 +663,12 @@ def main(dirs: Optional[list] = None) -> None:
print("Starting to build API reference files.")
if not dirs:
dirs = [
dir_
for dir_ in os.listdir(ROOT_DIR / "libs")
if dir_ not in ("cli", "partners", "packages.yml")
and "pyproject.toml" in os.listdir(ROOT_DIR / "libs" / dir_)
p.parent.name
for p in (ROOT_DIR / "libs").rglob("pyproject.toml")
# Exclude packages that are not directly under libs/ or libs/partners/
if p.parent.parent.name in ("libs", "partners")
]
dirs += [
dir_
for dir_ in os.listdir(ROOT_DIR / "libs" / "partners")
if os.path.isdir(ROOT_DIR / "libs" / "partners" / dir_)
and "pyproject.toml" in os.listdir(ROOT_DIR / "libs" / "partners" / dir_)
]
for dir_ in dirs:
for dir_ in sorted(dirs):
# Skip any hidden directories
# Some of these could be present by mistake in the code base
# e.g., .pytest_cache from running tests from the wrong location.
@ -688,7 +679,7 @@ def main(dirs: Optional[list] = None) -> None:
print("Building package:", dir_)
_build_rst_file(package_name=dir_)
_build_index(dirs)
_build_index(sorted(dirs))
print("API reference files built.")

View File

@ -1098,4 +1098,3 @@ codes also allow CTRL to predict which parts of the training data are most
likely given a sequence. This provides a potential method for analyzing large
amounts of data via model-based source attribution. We have released multiple
full-sized, pretrained versions of CTRL at https://github.com/salesforce/ctrl.

View File

@ -14,4 +14,3 @@ This process is vital for building reliable applications.
- It allows you to track results over time and automatically run your evaluators on a schedule or as part of CI/Code
To learn more, check out [this LangSmith guide](https://docs.smith.langchain.com/concepts/evaluation).

View File

@ -119,7 +119,7 @@ from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-3-sonnet-20240229")
model = ChatAnthropic(model="claude-3-7-sonnet-20250219")
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
parser = StrOutputParser()

View File

@ -56,32 +56,13 @@
"text": [
"zzzz....\n",
"Hi! I just woke up. Your llm is starting\n",
"Sync handler being called in a `thread_pool_executor`: token: Here\n",
"Sync handler being called in a `thread_pool_executor`: token: 's\n",
"Sync handler being called in a `thread_pool_executor`: token: a\n",
"Sync handler being called in a `thread_pool_executor`: token: little\n",
"Sync handler being called in a `thread_pool_executor`: token: joke\n",
"Sync handler being called in a `thread_pool_executor`: token: for\n",
"Sync handler being called in a `thread_pool_executor`: token: you\n",
"Sync handler being called in a `thread_pool_executor`: token: :\n",
"Sync handler being called in a `thread_pool_executor`: token: \n",
"Sync handler being called in a `thread_pool_executor`: token: Why\n",
"Sync handler being called in a `thread_pool_executor`: token: don't scientists trust atoms?\n",
"\n",
"Why\n",
"Sync handler being called in a `thread_pool_executor`: token: can\n",
"Sync handler being called in a `thread_pool_executor`: token: 't\n",
"Sync handler being called in a `thread_pool_executor`: token: a\n",
"Sync handler being called in a `thread_pool_executor`: token: bicycle\n",
"Sync handler being called in a `thread_pool_executor`: token: stan\n",
"Sync handler being called in a `thread_pool_executor`: token: d up\n",
"Sync handler being called in a `thread_pool_executor`: token: by\n",
"Sync handler being called in a `thread_pool_executor`: token: itself\n",
"Sync handler being called in a `thread_pool_executor`: token: ?\n",
"Sync handler being called in a `thread_pool_executor`: token: Because\n",
"Sync handler being called in a `thread_pool_executor`: token: it\n",
"Sync handler being called in a `thread_pool_executor`: token: 's\n",
"Sync handler being called in a `thread_pool_executor`: token: two\n",
"Sync handler being called in a `thread_pool_executor`: token: -\n",
"Sync handler being called in a `thread_pool_executor`: token: tire\n",
"Because they make up\n",
"Sync handler being called in a `thread_pool_executor`: token: everything!\n",
"Sync handler being called in a `thread_pool_executor`: token: \n",
"zzzz....\n",
"Hi! I just woke up. Your llm is ending\n"
]
@ -89,10 +70,10 @@
{
"data": {
"text/plain": [
"LLMResult(generations=[[ChatGeneration(text=\"Here's a little joke for you:\\n\\nWhy can't a bicycle stand up by itself? Because it's two-tire\", message=AIMessage(content=\"Here's a little joke for you:\\n\\nWhy can't a bicycle stand up by itself? Because it's two-tire\", id='run-8afc89e8-02c0-4522-8480-d96977240bd4-0'))]], llm_output={}, run=[RunInfo(run_id=UUID('8afc89e8-02c0-4522-8480-d96977240bd4'))])"
"LLMResult(generations=[[ChatGeneration(text=\"Why don't scientists trust atoms?\\n\\nBecause they make up everything!\", message=AIMessage(content=\"Why don't scientists trust atoms?\\n\\nBecause they make up everything!\", additional_kwargs={}, response_metadata={'model_name': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None}, id='run--a596349d-8a7c-45fe-8691-bb1f9cfd6c08-0', usage_metadata={'input_tokens': 11, 'output_tokens': 17, 'total_tokens': 28, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}}))]], llm_output={}, run=[RunInfo(run_id=UUID('a596349d-8a7c-45fe-8691-bb1f9cfd6c08'))], type='LLMResult')"
]
},
"execution_count": 2,
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
@ -134,7 +115,7 @@
"# To enable streaming, we pass in `streaming=True` to the ChatModel constructor\n",
"# Additionally, we pass in a list with our custom handler\n",
"chat = ChatAnthropic(\n",
" model=\"claude-3-sonnet-20240229\",\n",
" model=\"claude-3-7-sonnet-20250219\",\n",
" max_tokens=25,\n",
" streaming=True,\n",
" callbacks=[MyCustomSyncHandler(), MyCustomAsyncHandler()],\n",
@ -157,7 +138,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -171,7 +152,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.6"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -49,22 +49,28 @@
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Error in LoggingHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Chain RunnableSequence started\n",
"Chain ChatPromptTemplate started\n",
"Chain ended, outputs: messages=[HumanMessage(content='What is 1 + 2?')]\n",
"Chain ended, outputs: messages=[HumanMessage(content='What is 1 + 2?', additional_kwargs={}, response_metadata={})]\n",
"Chat model started\n",
"Chat model ended, response: generations=[[ChatGeneration(text='1 + 2 = 3', message=AIMessage(content='1 + 2 = 3', response_metadata={'id': 'msg_01NTYMsH9YxkoWsiPYs4Lemn', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}}, id='run-d6bcfd72-9c94-466d-bac0-f39e456ad6e3-0'))]] llm_output={'id': 'msg_01NTYMsH9YxkoWsiPYs4Lemn', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}} run=None\n",
"Chain ended, outputs: content='1 + 2 = 3' response_metadata={'id': 'msg_01NTYMsH9YxkoWsiPYs4Lemn', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}} id='run-d6bcfd72-9c94-466d-bac0-f39e456ad6e3-0'\n"
"Chat model ended, response: generations=[[ChatGeneration(text='The sum of 1 + 2 is 3.', message=AIMessage(content='The sum of 1 + 2 is 3.', additional_kwargs={}, response_metadata={'id': 'msg_01F1qPrmBD9igfzHdqVipmKX', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 17, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--71edddf3-2474-42dc-ad43-fadb4882c3c8-0', usage_metadata={'input_tokens': 16, 'output_tokens': 17, 'total_tokens': 33, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}))]] llm_output={'id': 'msg_01F1qPrmBD9igfzHdqVipmKX', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 17, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'} run=None type='LLMResult'\n",
"Chain ended, outputs: content='The sum of 1 + 2 is 3.' additional_kwargs={} response_metadata={'id': 'msg_01F1qPrmBD9igfzHdqVipmKX', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 17, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'} id='run--71edddf3-2474-42dc-ad43-fadb4882c3c8-0' usage_metadata={'input_tokens': 16, 'output_tokens': 17, 'total_tokens': 33, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}\n"
]
},
{
"data": {
"text/plain": [
"AIMessage(content='1 + 2 = 3', response_metadata={'id': 'msg_01NTYMsH9YxkoWsiPYs4Lemn', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}}, id='run-d6bcfd72-9c94-466d-bac0-f39e456ad6e3-0')"
"AIMessage(content='The sum of 1 + 2 is 3.', additional_kwargs={}, response_metadata={'id': 'msg_01F1qPrmBD9igfzHdqVipmKX', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 17, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--71edddf3-2474-42dc-ad43-fadb4882c3c8-0', usage_metadata={'input_tokens': 16, 'output_tokens': 17, 'total_tokens': 33, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})"
]
},
"execution_count": 1,
@ -101,7 +107,7 @@
"\n",
"\n",
"callbacks = [LoggingHandler()]\n",
"llm = ChatAnthropic(model=\"claude-3-sonnet-20240229\")\n",
"llm = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\")\n",
"prompt = ChatPromptTemplate.from_template(\"What is 1 + {number}?\")\n",
"\n",
"chain = prompt | llm\n",
@ -127,7 +133,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -141,7 +147,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.4"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -52,16 +52,16 @@
"output_type": "stream",
"text": [
"Chat model started\n",
"Chat model ended, response: generations=[[ChatGeneration(text='1 + 2 = 3', message=AIMessage(content='1 + 2 = 3', response_metadata={'id': 'msg_01CdKsRmeS9WRb8BWnHDEHm7', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}}, id='run-2d7fdf2a-7405-4e17-97c0-67e6b2a65305-0'))]] llm_output={'id': 'msg_01CdKsRmeS9WRb8BWnHDEHm7', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}} run=None\n"
"Chat model ended, response: generations=[[ChatGeneration(text='1 + 2 = 3', message=AIMessage(content='1 + 2 = 3', additional_kwargs={}, response_metadata={'id': 'msg_01DQMbSk263KpY2vouHM5gsC', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 13, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--ab896e4e-c3fd-48b1-a41a-b6b525cbc041-0', usage_metadata={'input_tokens': 16, 'output_tokens': 13, 'total_tokens': 29, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}))]] llm_output={'id': 'msg_01DQMbSk263KpY2vouHM5gsC', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 13, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'} run=None type='LLMResult'\n"
]
},
{
"data": {
"text/plain": [
"AIMessage(content='1 + 2 = 3', response_metadata={'id': 'msg_01CdKsRmeS9WRb8BWnHDEHm7', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}}, id='run-2d7fdf2a-7405-4e17-97c0-67e6b2a65305-0')"
"AIMessage(content='1 + 2 = 3', additional_kwargs={}, response_metadata={'id': 'msg_01DQMbSk263KpY2vouHM5gsC', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 13, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--ab896e4e-c3fd-48b1-a41a-b6b525cbc041-0', usage_metadata={'input_tokens': 16, 'output_tokens': 13, 'total_tokens': 29, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})"
]
},
"execution_count": 18,
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
@ -95,7 +95,7 @@
"\n",
"\n",
"callbacks = [LoggingHandler()]\n",
"llm = ChatAnthropic(model=\"claude-3-sonnet-20240229\", callbacks=callbacks)\n",
"llm = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\", callbacks=callbacks)\n",
"prompt = ChatPromptTemplate.from_template(\"What is 1 + {number}?\")\n",
"\n",
"chain = prompt | llm\n",
@ -119,7 +119,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -133,7 +133,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.4"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -42,25 +42,31 @@
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Error in LoggingHandler.on_chain_start callback: AttributeError(\"'NoneType' object has no attribute 'get'\")\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Chain RunnableSequence started\n",
"Chain ChatPromptTemplate started\n",
"Chain ended, outputs: messages=[HumanMessage(content='What is 1 + 2?')]\n",
"Chain ended, outputs: messages=[HumanMessage(content='What is 1 + 2?', additional_kwargs={}, response_metadata={})]\n",
"Chat model started\n",
"Chat model ended, response: generations=[[ChatGeneration(text='1 + 2 = 3', message=AIMessage(content='1 + 2 = 3', response_metadata={'id': 'msg_01D8Tt5FdtBk5gLTfBPm2tac', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}}, id='run-bb0dddd8-85f3-4e6b-8553-eaa79f859ef8-0'))]] llm_output={'id': 'msg_01D8Tt5FdtBk5gLTfBPm2tac', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}} run=None\n",
"Chain ended, outputs: content='1 + 2 = 3' response_metadata={'id': 'msg_01D8Tt5FdtBk5gLTfBPm2tac', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}} id='run-bb0dddd8-85f3-4e6b-8553-eaa79f859ef8-0'\n"
"Chat model ended, response: generations=[[ChatGeneration(text='1 + 2 = 3', message=AIMessage(content='1 + 2 = 3', additional_kwargs={}, response_metadata={'id': 'msg_019ieJt8K32iC77qBbQmSa9m', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 13, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--2f596356-99c9-45ef-94ff-fb170072abdf-0', usage_metadata={'input_tokens': 16, 'output_tokens': 13, 'total_tokens': 29, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}))]] llm_output={'id': 'msg_019ieJt8K32iC77qBbQmSa9m', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 13, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'} run=None type='LLMResult'\n",
"Chain ended, outputs: content='1 + 2 = 3' additional_kwargs={} response_metadata={'id': 'msg_019ieJt8K32iC77qBbQmSa9m', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 13, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'} id='run--2f596356-99c9-45ef-94ff-fb170072abdf-0' usage_metadata={'input_tokens': 16, 'output_tokens': 13, 'total_tokens': 29, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}}\n"
]
},
{
"data": {
"text/plain": [
"AIMessage(content='1 + 2 = 3', response_metadata={'id': 'msg_01D8Tt5FdtBk5gLTfBPm2tac', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 13}}, id='run-bb0dddd8-85f3-4e6b-8553-eaa79f859ef8-0')"
"AIMessage(content='1 + 2 = 3', additional_kwargs={}, response_metadata={'id': 'msg_019ieJt8K32iC77qBbQmSa9m', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 13, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--2f596356-99c9-45ef-94ff-fb170072abdf-0', usage_metadata={'input_tokens': 16, 'output_tokens': 13, 'total_tokens': 29, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})"
]
},
"execution_count": 4,
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
@ -94,7 +100,7 @@
"\n",
"\n",
"callbacks = [LoggingHandler()]\n",
"llm = ChatAnthropic(model=\"claude-3-sonnet-20240229\")\n",
"llm = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\")\n",
"prompt = ChatPromptTemplate.from_template(\"What is 1 + {number}?\")\n",
"\n",
"chain = prompt | llm\n",
@ -118,7 +124,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -132,7 +138,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.5"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -49,33 +49,13 @@
"name": "stdout",
"output_type": "stream",
"text": [
"My custom handler, token: Here\n",
"My custom handler, token: 's\n",
"My custom handler, token: a\n",
"My custom handler, token: bear\n",
"My custom handler, token: joke\n",
"My custom handler, token: for\n",
"My custom handler, token: you\n",
"My custom handler, token: :\n",
"My custom handler, token: \n",
"My custom handler, token: Why\n",
"My custom handler, token: don't bears wear shoes?\n",
"\n",
"Why\n",
"My custom handler, token: di\n",
"My custom handler, token: d the\n",
"My custom handler, token: bear\n",
"My custom handler, token: dissol\n",
"My custom handler, token: ve\n",
"My custom handler, token: in\n",
"My custom handler, token: water\n",
"My custom handler, token: ?\n",
"My custom handler, token: \n",
"Because\n",
"My custom handler, token: it\n",
"My custom handler, token: was\n",
"My custom handler, token: a\n",
"My custom handler, token: polar\n",
"My custom handler, token: bear\n",
"My custom handler, token: !\n"
"Because they\n",
"My custom handler, token: prefer to go bear-foot!\n",
"My custom handler, token: \n"
]
}
],
@ -95,7 +75,7 @@
"# To enable streaming, we pass in `streaming=True` to the ChatModel constructor\n",
"# Additionally, we pass in our custom handler as a list to the callbacks parameter\n",
"model = ChatAnthropic(\n",
" model=\"claude-3-sonnet-20240229\", streaming=True, callbacks=[MyCustomHandler()]\n",
" model=\"claude-3-7-sonnet-20250219\", streaming=True, callbacks=[MyCustomHandler()]\n",
")\n",
"\n",
"chain = prompt | model\n",
@ -119,7 +99,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -133,7 +113,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.5"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -35,7 +35,7 @@
"\n",
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"llm = ChatAnthropic(model=\"claude-3-sonnet-20240229\")"
"llm = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\")"
]
},
{
@ -47,10 +47,10 @@
{
"data": {
"text/plain": [
"\"According to the context provided, Egypt's population in 2024 is estimated to be about 111 million.\""
"\"Egypt's population in 2024 is about 111 million.\""
]
},
"execution_count": 10,
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
@ -142,13 +142,10 @@
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"What\n",
" is\n",
" the\n",
" population\n",
" of\n",
" Egypt\n",
"?\n"
" is the population of Egypt?\n",
"\n"
]
}
],
@ -168,9 +165,9 @@
],
"metadata": {
"kernelspec": {
"display_name": "poetry-venv-2",
"display_name": "langchain",
"language": "python",
"name": "poetry-venv-2"
"name": "python3"
},
"language_info": {
"codemirror_mode": {
@ -182,7 +179,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.1"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -42,7 +42,7 @@
"\n",
"from langchain_anthropic.chat_models import ChatAnthropic\n",
"\n",
"model = ChatAnthropic(model_name=\"claude-3-sonnet-20240229\", temperature=0)"
"model = ChatAnthropic(model_name=\"claude-3-7-sonnet-20250219\", temperature=0)"
]
},
{
@ -200,7 +200,7 @@
{
"data": {
"text/plain": [
"People(people=[Person(name='Anna', height_in_meters=1.83)])"
"People(people=[Person(name='Anna', height_in_meters=1.8288)])"
]
},
"execution_count": 5,
@ -242,7 +242,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": null,
"id": "b1f11912-c1bb-4a2a-a482-79bf3996961f",
"metadata": {
"execution": {
@ -359,14 +359,6 @@
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/bagatur/langchain/.venv/lib/python3.11/site-packages/pydantic/_internal/_fields.py:201: UserWarning: Field name \"schema\" in \"PromptInput\" shadows an attribute in parent \"BaseModel\"\n",
" warnings.warn(\n"
]
},
{
"data": {
"text/plain": [
@ -397,7 +389,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -411,7 +403,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -23,11 +23,11 @@
{
"data": {
"text/plain": [
"[HumanMessage(content='example input', name='example_user', id='2'),\n",
" HumanMessage(content='real input', name='bob', id='4')]"
"[HumanMessage(content='example input', additional_kwargs={}, response_metadata={}, name='example_user', id='2'),\n",
" HumanMessage(content='real input', additional_kwargs={}, response_metadata={}, name='bob', id='4')]"
]
},
"execution_count": 1,
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
@ -60,12 +60,12 @@
{
"data": {
"text/plain": [
"[SystemMessage(content='you are a good assistant', id='1'),\n",
" HumanMessage(content='real input', name='bob', id='4'),\n",
" AIMessage(content='real output', name='alice', id='5')]"
"[SystemMessage(content='you are a good assistant', additional_kwargs={}, response_metadata={}, id='1'),\n",
" HumanMessage(content='real input', additional_kwargs={}, response_metadata={}, name='bob', id='4'),\n",
" AIMessage(content='real output', additional_kwargs={}, response_metadata={}, name='alice', id='5')]"
]
},
"execution_count": 2,
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
@ -83,12 +83,12 @@
{
"data": {
"text/plain": [
"[HumanMessage(content='example input', name='example_user', id='2'),\n",
" HumanMessage(content='real input', name='bob', id='4'),\n",
" AIMessage(content='real output', name='alice', id='5')]"
"[HumanMessage(content='example input', additional_kwargs={}, response_metadata={}, name='example_user', id='2'),\n",
" HumanMessage(content='real input', additional_kwargs={}, response_metadata={}, name='bob', id='4'),\n",
" AIMessage(content='real output', additional_kwargs={}, response_metadata={}, name='alice', id='5')]"
]
},
"execution_count": 3,
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
@ -126,10 +126,10 @@
{
"data": {
"text/plain": [
"AIMessage(content=[], response_metadata={'id': 'msg_01Wz7gBHahAwkZ1KCBNtXmwA', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 16, 'output_tokens': 3}}, id='run-b5d8a3fe-004f-4502-a071-a6c025031827-0', usage_metadata={'input_tokens': 16, 'output_tokens': 3, 'total_tokens': 19})"
"AIMessage(content=[], additional_kwargs={}, response_metadata={'id': 'msg_01At8GtCiJ79M29yvNwCiQaB', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 16, 'output_tokens': 3, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--b3db2b91-0edf-4c48-99e7-35e641b8229d-0', usage_metadata={'input_tokens': 16, 'output_tokens': 3, 'total_tokens': 19, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})"
]
},
"execution_count": 4,
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
@ -137,7 +137,7 @@
"source": [
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"llm = ChatAnthropic(model=\"claude-3-sonnet-20240229\", temperature=0)\n",
"llm = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\", temperature=0)\n",
"# Notice we don't pass in messages. This creates\n",
"# a RunnableLambda that takes messages as input\n",
"filter_ = filter_messages(exclude_names=[\"example_user\", \"example_assistant\"])\n",
@ -164,8 +164,9 @@
{
"data": {
"text/plain": [
"[HumanMessage(content='real input', name='bob', id='4'),\n",
" AIMessage(content='real output', name='alice', id='5')]"
"[SystemMessage(content='you are a good assistant', additional_kwargs={}, response_metadata={}, id='1'),\n",
" HumanMessage(content='real input', additional_kwargs={}, response_metadata={}, name='bob', id='4'),\n",
" AIMessage(content='real output', additional_kwargs={}, response_metadata={}, name='alice', id='5')]"
]
},
"execution_count": 6,
@ -190,9 +191,9 @@
],
"metadata": {
"kernelspec": {
"display_name": "poetry-venv-2",
"display_name": "langchain",
"language": "python",
"name": "poetry-venv-2"
"name": "python3"
},
"language_info": {
"codemirror_mode": {
@ -204,7 +205,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.1"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -97,20 +97,13 @@
"id": "6d5a0283-11f8-435b-b27b-7b18f7693592",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Note: you may need to restart the kernel to use updated packages.\n"
]
},
{
"data": {
"text/plain": [
"AIMessage(content=[], additional_kwargs={}, response_metadata={'id': 'msg_01KNGUMTuzBVfwNouLDpUMwf', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 84, 'output_tokens': 3}}, id='run-b908b198-9c24-450b-9749-9d4a8182937b-0', usage_metadata={'input_tokens': 84, 'output_tokens': 3, 'total_tokens': 87})"
"AIMessage(content='\\n\\nAs for the actual answer, LangChain is named for connecting (chaining) language models together with other components. And Harrison Chase is one of the co-founders of LangChain, not someone being chased! \\n\\nBut I like to think he\\'s running after runaway tokens that escaped from the embedding space. \"Come back here, you vectors!\"', additional_kwargs={}, response_metadata={'id': 'msg_018MF8xBrM1ztw69XTx3Uxcy', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 84, 'output_tokens': 80, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--caa1b9d6-a554-40ad-95cd-268938d8223b-0', usage_metadata={'input_tokens': 84, 'output_tokens': 80, 'total_tokens': 164, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})"
]
},
"execution_count": 9,
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
@ -118,7 +111,7 @@
"source": [
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"llm = ChatAnthropic(model=\"claude-3-sonnet-20240229\", temperature=0)\n",
"llm = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\", temperature=0)\n",
"# Notice we don't pass in messages. This creates\n",
"# a RunnableLambda that takes messages as input\n",
"merger = merge_message_runs()\n",
@ -150,7 +143,7 @@
" AIMessage(content='Well, I guess they thought \"WordRope\" and \"SentenceString\" just didn\\'t have the same ring to it!\\nWhy, he\\'s probably chasing after the last cup of coffee in the office!', additional_kwargs={}, response_metadata={})]"
]
},
"execution_count": 10,
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
@ -176,10 +169,10 @@
{
"data": {
"text/plain": [
"AIMessage(content='A convergent series is an infinite series whose partial sums approach a finite value as more terms are added. In other words, the sequence of partial sums has a limit.\\n\\nMore formally, an infinite series Σ an (where an are the terms of the series) is said to be convergent if the sequence of partial sums:\\n\\nS1 = a1\\nS2 = a1 + a2 \\nS3 = a1 + a2 + a3\\n...\\nSn = a1 + a2 + a3 + ... + an\\n...\\n\\nconverges to some finite number S as n goes to infinity. We write:\\n\\nlim n→∞ Sn = S\\n\\nThe finite number S is called the sum of the convergent infinite series.\\n\\nIf the sequence of partial sums does not approach any finite limit, the infinite series is said to be divergent.\\n\\nSome key properties:\\n- A series converges if and only if the sequence of its partial sums is a Cauchy sequence.\\n- Absolute/conditional convergence criteria help determine if a given series converges.\\n- Convergent series have many important applications in mathematics, physics, engineering etc.', additional_kwargs={}, response_metadata={'id': 'msg_01MfV6y2hep7ZNvDz24A36U4', 'model': 'claude-3-sonnet-20240229', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'input_tokens': 29, 'output_tokens': 267}}, id='run-9d925f58-021e-4bd0-94fc-f8f5e91010a4-0', usage_metadata={'input_tokens': 29, 'output_tokens': 267, 'total_tokens': 296})"
"AIMessage(content=\"# Definition of a Convergent Series\\n\\nA series is a sum of terms in a sequence, typically written as:\\n\\n$$\\\\sum_{n=1}^{\\\\infty} a_n = a_1 + a_2 + a_3 + \\\\ldots$$\\n\\nA series is called **convergent** if the sequence of partial sums approaches a finite limit.\\n\\n## Formal Definition\\n\\nLet's define the sequence of partial sums:\\n$$S_N = \\\\sum_{n=1}^{N} a_n = a_1 + a_2 + \\\\ldots + a_N$$\\n\\nA series $\\\\sum_{n=1}^{\\\\infty} a_n$ is convergent if and only if:\\n- The limit of the partial sums exists and is finite\\n- That is, there exists a finite number $S$ such that $\\\\lim_{N \\\\to \\\\infty} S_N = S$\\n\\nIf this limit exists, we say the series converges to $S$, and we write:\\n$$\\\\sum_{n=1}^{\\\\infty} a_n = S$$\\n\\nIf the limit doesn't exist or is infinite, the series is called divergent.\", additional_kwargs={}, response_metadata={'id': 'msg_018ypyi2MTjV6S7jCydSqDn9', 'model': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None, 'usage': {'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'input_tokens': 29, 'output_tokens': 273, 'server_tool_use': None, 'service_tier': 'standard'}, 'model_name': 'claude-3-7-sonnet-20250219'}, id='run--5de0ca29-d031-48f7-bc75-671eade20b74-0', usage_metadata={'input_tokens': 29, 'output_tokens': 273, 'total_tokens': 302, 'input_token_details': {'cache_read': 0, 'cache_creation': 0}})"
]
},
"execution_count": 14,
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
@ -203,7 +196,7 @@
"id": "51ba533a-43c7-4e5f-bd91-a4ec23ceeb34",
"metadata": {},
"source": [
"LangSmith Trace: https://smith.langchain.com/public/432150b6-9909-40a7-8ae7-944b7e657438/r/f4ad5fb2-4d38-42a6-b780-25f62617d53f"
"[LangSmith Trace](https://smith.langchain.com/public/432150b6-9909-40a7-8ae7-944b7e657438/r/f4ad5fb2-4d38-42a6-b780-25f62617d53f)"
]
},
{
@ -213,15 +206,15 @@
"source": [
"## API reference\n",
"\n",
"For a complete description of all arguments head to the API reference: https://python.langchain.com/api_reference/core/messages/langchain_core.messages.utils.merge_message_runs.html"
"For a complete description of all arguments head to the [API reference](https://python.langchain.com/api_reference/core/messages/langchain_core.messages.utils.merge_message_runs.html)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "poetry-venv-2",
"display_name": "langchain",
"language": "python",
"name": "poetry-venv-2"
"name": "python3"
},
"language_info": {
"codemirror_mode": {
@ -233,7 +226,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -23,17 +23,18 @@
{
"data": {
"text/plain": [
"{'token_usage': {'completion_tokens': 110,\n",
"{'token_usage': {'completion_tokens': 93,\n",
" 'prompt_tokens': 16,\n",
" 'total_tokens': 126,\n",
" 'total_tokens': 109,\n",
" 'completion_tokens_details': {'accepted_prediction_tokens': 0,\n",
" 'audio_tokens': 0,\n",
" 'reasoning_tokens': 0,\n",
" 'rejected_prediction_tokens': 0},\n",
" 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}},\n",
" 'model_name': 'gpt-4o-mini-2024-07-18',\n",
" 'system_fingerprint': 'fp_b8bc95a0ac',\n",
" 'id': 'chatcmpl-BDrISvLar6AqcZngBmhajFZXVc2u9',\n",
" 'system_fingerprint': 'fp_34a54ae93c',\n",
" 'id': 'chatcmpl-ByJtse6I3U1lmVyPscLCjzydCvfDO',\n",
" 'service_tier': 'default',\n",
" 'finish_reason': 'stop',\n",
" 'logprobs': None}"
]
@ -68,15 +69,17 @@
{
"data": {
"text/plain": [
"{'id': 'msg_01JHnvPqgERY7MZwrvfkmq52',\n",
" 'model': 'claude-3-5-sonnet-20241022',\n",
"{'id': 'msg_017S9H7GMwA5RdZ1wHxzXoeX',\n",
" 'model': 'claude-3-7-sonnet-20250219',\n",
" 'stop_reason': 'end_turn',\n",
" 'stop_sequence': None,\n",
" 'usage': {'cache_creation_input_tokens': 0,\n",
" 'cache_read_input_tokens': 0,\n",
" 'input_tokens': 17,\n",
" 'output_tokens': 221},\n",
" 'model_name': 'claude-3-5-sonnet-20241022'}"
" 'output_tokens': 180,\n",
" 'server_tool_use': None,\n",
" 'service_tier': 'standard'},\n",
" 'model_name': 'claude-3-7-sonnet-20250219'}"
]
},
"execution_count": 2,
@ -87,7 +90,7 @@
"source": [
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"llm = ChatAnthropic(model=\"claude-3-5-sonnet-latest\")\n",
"llm = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\")\n",
"msg = llm.invoke(\"What's the oldest known example of cuneiform\")\n",
"msg.response_metadata"
]
@ -173,7 +176,7 @@
"source": [
"from langchain_aws import ChatBedrockConverse\n",
"\n",
"llm = ChatBedrockConverse(model=\"anthropic.claude-3-sonnet-20240229-v1:0\")\n",
"llm = ChatBedrockConverse(model=\"anthropic.claude-3-7-sonnet-20250219-v1:0\")\n",
"msg = llm.invoke(\"What's the oldest known example of cuneiform\")\n",
"msg.response_metadata"
]
@ -301,7 +304,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -315,7 +318,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.4"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -61,7 +61,7 @@
"if \"ANTHROPIC_API_KEY\" not in os.environ:\n",
" os.environ[\"ANTHROPIC_API_KEY\"] = getpass()\n",
"\n",
"model = ChatAnthropic(model=\"claude-3-sonnet-20240229\", temperature=0)"
"model = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\", temperature=0)"
]
},
{
@ -93,7 +93,7 @@
{
"data": {
"text/plain": [
"\"Here's a bear joke for you:\\n\\nWhy did the bear dissolve in water?\\nBecause it was a polar bear!\""
"\"Why don't bears wear shoes?\\n\\nBecause they prefer to go bear-foot!\""
]
},
"execution_count": 3,
@ -128,7 +128,7 @@
{
"data": {
"text/plain": [
"'Haha, that\\'s a clever play on words! Using \"polar\" to imply the bear dissolved or became polar/polarized when put in water. Not the most hilarious joke ever, but it has a cute, groan-worthy pun that makes it mildly amusing. I appreciate a good pun or wordplay joke.'"
"'Yes, that\\'s a funny joke! It\\'s a classic pun that plays on the homophone pair \"bare-foot\" and \"bear-foot.\" The humor comes from:\\n\\n1. The wordplay between \"barefoot\" (not wearing shoes) and \"bear-foot\" (the foot of a bear)\\n2. The logical connection to the setup (bears don\\'t wear shoes)\\n3. It\\'s family-friendly and accessible\\n4. It\\'s a simple, clean pun that creates an unexpected but satisfying punchline\\n\\nIt\\'s the kind of joke that might make you groan and smile at the same time - what people often call a \"dad joke.\"'"
]
},
"execution_count": 4,
@ -161,7 +161,7 @@
{
"data": {
"text/plain": [
"\"Haha, that's a cute and punny joke! I like how it plays on the idea of beets blushing or turning red like someone blushing. Food puns can be quite amusing. While not a total knee-slapper, it's a light-hearted, groan-worthy dad joke that would make me chuckle and shake my head. Simple vegetable humor!\""
"'Yes, that\\'s a cute and funny joke! It works well because:\\n\\n1. It plays on the double meaning of \"roots\" - both the literal roots of the beet plant and the metaphorical sense of knowing one\\'s origins or foundation\\n2. It\\'s a simple, clean pun that doesn\\'t rely on offensive content\\n3. It has a satisfying logical connection (beets are root vegetables)\\n\\nIt\\'s the kind of wholesome food pun that might make people groan a little but also smile. Perfect for sharing in casual conversation or with kids!'"
]
},
"execution_count": 5,
@ -205,7 +205,7 @@
{
"data": {
"text/plain": [
"\"I cannot reproduce any copyrighted material verbatim, but I can try to analyze the humor in the joke you provided without quoting it directly.\\n\\nThe joke plays on the idea that the Cylon raiders, who are the antagonists in the Battlestar Galactica universe, failed to locate the human survivors after attacking their home planets (the Twelve Colonies) due to using an outdated and poorly performing operating system (Windows Vista) for their targeting systems.\\n\\nThe humor stems from the juxtaposition of a futuristic science fiction setting with a relatable real-world frustration the use of buggy, slow, or unreliable software or technology. It pokes fun at the perceived inadequacies of Windows Vista, which was widely criticized for its performance issues and other problems when it was released.\\n\\nBy attributing the Cylons' failure to locate the humans to their use of Vista, the joke creates an amusing and unexpected connection between a fictional advanced race of robots and a familiar technological annoyance experienced by many people in the real world.\\n\\nOverall, the joke relies on incongruity and relatability to generate humor, but without reproducing any copyrighted material directly.\""
"\"This joke is moderately funny! It plays on Battlestar Galactica lore where Cylons are robots with 12 different models trying to infiltrate human society. The humor comes from the idea of a Cylon accidentally revealing their non-human nature through a pickup line that references their artificial origins. It's a decent nerd-culture joke that would land well with fans of the show, though someone unfamiliar with Battlestar Galactica might not get the reference. The punchline effectively highlights the contradiction in a Cylon trying to blend in while simultaneously revealing their true identity.\""
]
},
"execution_count": 6,
@ -256,7 +256,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -270,7 +270,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.1"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -79,18 +79,7 @@
"execution_count": 1,
"id": "f123bdcb-8c8b-440c-9bbd-aa5ed4e9cd17",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.2.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.0\u001b[0m\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpython -m pip install --upgrade pip\u001b[0m\n",
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"outputs": [],
"source": [
"# | output: false\n",
"# | echo: false\n",
@ -110,7 +99,7 @@
"\n",
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"model = ChatAnthropic(model=\"claude-3-sonnet-20240229\", temperature=0)"
"model = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\", temperature=0)"
]
},
{
@ -131,7 +120,14 @@
"name": "stdout",
"output_type": "stream",
"text": [
"The| sky| appears| blue| during| the| day|.|"
"|The sky typically| appears blue during the day due to a phenomenon| called Rayleigh scattering, where| air molecules scatter sunlight, with| blue light being scattered more than other colors. However|, the sky's color can vary|:\n",
"\n",
"- At sunrise/sunset:| Red, orange, pink, or purple\n",
"-| During storms: Gray or dark blue|\n",
"- At night: Dark| blue to black\n",
"- In certain| atmospheric conditions: White, yellow, or green| (rare)\n",
"\n",
"The color we perceive depends| on weather conditions, time of day, pollution| levels, and our viewing angle.||"
]
}
],
@ -160,7 +156,7 @@
"name": "stdout",
"output_type": "stream",
"text": [
"The| sky| appears| blue| during| the| day|.|"
"|The sky typically| appears blue during the day due to a phenomenon called Rayleigh| scattering, where air molecules scatter sunlight,| with blue light being scattered more than other colors. However|, the sky's color can vary - appearing re|d, orange, or pink during sunrise and sunset,| gray on cloudy days, and black at night.| The color you see depends on the time of| day, weather conditions, and your location.||"
]
}
],
@ -188,10 +184,10 @@
{
"data": {
"text/plain": [
"AIMessageChunk(content='The', id='run-b36bea64-5511-4d7a-b6a3-a07b3db0c8e7')"
"AIMessageChunk(content='', additional_kwargs={}, response_metadata={'model_name': 'claude-3-7-sonnet-20250219'}, id='run--c4f01565-8bb4-4f07-9b23-acfe46cbeca3', usage_metadata={'input_tokens': 13, 'output_tokens': 0, 'total_tokens': 13, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})"
]
},
"execution_count": 4,
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
@ -219,10 +215,10 @@
{
"data": {
"text/plain": [
"AIMessageChunk(content='The sky appears blue during', id='run-b36bea64-5511-4d7a-b6a3-a07b3db0c8e7')"
"AIMessageChunk(content='The sky typically appears blue during the day due to a phenomenon called Rayleigh scattering, where air molecules scatter sunlight, with blue light being scattered more than other colors. However', additional_kwargs={}, response_metadata={'model_name': 'claude-3-7-sonnet-20250219'}, id='run--c4f01565-8bb4-4f07-9b23-acfe46cbeca3', usage_metadata={'input_tokens': 13, 'output_tokens': 0, 'total_tokens': 13, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})"
]
},
"execution_count": 5,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
@ -259,17 +255,9 @@
"name": "stdout",
"output_type": "stream",
"text": [
"Here|'s| a| joke| about| a| par|rot|:|\n",
"|Why| don't parrots use the internet?\n",
"\n",
"A man| goes| to| a| pet| shop| to| buy| a| par|rot|.| The| shop| owner| shows| him| two| stunning| pa|rr|ots| with| beautiful| pl|um|age|.|\n",
"\n",
"\"|There|'s| a| talking| par|rot| an|d a| non|-|talking| par|rot|,\"| the| owner| says|.| \"|The| talking| par|rot| costs| $|100|,| an|d the| non|-|talking| par|rot| is| $|20|.\"|\n",
"\n",
"The| man| says|,| \"|I|'ll| take| the| non|-|talking| par|rot| at| $|20|.\"|\n",
"\n",
"He| pays| an|d leaves| with| the| par|rot|.| As| he|'s| walking| down| the| street|,| the| par|rot| looks| up| at| him| an|d says|,| \"|You| know|,| you| really| are| a| stupi|d man|!\"|\n",
"\n",
"The| man| is| stun|ne|d an|d looks| at| the| par|rot| in| dis|bel|ief|.| The| par|rot| continues|,| \"|Yes|,| you| got| r|ippe|d off| big| time|!| I| can| talk| just| as| well| as| that| other| par|rot|,| an|d you| only| pai|d $|20| |for| me|!\"|"
"They|'re afraid of getting a virus from all the tweets|!||"
]
}
],
@ -337,26 +325,14 @@
"name": "stdout",
"output_type": "stream",
"text": [
"{}\n",
"{'countries': []}\n",
"{'countries': [{}]}\n",
"{'countries': [{'name': ''}]}\n",
"{'countries': [{'name': 'France'}]}\n",
"{'countries': [{'name': 'France', 'population': 67}]}\n",
"{'countries': [{'name': 'France', 'population': 67413}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': ''}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain'}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47351}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47351567}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47351567}, {}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47351567}, {'name': ''}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47351567}, {'name': 'Japan'}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47351567}, {'name': 'Japan', 'population': 125}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47351567}, {'name': 'Japan', 'population': 125584}]}\n",
"{'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47351567}, {'name': 'Japan', 'population': 125584000}]}\n"
"{'countries': [{'name': 'France', 'population': 67750}]}\n",
"{'countries': [{'name': 'France', 'population': 67750000}, {}]}\n",
"{'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain'}]}\n",
"{'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {}]}\n",
"{'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {'name': 'Japan'}]}\n",
"{'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {'name': 'Japan', 'population': 125700000}]}\n"
]
}
],
@ -539,11 +515,11 @@
{
"data": {
"text/plain": [
"[[Document(page_content='harrison worked at kensho'),\n",
" Document(page_content='harrison likes spicy food')]]"
"[[Document(id='2740a247-9738-48c4-8c8f-d879d4ed39f7', metadata={}, page_content='harrison worked at kensho'),\n",
" Document(id='1d3d012f-1cb0-4bee-928a-c8bf0f8b1b92', metadata={}, page_content='harrison likes spicy food')]]"
]
},
"execution_count": 10,
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
@ -614,15 +590,15 @@
"name": "stdout",
"output_type": "stream",
"text": [
"Base|d on| the| given| context|,| Harrison| worke|d at| K|ens|ho|.|\n",
"|Base|d on the provided context, Harrison worked at Kens|ho.\n",
"\n",
"Here| are| |3| |made| up| sentences| about| this| place|:|\n",
"Three made up sentences about Kens|ho:\n",
"\n",
"1|.| K|ens|ho| was| a| cutting|-|edge| technology| company| known| for| its| innovative| solutions| in| artificial| intelligence| an|d data| analytics|.|\n",
"1. Kensho is a| cutting-edge technology company that specializes in| AI and data analytics for financial institutions.\n",
"\n",
"2|.| The| modern| office| space| at| K|ens|ho| feature|d open| floor| plans|,| collaborative| work|sp|aces|,| an|d a| vib|rant| atmosphere| that| fos|tere|d creativity| an|d team|work|.|\n",
"2|. The Kensho office features| an open floor plan with panoramic views of the city| skyline, creating an inspiring environment for its| employees.\n",
"\n",
"3|.| With| its| prime| location| in| the| heart| of| the| city|,| K|ens|ho| attracte|d top| talent| from| aroun|d the| worl|d,| creating| a| diverse| an|d dynamic| work| environment|.|"
"3. At Kensho,| team members often collaborate in innovative brainstorming sessions while| enjoying complimentary gourmet coffee from| their in-house café.||"
]
}
],
@ -763,38 +739,38 @@
" 'data': {'input': 'hello'},\n",
" 'name': 'ChatAnthropic',\n",
" 'tags': [],\n",
" 'run_id': 'b18d016d-8b9b-49e7-a555-44db498fcf66',\n",
" 'run_id': 'c35a72be-a5af-4bd5-bd9b-206135c28ef6',\n",
" 'metadata': {'ls_provider': 'anthropic',\n",
" 'ls_model_name': 'claude-3-sonnet-20240229',\n",
" 'ls_model_name': 'claude-3-7-sonnet-20250219',\n",
" 'ls_model_type': 'chat',\n",
" 'ls_temperature': 0.0,\n",
" 'ls_max_tokens': 1024},\n",
" 'parent_ids': []},\n",
" {'event': 'on_chat_model_stream',\n",
" 'run_id': 'b18d016d-8b9b-49e7-a555-44db498fcf66',\n",
" 'run_id': 'c35a72be-a5af-4bd5-bd9b-206135c28ef6',\n",
" 'name': 'ChatAnthropic',\n",
" 'tags': [],\n",
" 'metadata': {'ls_provider': 'anthropic',\n",
" 'ls_model_name': 'claude-3-sonnet-20240229',\n",
" 'ls_model_name': 'claude-3-7-sonnet-20250219',\n",
" 'ls_model_type': 'chat',\n",
" 'ls_temperature': 0.0,\n",
" 'ls_max_tokens': 1024},\n",
" 'data': {'chunk': AIMessageChunk(content='', additional_kwargs={}, response_metadata={}, id='run-b18d016d-8b9b-49e7-a555-44db498fcf66', usage_metadata={'input_tokens': 8, 'output_tokens': 4, 'total_tokens': 12, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})},\n",
" 'data': {'chunk': AIMessageChunk(content='', additional_kwargs={}, response_metadata={'model_name': 'claude-3-7-sonnet-20250219'}, id='run--c35a72be-a5af-4bd5-bd9b-206135c28ef6', usage_metadata={'input_tokens': 8, 'output_tokens': 0, 'total_tokens': 8, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})},\n",
" 'parent_ids': []},\n",
" {'event': 'on_chat_model_stream',\n",
" 'run_id': 'b18d016d-8b9b-49e7-a555-44db498fcf66',\n",
" 'run_id': 'c35a72be-a5af-4bd5-bd9b-206135c28ef6',\n",
" 'name': 'ChatAnthropic',\n",
" 'tags': [],\n",
" 'metadata': {'ls_provider': 'anthropic',\n",
" 'ls_model_name': 'claude-3-sonnet-20240229',\n",
" 'ls_model_name': 'claude-3-7-sonnet-20250219',\n",
" 'ls_model_type': 'chat',\n",
" 'ls_temperature': 0.0,\n",
" 'ls_max_tokens': 1024},\n",
" 'data': {'chunk': AIMessageChunk(content='Hello! How can', additional_kwargs={}, response_metadata={}, id='run-b18d016d-8b9b-49e7-a555-44db498fcf66')},\n",
" 'data': {'chunk': AIMessageChunk(content='Hello! How', additional_kwargs={}, response_metadata={}, id='run--c35a72be-a5af-4bd5-bd9b-206135c28ef6')},\n",
" 'parent_ids': []}]"
]
},
"execution_count": 14,
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
@ -813,30 +789,30 @@
"data": {
"text/plain": [
"[{'event': 'on_chat_model_stream',\n",
" 'run_id': 'b18d016d-8b9b-49e7-a555-44db498fcf66',\n",
" 'run_id': 'c35a72be-a5af-4bd5-bd9b-206135c28ef6',\n",
" 'name': 'ChatAnthropic',\n",
" 'tags': [],\n",
" 'metadata': {'ls_provider': 'anthropic',\n",
" 'ls_model_name': 'claude-3-sonnet-20240229',\n",
" 'ls_model_name': 'claude-3-7-sonnet-20250219',\n",
" 'ls_model_type': 'chat',\n",
" 'ls_temperature': 0.0,\n",
" 'ls_max_tokens': 1024},\n",
" 'data': {'chunk': AIMessageChunk(content='', additional_kwargs={}, response_metadata={'stop_reason': 'end_turn', 'stop_sequence': None}, id='run-b18d016d-8b9b-49e7-a555-44db498fcf66', usage_metadata={'input_tokens': 0, 'output_tokens': 12, 'total_tokens': 12, 'input_token_details': {}})},\n",
" 'data': {'chunk': AIMessageChunk(content='', additional_kwargs={}, response_metadata={'stop_reason': 'end_turn', 'stop_sequence': None}, id='run--c35a72be-a5af-4bd5-bd9b-206135c28ef6', usage_metadata={'input_tokens': 0, 'output_tokens': 40, 'total_tokens': 40})},\n",
" 'parent_ids': []},\n",
" {'event': 'on_chat_model_end',\n",
" 'data': {'output': AIMessageChunk(content='Hello! How can I assist you today?', additional_kwargs={}, response_metadata={'stop_reason': 'end_turn', 'stop_sequence': None}, id='run-b18d016d-8b9b-49e7-a555-44db498fcf66', usage_metadata={'input_tokens': 8, 'output_tokens': 16, 'total_tokens': 24, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})},\n",
" 'run_id': 'b18d016d-8b9b-49e7-a555-44db498fcf66',\n",
" 'data': {'output': AIMessageChunk(content=\"Hello! How can I assist you today? Whether you have questions, need information, or just want to chat, I'm here to help. What would you like to talk about?\", additional_kwargs={}, response_metadata={'model_name': 'claude-3-7-sonnet-20250219', 'stop_reason': 'end_turn', 'stop_sequence': None}, id='run--c35a72be-a5af-4bd5-bd9b-206135c28ef6', usage_metadata={'input_tokens': 8, 'output_tokens': 40, 'total_tokens': 48, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})},\n",
" 'run_id': 'c35a72be-a5af-4bd5-bd9b-206135c28ef6',\n",
" 'name': 'ChatAnthropic',\n",
" 'tags': [],\n",
" 'metadata': {'ls_provider': 'anthropic',\n",
" 'ls_model_name': 'claude-3-sonnet-20240229',\n",
" 'ls_model_name': 'claude-3-7-sonnet-20250219',\n",
" 'ls_model_type': 'chat',\n",
" 'ls_temperature': 0.0,\n",
" 'ls_max_tokens': 1024},\n",
" 'parent_ids': []}]"
]
},
"execution_count": 15,
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
@ -903,23 +879,34 @@
" 'data': {'input': 'output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`'},\n",
" 'name': 'RunnableSequence',\n",
" 'tags': [],\n",
" 'run_id': '4765006b-16e2-4b1d-a523-edd9fd64cb92',\n",
" 'metadata': {}},\n",
" 'run_id': 'f859e56f-a760-4670-a24e-040e11bcd7fc',\n",
" 'metadata': {},\n",
" 'parent_ids': []},\n",
" {'event': 'on_chat_model_start',\n",
" 'data': {'input': {'messages': [[HumanMessage(content='output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`')]]}},\n",
" 'data': {'input': {'messages': [[HumanMessage(content='output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`', additional_kwargs={}, response_metadata={})]]}},\n",
" 'name': 'ChatAnthropic',\n",
" 'tags': ['seq:step:1'],\n",
" 'run_id': '0320c234-7b52-4a14-ae4e-5f100949e589',\n",
" 'metadata': {}},\n",
" 'run_id': '2aa8c9e6-a5cd-4e94-b994-cb0e9bd8ab21',\n",
" 'metadata': {'ls_provider': 'anthropic',\n",
" 'ls_model_name': 'claude-3-7-sonnet-20250219',\n",
" 'ls_model_type': 'chat',\n",
" 'ls_temperature': 0.0,\n",
" 'ls_max_tokens': 1024},\n",
" 'parent_ids': ['f859e56f-a760-4670-a24e-040e11bcd7fc']},\n",
" {'event': 'on_chat_model_stream',\n",
" 'data': {'chunk': AIMessageChunk(content='{', id='run-0320c234-7b52-4a14-ae4e-5f100949e589')},\n",
" 'run_id': '0320c234-7b52-4a14-ae4e-5f100949e589',\n",
" 'data': {'chunk': AIMessageChunk(content='', additional_kwargs={}, response_metadata={'model_name': 'claude-3-7-sonnet-20250219'}, id='run--2aa8c9e6-a5cd-4e94-b994-cb0e9bd8ab21', usage_metadata={'input_tokens': 56, 'output_tokens': 0, 'total_tokens': 56, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})},\n",
" 'run_id': '2aa8c9e6-a5cd-4e94-b994-cb0e9bd8ab21',\n",
" 'name': 'ChatAnthropic',\n",
" 'tags': ['seq:step:1'],\n",
" 'metadata': {}}]"
" 'metadata': {'ls_provider': 'anthropic',\n",
" 'ls_model_name': 'claude-3-7-sonnet-20250219',\n",
" 'ls_model_type': 'chat',\n",
" 'ls_temperature': 0.0,\n",
" 'ls_max_tokens': 1024},\n",
" 'parent_ids': ['f859e56f-a760-4670-a24e-040e11bcd7fc']}]"
]
},
"execution_count": 18,
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
@ -955,25 +942,25 @@
"output_type": "stream",
"text": [
"Chat model chunk: ''\n",
"Chat model chunk: '{'\n",
"Parser chunk: {}\n",
"Chat model chunk: '\\n \"countries'\n",
"Chat model chunk: '\": [\\n '\n",
"Chat model chunk: '```'\n",
"Chat model chunk: 'json\\n{\\n \"countries\": ['\n",
"Parser chunk: {'countries': []}\n",
"Chat model chunk: '{\\n \"'\n",
"Parser chunk: {'countries': [{}]}\n",
"Chat model chunk: 'name\": \"France'\n",
"Chat model chunk: '\\n {\\n \"name\": \"France\",'\n",
"Parser chunk: {'countries': [{'name': 'France'}]}\n",
"Chat model chunk: '\",\\n \"'\n",
"Chat model chunk: 'population\": 67'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67}]}\n",
"Chat model chunk: '413'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67413}]}\n",
"Chat model chunk: '000\\n },'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67413000}]}\n",
"Chat model chunk: '\\n {'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67413000}, {}]}\n",
"Chat model chunk: '\\n \"name\":'\n",
"Chat model chunk: '\\n \"population\": 67750000\\n },'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}]}\n",
"Chat model chunk: '\\n {\\n \"name\": \"Spain\",'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain'}]}\n",
"Chat model chunk: '\\n \"population\": 47350'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350}]}\n",
"Chat model chunk: '000\\n },\\n {\\n \"'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {}]}\n",
"Chat model chunk: 'name\": \"Japan\",\\n \"population\":'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {'name': 'Japan'}]}\n",
"Chat model chunk: ' 125700000\\n }'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {'name': 'Japan', 'population': 125700000}]}\n",
"Chat model chunk: '\\n ]\\n}\\n```'\n",
"Chat model chunk: ''\n",
"...\n"
]
}
@ -1033,18 +1020,16 @@
"name": "stdout",
"output_type": "stream",
"text": [
"{'event': 'on_parser_start', 'data': {'input': 'output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`'}, 'name': 'my_parser', 'tags': ['seq:step:2'], 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'metadata': {}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"{'event': 'on_parser_stream', 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {}}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"{'event': 'on_parser_stream', 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': []}}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"{'event': 'on_parser_stream', 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{}]}}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"{'event': 'on_parser_stream', 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France'}]}}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"{'event': 'on_parser_stream', 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67}]}}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"{'event': 'on_parser_stream', 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67413}]}}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"{'event': 'on_parser_stream', 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67413000}]}}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"{'event': 'on_parser_stream', 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67413000}, {}]}}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"{'event': 'on_parser_stream', 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain'}]}}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"{'event': 'on_parser_stream', 'run_id': '37ee9e85-481c-415e-863b-c9e132d24948', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47}]}}, 'parent_ids': ['5a0bc625-09fd-4bdf-9932-54909a9a8c29']}\n",
"...\n"
"{'event': 'on_parser_start', 'data': {'input': 'output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`'}, 'name': 'my_parser', 'tags': ['seq:step:2'], 'run_id': '781af9b6-31f8-47f2-ab79-52d17b000857', 'metadata': {}, 'parent_ids': ['82c918c6-d5f6-4d2d-b710-4668509fe2f0']}\n",
"{'event': 'on_parser_stream', 'run_id': '781af9b6-31f8-47f2-ab79-52d17b000857', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': []}}, 'parent_ids': ['82c918c6-d5f6-4d2d-b710-4668509fe2f0']}\n",
"{'event': 'on_parser_stream', 'run_id': '781af9b6-31f8-47f2-ab79-52d17b000857', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France'}]}}, 'parent_ids': ['82c918c6-d5f6-4d2d-b710-4668509fe2f0']}\n",
"{'event': 'on_parser_stream', 'run_id': '781af9b6-31f8-47f2-ab79-52d17b000857', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67750}]}}, 'parent_ids': ['82c918c6-d5f6-4d2d-b710-4668509fe2f0']}\n",
"{'event': 'on_parser_stream', 'run_id': '781af9b6-31f8-47f2-ab79-52d17b000857', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67750000}, {}]}}, 'parent_ids': ['82c918c6-d5f6-4d2d-b710-4668509fe2f0']}\n",
"{'event': 'on_parser_stream', 'run_id': '781af9b6-31f8-47f2-ab79-52d17b000857', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain'}]}}, 'parent_ids': ['82c918c6-d5f6-4d2d-b710-4668509fe2f0']}\n",
"{'event': 'on_parser_stream', 'run_id': '781af9b6-31f8-47f2-ab79-52d17b000857', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}]}}, 'parent_ids': ['82c918c6-d5f6-4d2d-b710-4668509fe2f0']}\n",
"{'event': 'on_parser_stream', 'run_id': '781af9b6-31f8-47f2-ab79-52d17b000857', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {'name': 'Japan'}]}}, 'parent_ids': ['82c918c6-d5f6-4d2d-b710-4668509fe2f0']}\n",
"{'event': 'on_parser_stream', 'run_id': '781af9b6-31f8-47f2-ab79-52d17b000857', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {'name': 'Japan', 'population': 125700000}]}}, 'parent_ids': ['82c918c6-d5f6-4d2d-b710-4668509fe2f0']}\n",
"{'event': 'on_parser_end', 'data': {'output': {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {'name': 'Japan', 'population': 125700000}]}}, 'run_id': '781af9b6-31f8-47f2-ab79-52d17b000857', 'name': 'my_parser', 'tags': ['seq:step:2'], 'metadata': {}, 'parent_ids': ['82c918c6-d5f6-4d2d-b710-4668509fe2f0']}\n"
]
}
],
@ -1086,17 +1071,17 @@
"name": "stdout",
"output_type": "stream",
"text": [
"{'event': 'on_chat_model_start', 'data': {'input': 'output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`'}, 'name': 'model', 'tags': ['seq:step:1'], 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='', additional_kwargs={}, response_metadata={}, id='run-156c3e40-82fb-49ff-8e41-9e998061be8c', usage_metadata={'input_tokens': 56, 'output_tokens': 1, 'total_tokens': 57, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})}, 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='{', additional_kwargs={}, response_metadata={}, id='run-156c3e40-82fb-49ff-8e41-9e998061be8c')}, 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='\\n \"countries', additional_kwargs={}, response_metadata={}, id='run-156c3e40-82fb-49ff-8e41-9e998061be8c')}, 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='\": [\\n ', additional_kwargs={}, response_metadata={}, id='run-156c3e40-82fb-49ff-8e41-9e998061be8c')}, 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='{\\n \"', additional_kwargs={}, response_metadata={}, id='run-156c3e40-82fb-49ff-8e41-9e998061be8c')}, 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='name\": \"France', additional_kwargs={}, response_metadata={}, id='run-156c3e40-82fb-49ff-8e41-9e998061be8c')}, 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='\",\\n \"', additional_kwargs={}, response_metadata={}, id='run-156c3e40-82fb-49ff-8e41-9e998061be8c')}, 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='population\": 67', additional_kwargs={}, response_metadata={}, id='run-156c3e40-82fb-49ff-8e41-9e998061be8c')}, 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='413', additional_kwargs={}, response_metadata={}, id='run-156c3e40-82fb-49ff-8e41-9e998061be8c')}, 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='000\\n },', additional_kwargs={}, response_metadata={}, id='run-156c3e40-82fb-49ff-8e41-9e998061be8c')}, 'run_id': '156c3e40-82fb-49ff-8e41-9e998061be8c', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['7b927055-bc1b-4b50-a34c-10d3cfcb3899']}\n",
"{'event': 'on_chat_model_start', 'data': {'input': 'output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`'}, 'name': 'model', 'tags': ['seq:step:1'], 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='', additional_kwargs={}, response_metadata={'model_name': 'claude-3-7-sonnet-20250219'}, id='run--b7a08416-a629-4b42-b5d5-dbe48566e5d5', usage_metadata={'input_tokens': 56, 'output_tokens': 0, 'total_tokens': 56, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})}, 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='```', additional_kwargs={}, response_metadata={}, id='run--b7a08416-a629-4b42-b5d5-dbe48566e5d5')}, 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='json\\n{\\n \"countries\": [', additional_kwargs={}, response_metadata={}, id='run--b7a08416-a629-4b42-b5d5-dbe48566e5d5')}, 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='\\n {\\n \"name\": \"France\",', additional_kwargs={}, response_metadata={}, id='run--b7a08416-a629-4b42-b5d5-dbe48566e5d5')}, 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='\\n \"population\": 67750', additional_kwargs={}, response_metadata={}, id='run--b7a08416-a629-4b42-b5d5-dbe48566e5d5')}, 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='000\\n },\\n {\\n \"', additional_kwargs={}, response_metadata={}, id='run--b7a08416-a629-4b42-b5d5-dbe48566e5d5')}, 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='name\": \"Spain\",\\n \"population\":', additional_kwargs={}, response_metadata={}, id='run--b7a08416-a629-4b42-b5d5-dbe48566e5d5')}, 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content=' 47350000\\n },', additional_kwargs={}, response_metadata={}, id='run--b7a08416-a629-4b42-b5d5-dbe48566e5d5')}, 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='\\n {\\n \"name\": \"Japan\",', additional_kwargs={}, response_metadata={}, id='run--b7a08416-a629-4b42-b5d5-dbe48566e5d5')}, 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='\\n \"population\": 125700', additional_kwargs={}, response_metadata={}, id='run--b7a08416-a629-4b42-b5d5-dbe48566e5d5')}, 'run_id': 'b7a08416-a629-4b42-b5d5-dbe48566e5d5', 'name': 'model', 'tags': ['seq:step:1'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['116a6506-5a19-4f60-a8c2-7b728d4b8248']}\n",
"...\n"
]
}
@ -1144,17 +1129,17 @@
"name": "stdout",
"output_type": "stream",
"text": [
"{'event': 'on_chain_start', 'data': {'input': 'output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`'}, 'name': 'RunnableSequence', 'tags': ['my_chain'], 'run_id': '58d1302e-36ce-4df7-a3cb-47cb73d57e44', 'metadata': {}, 'parent_ids': []}\n",
"{'event': 'on_chat_model_start', 'data': {'input': {'messages': [[HumanMessage(content='output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`', additional_kwargs={}, response_metadata={})]]}}, 'name': 'ChatAnthropic', 'tags': ['seq:step:1', 'my_chain'], 'run_id': '8222e8a1-d978-4f30-87fc-b2dba838774b', 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['58d1302e-36ce-4df7-a3cb-47cb73d57e44']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='', additional_kwargs={}, response_metadata={}, id='run-8222e8a1-d978-4f30-87fc-b2dba838774b', usage_metadata={'input_tokens': 56, 'output_tokens': 1, 'total_tokens': 57, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})}, 'run_id': '8222e8a1-d978-4f30-87fc-b2dba838774b', 'name': 'ChatAnthropic', 'tags': ['seq:step:1', 'my_chain'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['58d1302e-36ce-4df7-a3cb-47cb73d57e44']}\n",
"{'event': 'on_parser_start', 'data': {}, 'name': 'JsonOutputParser', 'tags': ['seq:step:2', 'my_chain'], 'run_id': '75604c84-e1e6-494a-8b2a-950f45d932e8', 'metadata': {}, 'parent_ids': ['58d1302e-36ce-4df7-a3cb-47cb73d57e44']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='{', additional_kwargs={}, response_metadata={}, id='run-8222e8a1-d978-4f30-87fc-b2dba838774b')}, 'run_id': '8222e8a1-d978-4f30-87fc-b2dba838774b', 'name': 'ChatAnthropic', 'tags': ['seq:step:1', 'my_chain'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['58d1302e-36ce-4df7-a3cb-47cb73d57e44']}\n",
"{'event': 'on_parser_stream', 'run_id': '75604c84-e1e6-494a-8b2a-950f45d932e8', 'name': 'JsonOutputParser', 'tags': ['seq:step:2', 'my_chain'], 'metadata': {}, 'data': {'chunk': {}}, 'parent_ids': ['58d1302e-36ce-4df7-a3cb-47cb73d57e44']}\n",
"{'event': 'on_chain_stream', 'run_id': '58d1302e-36ce-4df7-a3cb-47cb73d57e44', 'name': 'RunnableSequence', 'tags': ['my_chain'], 'metadata': {}, 'data': {'chunk': {}}, 'parent_ids': []}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='\\n \"countries', additional_kwargs={}, response_metadata={}, id='run-8222e8a1-d978-4f30-87fc-b2dba838774b')}, 'run_id': '8222e8a1-d978-4f30-87fc-b2dba838774b', 'name': 'ChatAnthropic', 'tags': ['seq:step:1', 'my_chain'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['58d1302e-36ce-4df7-a3cb-47cb73d57e44']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='\": [\\n ', additional_kwargs={}, response_metadata={}, id='run-8222e8a1-d978-4f30-87fc-b2dba838774b')}, 'run_id': '8222e8a1-d978-4f30-87fc-b2dba838774b', 'name': 'ChatAnthropic', 'tags': ['seq:step:1', 'my_chain'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-sonnet-20240229', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['58d1302e-36ce-4df7-a3cb-47cb73d57e44']}\n",
"{'event': 'on_parser_stream', 'run_id': '75604c84-e1e6-494a-8b2a-950f45d932e8', 'name': 'JsonOutputParser', 'tags': ['seq:step:2', 'my_chain'], 'metadata': {}, 'data': {'chunk': {'countries': []}}, 'parent_ids': ['58d1302e-36ce-4df7-a3cb-47cb73d57e44']}\n",
"{'event': 'on_chain_stream', 'run_id': '58d1302e-36ce-4df7-a3cb-47cb73d57e44', 'name': 'RunnableSequence', 'tags': ['my_chain'], 'metadata': {}, 'data': {'chunk': {'countries': []}}, 'parent_ids': []}\n",
"{'event': 'on_chain_start', 'data': {'input': 'output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`'}, 'name': 'RunnableSequence', 'tags': ['my_chain'], 'run_id': '3e4f8c37-a44a-46b7-a7e5-75182d1cca31', 'metadata': {}, 'parent_ids': []}\n",
"{'event': 'on_chat_model_start', 'data': {'input': {'messages': [[HumanMessage(content='output a list of the countries france, spain and japan and their populations in JSON format. Use a dict with an outer key of \"countries\" which contains a list of countries. Each country should have the key `name` and `population`', additional_kwargs={}, response_metadata={})]]}}, 'name': 'ChatAnthropic', 'tags': ['seq:step:1', 'my_chain'], 'run_id': '778846c9-acd3-43b7-b9c0-ac718761b2bc', 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['3e4f8c37-a44a-46b7-a7e5-75182d1cca31']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='', additional_kwargs={}, response_metadata={'model_name': 'claude-3-7-sonnet-20250219'}, id='run--778846c9-acd3-43b7-b9c0-ac718761b2bc', usage_metadata={'input_tokens': 56, 'output_tokens': 0, 'total_tokens': 56, 'input_token_details': {'cache_creation': 0, 'cache_read': 0}})}, 'run_id': '778846c9-acd3-43b7-b9c0-ac718761b2bc', 'name': 'ChatAnthropic', 'tags': ['seq:step:1', 'my_chain'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['3e4f8c37-a44a-46b7-a7e5-75182d1cca31']}\n",
"{'event': 'on_parser_start', 'data': {}, 'name': 'JsonOutputParser', 'tags': ['seq:step:2', 'my_chain'], 'run_id': '2c46d24f-231c-4062-a7ab-b7954840986d', 'metadata': {}, 'parent_ids': ['3e4f8c37-a44a-46b7-a7e5-75182d1cca31']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='```', additional_kwargs={}, response_metadata={}, id='run--778846c9-acd3-43b7-b9c0-ac718761b2bc')}, 'run_id': '778846c9-acd3-43b7-b9c0-ac718761b2bc', 'name': 'ChatAnthropic', 'tags': ['seq:step:1', 'my_chain'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['3e4f8c37-a44a-46b7-a7e5-75182d1cca31']}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='json\\n{\\n \"countries\": [', additional_kwargs={}, response_metadata={}, id='run--778846c9-acd3-43b7-b9c0-ac718761b2bc')}, 'run_id': '778846c9-acd3-43b7-b9c0-ac718761b2bc', 'name': 'ChatAnthropic', 'tags': ['seq:step:1', 'my_chain'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['3e4f8c37-a44a-46b7-a7e5-75182d1cca31']}\n",
"{'event': 'on_parser_stream', 'run_id': '2c46d24f-231c-4062-a7ab-b7954840986d', 'name': 'JsonOutputParser', 'tags': ['seq:step:2', 'my_chain'], 'metadata': {}, 'data': {'chunk': {'countries': []}}, 'parent_ids': ['3e4f8c37-a44a-46b7-a7e5-75182d1cca31']}\n",
"{'event': 'on_chain_stream', 'run_id': '3e4f8c37-a44a-46b7-a7e5-75182d1cca31', 'name': 'RunnableSequence', 'tags': ['my_chain'], 'metadata': {}, 'data': {'chunk': {'countries': []}}, 'parent_ids': []}\n",
"{'event': 'on_chat_model_stream', 'data': {'chunk': AIMessageChunk(content='\\n {\\n \"name\": \"France\",', additional_kwargs={}, response_metadata={}, id='run--778846c9-acd3-43b7-b9c0-ac718761b2bc')}, 'run_id': '778846c9-acd3-43b7-b9c0-ac718761b2bc', 'name': 'ChatAnthropic', 'tags': ['seq:step:1', 'my_chain'], 'metadata': {'ls_provider': 'anthropic', 'ls_model_name': 'claude-3-7-sonnet-20250219', 'ls_model_type': 'chat', 'ls_temperature': 0.0, 'ls_max_tokens': 1024}, 'parent_ids': ['3e4f8c37-a44a-46b7-a7e5-75182d1cca31']}\n",
"{'event': 'on_parser_stream', 'run_id': '2c46d24f-231c-4062-a7ab-b7954840986d', 'name': 'JsonOutputParser', 'tags': ['seq:step:2', 'my_chain'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France'}]}}, 'parent_ids': ['3e4f8c37-a44a-46b7-a7e5-75182d1cca31']}\n",
"{'event': 'on_chain_stream', 'run_id': '3e4f8c37-a44a-46b7-a7e5-75182d1cca31', 'name': 'RunnableSequence', 'tags': ['my_chain'], 'metadata': {}, 'data': {'chunk': {'countries': [{'name': 'France'}]}}, 'parent_ids': []}\n",
"...\n"
]
}
@ -1271,32 +1256,27 @@
"output_type": "stream",
"text": [
"Chat model chunk: ''\n",
"Chat model chunk: '{'\n",
"Parser chunk: {}\n",
"Chat model chunk: '\\n \"countries'\n",
"Chat model chunk: '\": [\\n '\n",
"Chat model chunk: '```'\n",
"Chat model chunk: 'json\\n{\\n \"countries\": ['\n",
"Parser chunk: {'countries': []}\n",
"Chat model chunk: '{\\n \"'\n",
"Parser chunk: {'countries': [{}]}\n",
"Chat model chunk: 'name\": \"France'\n",
"Chat model chunk: '\\n {\\n \"name\": \"France\",'\n",
"Parser chunk: {'countries': [{'name': 'France'}]}\n",
"Chat model chunk: '\",\\n \"'\n",
"Chat model chunk: 'population\": 67'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67}]}\n",
"Chat model chunk: '413'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67413}]}\n",
"Chat model chunk: '000\\n },'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67413000}]}\n",
"Chat model chunk: '\\n {'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67413000}, {}]}\n",
"Chat model chunk: '\\n \"name\":'\n",
"Chat model chunk: ' \"Spain\",'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain'}]}\n",
"Chat model chunk: '\\n \"population\":'\n",
"Chat model chunk: ' 47'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47}]}\n",
"Chat model chunk: '351'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67413000}, {'name': 'Spain', 'population': 47351}]}\n",
"Chat model chunk: '\\n \"population\": 67750'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750}]}\n",
"Chat model chunk: '000\\n },\\n {\\n \"'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {}]}\n",
"Chat model chunk: 'name\": \"Spain\",\\n \"population\":'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain'}]}\n",
"Chat model chunk: ' 47350000\\n },'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}]}\n",
"Chat model chunk: '\\n {\\n \"name\": \"Japan\",'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {'name': 'Japan'}]}\n",
"Chat model chunk: '\\n \"population\": 125700'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {'name': 'Japan', 'population': 125700}]}\n",
"Chat model chunk: '000\\n }\\n ]\\n}'\n",
"Parser chunk: {'countries': [{'name': 'France', 'population': 67750000}, {'name': 'Spain', 'population': 47350000}, {'name': 'Japan', 'population': 125700000}]}\n",
"Chat model chunk: '\\n```'\n",
"Chat model chunk: ''\n",
"...\n"
]
}
@ -1350,10 +1330,10 @@
"name": "stdout",
"output_type": "stream",
"text": [
"{'event': 'on_tool_start', 'data': {'input': 'hello'}, 'name': 'bad_tool', 'tags': [], 'run_id': 'ea900472-a8f7-425d-b627-facdef936ee8', 'metadata': {}}\n",
"{'event': 'on_chain_start', 'data': {'input': 'hello'}, 'name': 'reverse_word', 'tags': [], 'run_id': '77b01284-0515-48f4-8d7c-eb27c1882f86', 'metadata': {}}\n",
"{'event': 'on_chain_end', 'data': {'output': 'olleh', 'input': 'hello'}, 'run_id': '77b01284-0515-48f4-8d7c-eb27c1882f86', 'name': 'reverse_word', 'tags': [], 'metadata': {}}\n",
"{'event': 'on_tool_end', 'data': {'output': 'olleh'}, 'run_id': 'ea900472-a8f7-425d-b627-facdef936ee8', 'name': 'bad_tool', 'tags': [], 'metadata': {}}\n"
"{'event': 'on_tool_start', 'data': {'input': 'hello'}, 'name': 'bad_tool', 'tags': [], 'run_id': 'b1c6b79d-f94b-432f-a289-1ea68a7c3cea', 'metadata': {}, 'parent_ids': []}\n",
"{'event': 'on_chain_start', 'data': {'input': 'hello'}, 'name': 'reverse_word', 'tags': [], 'run_id': 'e661c1ec-e6d2-4f9a-9620-b50645f2b194', 'metadata': {}, 'parent_ids': ['b1c6b79d-f94b-432f-a289-1ea68a7c3cea']}\n",
"{'event': 'on_chain_end', 'data': {'output': 'olleh', 'input': 'hello'}, 'run_id': 'e661c1ec-e6d2-4f9a-9620-b50645f2b194', 'name': 'reverse_word', 'tags': [], 'metadata': {}, 'parent_ids': ['b1c6b79d-f94b-432f-a289-1ea68a7c3cea']}\n",
"{'event': 'on_tool_end', 'data': {'output': 'olleh'}, 'run_id': 'b1c6b79d-f94b-432f-a289-1ea68a7c3cea', 'name': 'bad_tool', 'tags': [], 'metadata': {}, 'parent_ids': []}\n"
]
}
],
@ -1397,10 +1377,10 @@
"name": "stdout",
"output_type": "stream",
"text": [
"{'event': 'on_tool_start', 'data': {'input': 'hello'}, 'name': 'correct_tool', 'tags': [], 'run_id': 'd5ea83b9-9278-49cc-9f1d-aa302d671040', 'metadata': {}}\n",
"{'event': 'on_chain_start', 'data': {'input': 'hello'}, 'name': 'reverse_word', 'tags': [], 'run_id': '44dafbf4-2f87-412b-ae0e-9f71713810df', 'metadata': {}}\n",
"{'event': 'on_chain_end', 'data': {'output': 'olleh', 'input': 'hello'}, 'run_id': '44dafbf4-2f87-412b-ae0e-9f71713810df', 'name': 'reverse_word', 'tags': [], 'metadata': {}}\n",
"{'event': 'on_tool_end', 'data': {'output': 'olleh'}, 'run_id': 'd5ea83b9-9278-49cc-9f1d-aa302d671040', 'name': 'correct_tool', 'tags': [], 'metadata': {}}\n"
"{'event': 'on_tool_start', 'data': {'input': 'hello'}, 'name': 'correct_tool', 'tags': [], 'run_id': '399c91f5-a40b-4173-943f-a9c583a04003', 'metadata': {}, 'parent_ids': []}\n",
"{'event': 'on_chain_start', 'data': {'input': 'hello'}, 'name': 'reverse_word', 'tags': [], 'run_id': 'e9cc7db1-4587-40af-9c35-2d787b3f0956', 'metadata': {}, 'parent_ids': ['399c91f5-a40b-4173-943f-a9c583a04003']}\n",
"{'event': 'on_chain_end', 'data': {'output': 'olleh', 'input': 'hello'}, 'run_id': 'e9cc7db1-4587-40af-9c35-2d787b3f0956', 'name': 'reverse_word', 'tags': [], 'metadata': {}, 'parent_ids': ['399c91f5-a40b-4173-943f-a9c583a04003']}\n",
"{'event': 'on_tool_end', 'data': {'output': 'olleh'}, 'run_id': '399c91f5-a40b-4173-943f-a9c583a04003', 'name': 'correct_tool', 'tags': [], 'metadata': {}, 'parent_ids': []}\n"
]
}
],
@ -1433,11 +1413,9 @@
"name": "stdout",
"output_type": "stream",
"text": [
"{'event': 'on_chain_start', 'data': {'input': '1234'}, 'name': 'reverse_and_double', 'tags': [], 'run_id': '03b0e6a1-3e60-42fc-8373-1e7829198d80', 'metadata': {}}\n",
"{'event': 'on_chain_start', 'data': {'input': '1234'}, 'name': 'reverse_word', 'tags': [], 'run_id': '5cf26fc8-840b-4642-98ed-623dda28707a', 'metadata': {}}\n",
"{'event': 'on_chain_end', 'data': {'output': '4321', 'input': '1234'}, 'run_id': '5cf26fc8-840b-4642-98ed-623dda28707a', 'name': 'reverse_word', 'tags': [], 'metadata': {}}\n",
"{'event': 'on_chain_stream', 'data': {'chunk': '43214321'}, 'run_id': '03b0e6a1-3e60-42fc-8373-1e7829198d80', 'name': 'reverse_and_double', 'tags': [], 'metadata': {}}\n",
"{'event': 'on_chain_end', 'data': {'output': '43214321'}, 'run_id': '03b0e6a1-3e60-42fc-8373-1e7829198d80', 'name': 'reverse_and_double', 'tags': [], 'metadata': {}}\n"
"{'event': 'on_chain_start', 'data': {'input': '1234'}, 'name': 'reverse_and_double', 'tags': [], 'run_id': '04726e2e-f508-4f90-9d4f-f88e588f0b39', 'metadata': {}, 'parent_ids': []}\n",
"{'event': 'on_chain_stream', 'run_id': '04726e2e-f508-4f90-9d4f-f88e588f0b39', 'name': 'reverse_and_double', 'tags': [], 'metadata': {}, 'data': {'chunk': '43214321'}, 'parent_ids': []}\n",
"{'event': 'on_chain_end', 'data': {'output': '43214321'}, 'run_id': '04726e2e-f508-4f90-9d4f-f88e588f0b39', 'name': 'reverse_and_double', 'tags': [], 'metadata': {}, 'parent_ids': []}\n"
]
}
],
@ -1475,11 +1453,9 @@
"name": "stdout",
"output_type": "stream",
"text": [
"{'event': 'on_chain_start', 'data': {'input': '1234'}, 'name': 'reverse_and_double', 'tags': [], 'run_id': '1bfcaedc-f4aa-4d8e-beee-9bba6ef17008', 'metadata': {}}\n",
"{'event': 'on_chain_start', 'data': {'input': '1234'}, 'name': 'reverse_word', 'tags': [], 'run_id': '64fc99f0-5d7d-442b-b4f5-4537129f67d1', 'metadata': {}}\n",
"{'event': 'on_chain_end', 'data': {'output': '4321', 'input': '1234'}, 'run_id': '64fc99f0-5d7d-442b-b4f5-4537129f67d1', 'name': 'reverse_word', 'tags': [], 'metadata': {}}\n",
"{'event': 'on_chain_stream', 'data': {'chunk': '43214321'}, 'run_id': '1bfcaedc-f4aa-4d8e-beee-9bba6ef17008', 'name': 'reverse_and_double', 'tags': [], 'metadata': {}}\n",
"{'event': 'on_chain_end', 'data': {'output': '43214321'}, 'run_id': '1bfcaedc-f4aa-4d8e-beee-9bba6ef17008', 'name': 'reverse_and_double', 'tags': [], 'metadata': {}}\n"
"{'event': 'on_chain_start', 'data': {'input': '1234'}, 'name': 'reverse_and_double', 'tags': [], 'run_id': '25f72976-aa79-408d-bb42-6d0f038cde52', 'metadata': {}, 'parent_ids': []}\n",
"{'event': 'on_chain_stream', 'run_id': '25f72976-aa79-408d-bb42-6d0f038cde52', 'name': 'reverse_and_double', 'tags': [], 'metadata': {}, 'data': {'chunk': '43214321'}, 'parent_ids': []}\n",
"{'event': 'on_chain_end', 'data': {'output': '43214321'}, 'run_id': '25f72976-aa79-408d-bb42-6d0f038cde52', 'name': 'reverse_and_double', 'tags': [], 'metadata': {}, 'parent_ids': []}\n"
]
}
],
@ -1513,7 +1489,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -1527,7 +1503,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.4"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -94,7 +94,7 @@
"\n",
"from langchain_anthropic import ChatAnthropic\n",
"\n",
"llm = ChatAnthropic(model=\"claude-3-sonnet-20240229\", temperature=0)"
"llm = ChatAnthropic(model=\"claude-3-7-sonnet-20250219\", temperature=0)"
]
},
{
@ -108,11 +108,12 @@
"text/plain": [
"[{'name': 'count_emails',\n",
" 'args': {'last_n_days': 5},\n",
" 'id': 'toolu_01QYZdJ4yPiqsdeENWHqioFW',\n",
" 'id': 'toolu_01XrE4AU9QLo4imbriDDkmXm',\n",
" 'type': 'tool_call',\n",
" 'output': 10}]"
]
},
"execution_count": 3,
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
@ -299,7 +300,7 @@
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"display_name": "langchain",
"language": "python",
"name": "python3"
},
@ -313,7 +314,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.4"
"version": "3.10.16"
}
},
"nbformat": 4,

View File

@ -8,7 +8,6 @@
pip install awadb
```
## Vector store
```python
@ -17,7 +16,6 @@ from langchain_community.vectorstores import AwaDB
See a [usage example](/docs/integrations/vectorstores/awadb).
## Embedding models
```python

View File

@ -21,8 +21,8 @@ fine-tuned models on dedicated GPUs. If you're used to a provider like OpenAI, u
You'll need two things to use Baseten models with LangChain:
- A [Baseten account](https://baseten.co)
- An [API key](https://docs.baseten.co/observability/api-keys)
* A [Baseten account](https://baseten.co)
* An [API key](https://docs.baseten.co/observability/api-keys)
Export your API key to your as an environment variable called `BASETEN_API_KEY`.

View File

@ -6,7 +6,6 @@
>Behind the scenes, `Breebs` implements several `Retrieval Augmented Generation (RAG)` models
> to seamlessly provide useful context at each iteration.
## Retriever
```python

View File

@ -52,7 +52,6 @@ llm = Databricks(endpoint="your-completion-endpoint")
See the [usage example](/docs/integrations/llms/databricks) for more guidance on how to use it within your LangChain application.
Embeddings
----------
@ -66,7 +65,6 @@ embeddings = DatabricksEmbeddings(endpoint="databricks-bge-large-en")
See the [usage example](/docs/integrations/text_embedding/databricks) for more guidance on how to use it within your LangChain application.
Vector Search
-------------
@ -88,7 +86,6 @@ docs = dvs.similarity_search("What is vector search?)
See the [usage example](/docs/integrations/vectorstores/databricks_vector_search) for how to set up vector indices and integrate them with LangChain.
MLflow Integration
------------------
@ -103,6 +100,7 @@ See [MLflow LangChain Integration](/docs/integrations/providers/mlflow_tracking)
SQLDatabase
-----------
To connect to Databricks SQL or query structured data, see the [Databricks structured retriever tool documentation](https://docs.databricks.com/en/generative-ai/agent-framework/structured-retrieval-tools.html#table-query-tool) and to create an agent using the above created SQL UDF see [Databricks UC Integration](https://docs.unitycatalog.io/ai/integrations/langchain/).
Open Models

View File

@ -19,7 +19,6 @@ pip install fiddler-client
## Callbacks
```python
from langchain_community.callbacks.fiddler_callback import FiddlerCallbackHandler
```

View File

@ -9,7 +9,7 @@
- Install the Fireworks integration package.
```
```bash
pip install langchain-fireworks
```

View File

@ -13,6 +13,7 @@ Deployment of Marqo is flexible, you can get started yourself with our docker im
To run Marqo locally with our docker image, [see our getting started.](https://docs.marqo.ai/latest/)
## Installation and Setup
- Install the Python SDK with `pip install marqo`
## Wrappers
@ -24,6 +25,7 @@ There exists a wrapper around Marqo indexes, allowing you to use them within the
The Marqo vectorstore can also work with existing multimodal indexes where your documents have a mix of images and text, for more information refer to [our documentation](https://docs.marqo.ai/latest/#multi-modal-and-cross-modal-search). Note that instantiating the Marqo vectorstore with an existing multimodal index will disable the ability to add any new documents to it via the langchain vectorstore `add_texts` method.
To import this vectorstore:
```python
from langchain_community.vectorstores import Marqo
```

View File

@ -8,7 +8,7 @@
- Install the Pipeshift integration package.
```
```bash
pip install langchain-pipeshift
```

View File

@ -3,6 +3,7 @@
Learn how to use LangChain with models on Predibase.
## Setup
- Create a [Predibase](https://predibase.com/) account and [API key](https://docs.predibase.com/sdk-guide/intro).
- Install the Predibase Python client with `pip install predibase`
- Use your API key to authenticate

View File

@ -5,6 +5,7 @@ SWI-Prolog offers a comprehensive free Prolog environment.
## Installation and Setup
Once SWI-Prolog has been installed, install lanchain-prolog using pip:
```bash
pip install langchain-prolog
```

View File

@ -10,14 +10,14 @@ This page covers how Shale-Serve API can be incorporated with LangChain.
As of June 2023, the API supports Vicuna-13B by default. We are going to support more LLMs such as Falcon-40B in future releases.
## How to
### 1. Find the link to our Discord on https://shaleprotocol.com. Generate an API key through the "Shale Bot" on our Discord. No credit card is required and no free trials. It's a forever free tier with 1K limit per day per API key.
### 1. Find the link to our Discord on https://shaleprotocol.com. Generate an API key through the "Shale Bot" on our Discord. No credit card is required and no free trials. It's a forever free tier with 1K limit per day per API key
### 2. Use https://shale.live/v1 as OpenAI API drop-in replacement
For example
```python
from langchain_openai import OpenAI
from langchain_core.prompts import PromptTemplate

View File

@ -638,7 +638,7 @@
"\n",
"For guides on how to use this vector store for retrieval-augmented generation (RAG), see the following sections:\n",
"\n",
"- [Tutorials](/docs/tutorials/)\n",
"- [Tutorials](/docs/tutorials/rag)\n",
"- [How-to: Question and answer with RAG](https://python.langchain.com/docs/how_to/#qa-with-rag)\n",
"- [Retrieval conceptual docs](https://python.langchain.com/docs/concepts/retrieval)"
]

View File

@ -34,8 +34,8 @@ we hope that it will help you migrate your code more quickly.
The migration script has the following limitations:
1. Its limited to helping users move from old imports to new imports. It does not help address other deprecations.
2. It cant handle imports that involve `as` .
1. It's limited to helping users move from old imports to new imports. It does not help address other deprecations.
2. It can't handle imports that involve `as` .
3. New imports are always placed in global scope, even if the old import that was replaced was located inside some local scope (e..g, function body).
4. It will likely miss some deprecated imports.
@ -66,8 +66,8 @@ You will need to run the migration script **twice** as it only applies one impor
For example, say your code still uses `from langchain.chat_models import ChatOpenAI`:
After the first run, youll get: `from langchain_community.chat_models import ChatOpenAI`
After the second run, youll get: `from langchain_openai import ChatOpenAI`
After the first run, you'll get: `from langchain_community.chat_models import ChatOpenAI`
After the second run, you'll get: `from langchain_openai import ChatOpenAI`
```bash
# Run a first time

View File

@ -10,7 +10,7 @@
**These are the only breaking changes.**
## Whats new
## What's new
The following features have been added during the development of 0.2.x:
@ -95,7 +95,7 @@ well as updating the `langchain_core.pydantic_v1` and `langchain.pydantic_v1` im
Once you've updated to recent versions of the packages, you may need to address the following issues stemming from the internal switch from Pydantic v1 to Pydantic v2:
- If your code depends on Pydantic aside from LangChain, you will need to upgrade your pydantic version constraints to be `pydantic>=2,<3`. See [Pydantics migration guide](https://docs.pydantic.dev/latest/migration/) for help migrating your non-LangChain code to Pydantic v2 if you use pydantic v1.
- If your code depends on Pydantic aside from LangChain, you will need to upgrade your pydantic version constraints to be `pydantic>=2,<3`. See [Pydantic's migration guide](https://docs.pydantic.dev/latest/migration/) for help migrating your non-LangChain code to Pydantic v2 if you use pydantic v1.
- There are a number of side effects to LangChain components caused by the internal switch from Pydantic v1 to v2. We have listed some of the common cases below together with the recommended solutions.
## Common issues when transitioning to Pydantic 2
@ -246,8 +246,8 @@ You will need to run the migration script **twice** as it only applies one impor
For example, say that your code is still using the old import `from langchain.chat_models import ChatOpenAI`:
After the first run, youll get: `from langchain_community.chat_models import ChatOpenAI`
After the second run, youll get: `from langchain_openai import ChatOpenAI`
After the first run, you'll get: `from langchain_community.chat_models import ChatOpenAI`
After the second run, you'll get: `from langchain_openai import ChatOpenAI`
```bash
# Run a first time

View File

@ -67,12 +67,11 @@ def serve(
] = None,
) -> None:
"""Start the LangServe app, whether it's a template or an app."""
# see if is a template
try:
project_dir = get_package_root()
pyproject = project_dir / "pyproject.toml"
get_langserve_export(pyproject)
except KeyError:
except (KeyError, FileNotFoundError):
# not a template
app_namespace.serve(port=port, host=host)
else:

View File

@ -61,6 +61,7 @@ class __ModuleName__Loader(BaseLoader):
.. code-block:: python
TODO: Example output
""" # noqa: E501
# TODO: This method must be implemented to load documents.

View File

@ -61,6 +61,7 @@ class __ModuleName__Tool(BaseTool): # type: ignore[override]
.. code-block:: python
# TODO: output of invocation
""" # noqa: E501
# TODO: Set tool name and description

View File

@ -408,7 +408,7 @@ wheels = [
[[package]]
name = "langchain"
version = "0.3.26"
version = "0.3.27"
source = { editable = "../langchain" }
dependencies = [
{ name = "async-timeout", marker = "python_full_version < '3.11'" },

View File

@ -70,6 +70,7 @@ def beta(
@beta
def the_function_to_annotate():
pass
"""
def beta(

View File

@ -136,6 +136,7 @@ def deprecated(
@deprecated('1.4.0')
def the_function_to_deprecate():
pass
"""
_validate_deprecation_params(
removal, alternative, alternative_import, pending=pending
@ -549,6 +550,7 @@ def rename_parameter(
@_api.rename_parameter("3.1", "bad_name", "good_name")
def func(good_name): ...
"""
def decorator(f: Callable[_P, _R]) -> Callable[_P, _R]:

View File

@ -363,6 +363,7 @@ class Context:
print(output["result"]) # Output: "hello"
print(output["context"]) # Output: "What's your name?"
print(output["input"]) # Output: "What's your name?
"""
@staticmethod

View File

@ -53,6 +53,7 @@ class FileCallbackHandler(BaseCallbackHandler):
When not used as a context manager, a deprecation warning will be issued
on first use. The file will be opened immediately in ``__init__`` and closed
in ``__del__`` or when ``close()`` is called explicitly.
"""
def __init__(

View File

@ -105,6 +105,7 @@ def trace_as_chain_group(
# Use the callback manager for the chain group
res = llm.invoke(llm_input, {"callbacks": manager})
manager.on_chain_end({"output": res})
""" # noqa: E501
from langchain_core.tracers.context import _get_trace_callbacks
@ -186,6 +187,7 @@ async def atrace_as_chain_group(
# Use the async callback manager for the chain group
res = await llm.ainvoke(llm_input, {"callbacks": manager})
await manager.on_chain_end({"output": res})
""" # noqa: E501
from langchain_core.tracers.context import _get_trace_callbacks
@ -2575,6 +2577,7 @@ async def adispatch_custom_event(
behalf.
.. versionadded:: 0.2.15
"""
from langchain_core.runnables.config import (
ensure_config,
@ -2645,6 +2648,7 @@ def dispatch_custom_event(
foo_.invoke({"a": "1"}, {"callbacks": [CustomCallbackManager()]})
.. versionadded:: 0.2.15
"""
from langchain_core.runnables.config import (
ensure_config,

View File

@ -44,6 +44,7 @@ class UsageMetadataCallbackHandler(BaseCallbackHandler):
'input_token_details': {'cache_read': 0, 'cache_creation': 0}}}
.. versionadded:: 0.3.49
"""
def __init__(self) -> None:
@ -127,6 +128,7 @@ def get_usage_metadata_callback(
'input_token_details': {'cache_read': 0, 'cache_creation': 0}}}
.. versionadded:: 0.3.49
"""
from langchain_core.tracers.context import register_configure_hook

View File

@ -91,6 +91,7 @@ class BaseChatMessageHistory(ABC):
def clear(self):
with open(os.path.join(storage_path, session_id), "w") as f:
f.write("[]")
"""
messages: list[BaseMessage]

View File

@ -36,6 +36,7 @@ class LangSmithLoader(BaseLoader):
# -> [Document("...", metadata={"inputs": {...}, "outputs": {...}, ...}), ...]
.. versionadded:: 0.2.34
""" # noqa: E501
def __init__(

View File

@ -102,6 +102,7 @@ class Blob(BaseMedia):
# Read the blob as a byte stream
with blob.as_bytes_io() as f:
print(f.read())
"""
data: Union[bytes, str, None] = None
@ -265,6 +266,7 @@ class Document(BaseMedia):
page_content="Hello, world!",
metadata={"source": "https://example.com"}
)
"""
page_content: str

View File

@ -46,6 +46,7 @@ class FakeEmbeddings(Embeddings, BaseModel):
2
[-0.5670477847544458, -0.31403828652395727, -0.5840547508955257]
"""
size: int
@ -103,6 +104,7 @@ class DeterministicFakeEmbedding(Embeddings, BaseModel):
2
[-0.5670477847544458, -0.31403828652395727, -0.5840547508955257]
"""
size: int

View File

@ -444,6 +444,9 @@ def index(
scoped_full_cleanup_source_ids: set[str] = set()
for doc_batch in _batch(batch_size, doc_iterator):
# Track original batch size before deduplication
original_batch_size = len(doc_batch)
hashed_docs = list(
_deduplicate_in_order(
[
@ -452,6 +455,8 @@ def index(
]
)
)
# Count documents removed by within-batch deduplication
num_skipped += original_batch_size - len(hashed_docs)
source_ids: Sequence[Optional[str]] = [
source_id_assigner(hashed_doc) for hashed_doc in hashed_docs
@ -784,6 +789,9 @@ async def aindex(
scoped_full_cleanup_source_ids: set[str] = set()
async for doc_batch in _abatch(batch_size, async_doc_iterator):
# Track original batch size before deduplication
original_batch_size = len(doc_batch)
hashed_docs = list(
_deduplicate_in_order(
[
@ -792,6 +800,8 @@ async def aindex(
]
)
)
# Count documents removed by within-batch deduplication
num_skipped += original_batch_size - len(hashed_docs)
source_ids: Sequence[Optional[str]] = [
source_id_assigner(doc) for doc in hashed_docs

View File

@ -51,6 +51,7 @@ def _parse_data_uri(uri: str) -> Optional[dict]:
"mime_type": "image/jpeg",
"data": "/9j/4AAQSkZJRg...",
}
"""
regex = r"^data:(?P<mime_type>[^;]+);base64,(?P<data>.+)$"
match = re.match(regex, uri)

View File

@ -1467,6 +1467,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
.. versionchanged:: 0.2.26
Added support for TypedDict class.
""" # noqa: E501
_ = kwargs.pop("method", None)
_ = kwargs.pop("strict", None)

View File

@ -1418,6 +1418,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
.. code-block:: python
llm.save(file_path="path/llm.yaml")
"""
# Convert file to Path object.
save_path = Path(file_path)

View File

@ -53,6 +53,7 @@ class BaseMemory(Serializable, ABC):
def clear(self) -> None:
pass
""" # noqa: E501
model_config = ConfigDict(

View File

@ -57,6 +57,7 @@ class InputTokenDetails(TypedDict, total=False):
.. versionadded:: 0.3.9
May also hold extra provider-specific keys.
"""
audio: int
@ -89,6 +90,7 @@ class OutputTokenDetails(TypedDict, total=False):
}
.. versionadded:: 0.3.9
"""
audio: int
@ -128,6 +130,7 @@ class UsageMetadata(TypedDict):
.. versionchanged:: 0.3.9
Added ``input_token_details`` and ``output_token_details``.
"""
input_tokens: int

View File

@ -28,6 +28,7 @@ class HumanMessage(BaseMessage):
# Instantiate a chat model and invoke it with the messages
model = ...
print(model.invoke(messages))
"""
example: bool = False

View File

@ -59,6 +59,7 @@ class ToolMessage(BaseMessage, ToolOutputMixin):
The tool_call_id field is used to associate the tool call request with the
tool call response. This is useful in situations where a chat model is able
to request multiple tool calls in parallel.
""" # noqa: E501
tool_call_id: str
@ -191,6 +192,7 @@ class ToolCall(TypedDict):
This represents a request to call the tool named "foo" with arguments {"a": 1}
and an identifier of "123".
"""
name: str
@ -240,6 +242,7 @@ class ToolCallChunk(TypedDict):
AIMessageChunk(content="", tool_call_chunks=left_chunks)
+ AIMessageChunk(content="", tool_call_chunks=right_chunks)
).tool_call_chunks == [ToolCallChunk(name='foo', args='{"a":1}', index=0)]
"""
name: Optional[str]

View File

@ -111,6 +111,7 @@ def get_buffer_string(
]
get_buffer_string(messages)
# -> "Human: Hi, how are you?\nAI: Good, how are you?"
"""
string_messages = []
for m in messages:
@ -463,6 +464,7 @@ def filter_messages(
SystemMessage("you're a good assistant."),
HumanMessage("what's your name", id="foo", name="example_user"),
]
""" # noqa: E501
messages = convert_to_messages(messages)
filtered: list[BaseMessage] = []
@ -869,6 +871,7 @@ def trim_messages(
HumanMessage("This is a 4 token text. The full message is 10 tokens.", id="first"),
AIMessage( [{"type": "text", "text": "This is the FIRST 4 token block."}], id="second"),
]
""" # noqa: E501
# Validate arguments
if start_on and strategy == "first":

View File

@ -155,6 +155,7 @@ class BaseOutputParser(
@property
def _type(self) -> str:
return "boolean_output_parser"
""" # noqa: E501
@property

View File

@ -214,6 +214,7 @@ class PydanticOutputFunctionsParser(OutputFunctionsParser):
pydantic_schema={"cookie": Cookie, "dog": Dog}
)
result = parser.parse_result([chat_generation])
"""
pydantic_schema: Union[type[BaseModel], dict[str, type[BaseModel]]]

View File

@ -307,6 +307,7 @@ class BasePromptTemplate(
.. code-block:: python
prompt.format(variable1="foo")
"""
async def aformat(self, **kwargs: Any) -> FormatOutputType:
@ -323,6 +324,7 @@ class BasePromptTemplate(
.. code-block:: python
await prompt.aformat(variable1="foo")
"""
return self.format(**kwargs)
@ -363,6 +365,7 @@ class BasePromptTemplate(
.. code-block:: python
prompt.save(file_path="path/prompt.yaml")
"""
if self.partial_variables:
msg = "Cannot save prompt with partial variables."
@ -442,6 +445,7 @@ def format_document(doc: Document, prompt: BasePromptTemplate[str]) -> str:
prompt = PromptTemplate.from_template("Page {page}: {page_content}")
format_document(doc, prompt)
>>> "Page 1: This is a joke"
"""
return prompt.format(**_get_document_info(doc, prompt))

View File

@ -126,6 +126,7 @@ class MessagesPlaceholder(BaseMessagePromptTemplate):
# -> [
# HumanMessage(content="Hello!"),
# ]
"""
variable_name: str
@ -1164,6 +1165,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
Returns:
a chat prompt template.
"""
return cls(messages, template_format=template_format)
@ -1248,6 +1250,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
template2 = template.partial(user="Lucy", name="R2D2")
template2.format_messages(input="hello")
"""
prompt_dict = self.__dict__.copy()
prompt_dict["input_variables"] = list(

View File

@ -357,6 +357,7 @@ class FewShotChatMessagePromptTemplate(
from langchain_core.chat_models import ChatAnthropic
chain = final_prompt | ChatAnthropic(model="claude-3-haiku-20240307")
chain.invoke({"input": "What's 3+3?"})
"""
input_variables: list[str] = Field(default_factory=list)

View File

@ -122,6 +122,7 @@ class FewShotPromptWithTemplates(StringPromptTemplate):
.. code-block:: python
prompt.format(variable1="foo")
"""
kwargs = self._merge_partial_and_user_variables(**kwargs)
# Get the examples to use.

View File

@ -90,6 +90,7 @@ class ImagePromptTemplate(BasePromptTemplate[ImageURL]):
.. code-block:: python
prompt.format(variable1="foo")
"""
formatted = {}
for k, v in self.template.items():

View File

@ -45,6 +45,7 @@ class PipelinePromptTemplate(BasePromptTemplate):
Each PromptTemplate will be formatted and then passed
to future prompt templates as a variable with
the same name as `name`
"""
final_prompt: BasePromptTemplate

View File

@ -56,6 +56,7 @@ class PromptTemplate(StringPromptTemplate):
# Instantiation using initializer
prompt = PromptTemplate(template="Say {foo}")
"""
@property

View File

@ -115,6 +115,7 @@ class StructuredPrompt(ChatPromptTemplate):
Returns:
a structured prompt template
"""
return cls(messages, schema, **kwargs)

View File

@ -123,6 +123,7 @@ class InMemoryRateLimiter(BaseRateLimiter):
.. versionadded:: 0.2.24
""" # noqa: E501
def __init__(

View File

@ -124,6 +124,7 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):
# Op -- (n_docs,1) -- Cosine Sim with each doc
results = cosine_similarity(self.tfidf_array, query_vec).reshape((-1,))
return [self.docs[i] for i in results.argsort()[-self.k :][::-1]]
""" # noqa: E501
model_config = ConfigDict(
@ -230,6 +231,7 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):
.. code-block:: python
retriever.invoke("query")
"""
from langchain_core.callbacks.manager import CallbackManager
@ -294,6 +296,7 @@ class BaseRetriever(RunnableSerializable[RetrieverInput, RetrieverOutput], ABC):
.. code-block:: python
await retriever.ainvoke("query")
"""
from langchain_core.callbacks.manager import AsyncCallbackManager

Some files were not shown because too many files have changed in this diff Show More