Skip to main content

AWS (Amazon) integrations

还没翻译译自英文(docs.langchain.com)本页 74 段都还没译

This page covers all LangChain integrations with the Amazon Web Services (AWS) platform.

Chat models

Bedrock Mantle

The AWS Bedrock Mantle API exposes models through the OpenAI and Anthropic Messages protocols. ChatOpenAIMantle and ChatAnthropicMantle are the recommended interfaces for accessing these models.

Both classes accept a Bedrock API key via the bedrock_api_key parameter or the AWS_BEARER_TOKEN_BEDROCK environment variable. When neither is available, both derive short-lived API keys from standard AWS credentials and refresh them transparently.

ChatOpenAIMantle inherits from BaseChatOpenAI. See the corresponding Responses API docs for usage examples and capabilities. Refer to the AWS Mantle OpenAI-compatible API docs for supported models.

ChatAnthropicMantle inherits from ChatAnthropic and targets the Anthropic Messages endpoint on Mantle. See the ChatAnthropic docs for usage examples and capabilities. Refer to the AWS Mantle Anthropic API docs for supported models.

from langchain_aws import ChatOpenAIMantle, ChatAnthropicMantle

openai_model = ChatOpenAIMantle(
    model="openai.gpt-5.6-luna",
    region_name="us-east-1",
)

anthropic_model = ChatAnthropicMantle(
    model="anthropic.claude-opus-5-5",
    region_name="us-east-1",
)

Bedrock Converse

Amazon Bedrock is a fully managed service that offers a choice of high-performing foundation models (FMs) from leading AI companies like AI21 Labs, Anthropic, Cohere, Meta, OpenAI, Stability AI, and Amazon via a single API. Since Amazon Bedrock is serverless, you don't have to manage any infrastructure, and you can securely integrate and deploy generative AI capabilities into your applications using the AWS services you are already familiar with.

AWS Bedrock maintains a Converse API that provides a unified conversational interface for Bedrock models. You can see a list of all models that are supported here.

See a usage example.

from langchain_aws import ChatBedrockConverse

Embedding models

Bedrock

See a usage example.

from langchain_aws import BedrockEmbeddings

Document loaders

Amazon MemoryDB

Amazon MemoryDB is a durable, in-memory database service that delivers ultra-fast performance. MemoryDB is compatible with Redis OSS, a popular open source data store, enabling you to quickly build applications using the same flexible and friendly Redis OSS APIs, and commands that they already use today.

InMemoryVectorStore class provides a vectorstore to connect with Amazon MemoryDB.

from langchain_aws.vectorstores.inmemorydb import InMemoryVectorStore

vds = InMemoryVectorStore.from_documents(
            chunks,
            embeddings,
            redis_url="rediss://cluster_endpoint:6379/ssl=True ssl_cert_reqs=none",
            vector_schema=vector_schema,
            index_name=INDEX_NAME,
        )

See a usage example.

Valkey

Valkey is an open source, high-performance key/value datastore that supports workloads such as caching, message queues, and can act as a primary database. Use ValkeyVectorStore to connect with Amazon ElastiCache for Valkey or Amazon MemoryDB for Valkey.

from langchain_aws.vectorstores import ValkeyVectorStore

See a usage example.

Retrievers

Amazon Bedrock (Knowledge bases)

Knowledge bases for Amazon Bedrock is an Amazon Web Services (AWS) offering which lets you quickly build RAG applications by using your private data to customize foundation model response.

We need to install the langchain-aws library.

pip install langchain-aws
uv add langchain-aws

See a usage example.

from langchain_aws import AmazonKnowledgeBasesRetriever

Tools

Amazon Bedrock AgentCore Browser

Amazon Bedrock AgentCore Browser enables agents to interact with web pages through a managed Chrome browser for navigation, content extraction, and web automation.

pip install langchain-aws bedrock-agentcore playwright beautifulsoup4
uv add langchain-aws bedrock-agentcore playwright beautifulsoup4

See a usage example.

from langchain.agents import create_agent
from langchain_aws.tools import create_browser_toolkit

# Create toolkit
toolkit, browser_tools = create_browser_toolkit(region="us-west-2")

# Use with an agent
agent = create_agent(model=llm, tools=browser_tools)
result = await agent.ainvoke(
    {"messages": [{"role": "user", "content": "Go to example.com and get the heading"}]},
    config={"configurable": {"thread_id": "session-1"}}
)

# Cleanup when done
await toolkit.cleanup()

Amazon Bedrock AgentCore Code Interpreter

Amazon Bedrock AgentCore Code Interpreter enables agents to execute Python, JavaScript, and TypeScript code in secure, managed sandbox environments for calculations, data analysis, and visualizations.

pip install langchain-aws bedrock-agentcore
uv add langchain-aws bedrock-agentcore

See a usage example.

from langchain.agents import create_agent
from langchain_aws.tools import create_code_interpreter_toolkit

# Create toolkit (async)
toolkit, code_tools = await create_code_interpreter_toolkit(region="us-west-2")

# Use with an agent
agent = create_agent(model=llm, tools=code_tools)
result = await agent.ainvoke(
    {"messages": [{"role": "user", "content": "Calculate factorial of 10"}]},
    config={"configurable": {"thread_id": "session-1"}}
)

# Cleanup when done
await toolkit.cleanup()

Amazon Bedrock AgentCore Web Search gives agents current information from the web with a source URL on every result, authenticated with your AWS credentials rather than a search API key.

pip install langchain-aws bedrock-agentcore
uv add langchain-aws bedrock-agentcore

See a usage example.

from langchain.agents import create_agent
from langchain_aws.tools import create_web_search_toolkit

# Needs a gateway with a web search connector target. The factory is synchronous.
toolkit, tools = create_web_search_toolkit(
    region="us-east-1",
    gateway_id="my-web-search-gateway-abc123",
)

try:
    agent = create_agent(model=llm, tools=tools)
    result = agent.invoke(
        {"messages": [{"role": "user", "content": "What changed in the most recent boto3 release?"}]}
    )
finally:
    toolkit.close()

Sandboxes

AgentCoreSandbox

Amazon Bedrock AgentCore Code Interpreter sandbox backend for deepagents.

Graphs

Amazon neptune

Amazon Neptune is a high-performance graph analytics and serverless database for superior scalability and availability.

For the Cypher and SPARQL integrations below, we need to install the langchain-aws library.

pip install langchain-aws
uv add langchain-aws

Amazon neptune with cypher

See a usage example.

from langchain_aws.graphs import NeptuneGraph
from langchain_aws.graphs import NeptuneAnalyticsGraph
from langchain_aws.chains import create_neptune_opencypher_qa_chain

Amazon neptune with SPARQL

from langchain_aws.graphs import NeptuneRdfGraph
from langchain_aws.chains import create_neptune_sparql_qa_chain

Memory

Amazon Bedrock AgentCore Memory

Amazon Bedrock AgentCore Memory provides managed persistence for LangGraph agents, enabling conversation history and state management across sessions with automatic scaling and high availability.

pip install langgraph-checkpoint-aws
uv add langgraph-checkpoint-aws
from langgraph_checkpoint_aws import AgentCoreMemorySaver

# Create checkpointer
checkpointer = AgentCoreMemorySaver(
    memory_id="your-memory-id",
    region_name="us-west-2"
)

# Use with LangGraph
graph = workflow.compile(checkpointer=checkpointer)

# Invoke with thread_id and actor_id for conversation persistence
config = {
    "configurable": {
        "thread_id": "user-123",
        "actor_id": "my-agent"  # Required for AgentCore
    }
}
result = graph.invoke({"messages": []}, config)

Key features:

  • Managed infrastructure with no database setup required
  • Automatic scaling and high availability
  • Multi-agent support via actor_id isolation
  • Encryption at rest and in transit

Amazon Bedrock AgentCore Memory Store

Amazon Bedrock AgentCore Memory Store provides long-term memory with semantic search capabilities for LangGraph agents, enabling storage and retrieval of user preferences, facts, and extracted memories across sessions.

from langgraph_checkpoint_aws import AgentCoreMemoryStore

# Initialize store for long-term memories
store = AgentCoreMemoryStore(memory_id="your-memory-id", region_name="us-west-2")

# Use in a pre-model hook to save and retrieve memories
def pre_model_hook(state, config, *, store):
    actor_id = config["configurable"]["actor_id"]
    thread_id = config["configurable"]["thread_id"]
    namespace = (actor_id, thread_id)

    # Save a message
    store.put(namespace, str(uuid.uuid4()), {"message": msg})

    # Search for relevant memories
    results = store.search(("preferences", actor_id), query="user preferences", limit=5)
    return {"model_input_messages": state["messages"]}

Chains

Amazon Comprehend moderation chain

Amazon Comprehend is a natural-language processing (NLP) service that uses machine learning to uncover valuable insights and connections in text.

We need to install the boto3 and nltk libraries.

pip install boto3 nltk
uv add boto3 nltk

Warning

The langchain-experimental package is no longer maintained. Examples that import from langchain_experimental may be outdated or broken. Use with caution.

from langchain_experimental.comprehend_moderation import AmazonComprehendModerationChain

Runtime

Amazon Bedrock AgentCore Runtime

Amazon Bedrock AgentCore Runtime provides managed, serverless execution for LangGraph agents with built-in observability, automatic scaling, and seamless integration with other AgentCore services.

pip install bedrock-agentcore
uv add bedrock-agentcore
from bedrock_agentcore.runtime import BedrockAgentCoreApp

app = BedrockAgentCoreApp()

@app.entrypoint
def agent_invocation(payload, context):
    result = graph.invoke({"messages": [{"role": "user", "content": payload["prompt"]}]})
    return {"result": result["messages"][-1].content}

app.run()

Deploy using the AgentCore CLI:

# Configure your agent
agentcore configure

# Deploy to AgentCore Runtime
agentcore launch -e your_agent.py