- 工具调用 - 调用外部工具(如数据库查询或 API 调用)并在其响应中使用结果。
- 结构化输出 - 其中模型的响应被约束为遵循定义的格式。
- 多模态 - 处理和返回文本以外的数据,如图像、音频和视频。
- 推理 - 模型执行多步推理以得出结论。
有关提供商特定的集成信息和能力,请参阅提供商的聊天模型页面。
基本用法
模型可以通过两种方式使用:- 与智能体一起使用 - 在创建智能体时可以动态指定模型。
- 独立使用 - 可以直接调用模型(在智能体循环之外)进行文本生成、分类或提取等任务,而无需智能体框架。
初始化模型
在 LangChain 中开始使用独立模型的最简单方法是使用init_chat_model 从您选择的聊天模型提供商初始化一个(下面的示例):
- OpenAI
- Anthropic
- Azure
- Google Gemini
- AWS Bedrock
init_chat_model。
关键方法
调用 (Invoke)
模型将消息作为输入,并在生成完整响应后输出消息。
流式传输 (Stream)
调用模型,但在实时生成时流式传输输出。
批处理 (Batch)
批量向模型发送多个请求以实现更高效的处理。
除了聊天模型外,LangChain 还支持其他相关技术,如嵌入模型和向量存储。有关详细信息,请参阅集成页面。
参数
聊天模型采用可用于配置其行为的参数。支持的参数的完整集合因模型和提供商而异,但标准参数包括:您要使用的特定模型的名称或标识符。
与模型提供商进行身份验证所需的密钥。通常在您注册访问模型时颁发。通常通过设置来访问。
控制模型输出的随机性。较高的数字使响应更具创造性;较低的数字使它们更具确定性。
在取消请求之前等待模型响应的最长时间(以秒为单位)。
限制响应中的总数,有效控制输出的长度。
如果由于网络超时或速率限制等问题导致请求失败,系统将尝试重新发送请求的最大尝试次数。
init_chat_model,将这些参数作为内联传递:
Initialize using model parameters
每个聊天模型集成可能有用于控制提供商特定功能的额外参数。例如,
ChatOpenAI 具有 use_responses_api 来指示是使用 OpenAI Responses 还是 Completions API。要查找给定聊天模型支持的所有参数,请访问聊天模型集成页面。调用
必须调用聊天模型才能生成输出。有三种主要的调用方法,每种都适用于不同的用例。调用
调用模型最直接的方法是使用invoke() 和单个消息或消息列表。
Single message
Dictionary format
Message objects
流式传输
大多数模型可以在生成输出内容时流式传输它们。通过逐步显示输出,流式传输显著改善了用户体验,特别是对于较长的响应。 调用stream() 返回一个,该迭代器在生成输出块时产生它们。您可以使用循环实时处理每个块:
invoke() 相反,它在模型完成生成完整响应后返回单个 AIMessage,而 stream() 返回多个 AIMessageChunk 对象,每个对象包含输出文本的一部分。重要的是,流中的每个块都设计为通过求和聚合成完整消息:
Construct an AIMessage
invoke() 生成的消息相同的方式处理 - 例如,它可以聚合到消息历史记录中,并作为对话上下文传递回模型。
高级流式传输主题
高级流式传输主题
"自动流式传输"聊天模型
"自动流式传输"聊天模型
LangChain 通过在某些情况下自动启用流式传输模式来简化来自聊天模型的流式传输,即使您没有显式调用流式传输方法也是如此。当您使用非流式传输的 invoke 方法但仍希望流式传输整个应用程序(包括来自聊天模型的中间结果)时,这特别有用。例如,在 LangGraph 智能体中,您可以在节点内调用
model.invoke(),但如果以流式传输模式运行,LangChain 将自动委托给流式传输。工作原理
当您invoke() 聊天模型时,如果 LangChain 检测到您正在尝试流式传输整个应用程序,它将自动切换到内部流式传输模式。就使用 invoke 的代码而言,调用的结果将是相同的;但是,在流式传输聊天模型时,LangChain 将负责在 LangChain 的回调系统中调用 on_llm_new_token 事件。回调事件允许 LangGraph stream() 和 astream_events() 实时显示聊天模型的输出。流式传输事件
流式传输事件
批处理
将一组独立的请求批处理到模型可以显著提高性能并降低成本,因为处理可以并行完成:Batch
batch() 将仅返回整个批处理的最终输出。如果您想在每个单独输入完成生成时接收其输出,可以使用 batch_as_completed() 流式传输结果:
Yield batch responses upon completion
使用
batch_as_completed() 时,结果可能不按顺序到达。每个结果都包含输入索引,用于匹配以根据需要重建原始顺序。Tool calling
Models can request to call tools that perform tasks such as fetching data from a database, searching the web, or running code. Tools are pairings of:- A schema, including the name of the tool, a description, and/or argument definitions (often a JSON schema)
- A function or to execute.
You may hear the term “function calling”. We use this interchangeably with “tool calling”.
bind_tools(). In subsequent invocations, the model can choose to call any of the bound tools as needed.
Some model providers offer built-in tools that can be enabled via model or invocation parameters (e.g. ChatOpenAI, ChatAnthropic). Check the respective provider reference for details.
Binding user tools
Tool execution loop
Tool execution loop
When a model returns tool calls, you need to execute the tools and pass the results back to the model. This creates a conversation loop where the model can use tool results to generate its final response. LangChain includes agent abstractions that handle this orchestration for you.Here’s a simple example of how to do this:Each
Tool execution loop
ToolMessage returned by the tool includes a tool_call_id that matches the original tool call, helping the model correlate results with requests.Forcing tool calls
Forcing tool calls
By default, the model has the freedom to choose which bound tool to use based on the user’s input. However, you might want to force choosing a tool, ensuring the model uses either a particular tool or any tool from a given list:
Parallel tool calls
Parallel tool calls
Many models support calling multiple tools in parallel when appropriate. This allows the model to gather information from different sources simultaneously.The model intelligently determines when parallel execution is appropriate based on the independence of the requested operations.
Parallel tool calls
Streaming tool calls
Streaming tool calls
When streaming responses, tool calls are progressively built through You can accumulate chunks to build complete tool calls:
ToolCallChunk. This allows you to see tool calls as they’re being generated rather than waiting for the complete response.Streaming tool calls
Accumulate tool calls
Structured outputs
Models can be requested to provide their response in a format matching a given schema. This is useful for ensuring the output can be easily parsed and used in subsequent processing. LangChain supports multiple schema types and methods for enforcing structured outputs.- Pydantic
- TypedDict
- JSON Schema
Pydantic models provide the richest feature set with field validation, descriptions, and nested structures.
Key considerations for structured outputs:
- Method parameter: Some providers support different methods (
'json_schema','function_calling','json_mode')'json_schema'typically refers to dedicated structured output features offered by a provider'function_calling'derives structured output by forcing a tool call following the given schema'json_mode'is a precursor to'json_schema'offered by some providers- it generates valid json, but the schema must be described in the prompt
- Include raw: Use
include_raw=Trueto get both the parsed output and the raw AI message - Validation: Pydantic models provide automatic validation, while
TypedDictand JSON Schema require manual validation
Example: Message output alongside parsed structure
Example: Message output alongside parsed structure
It can be useful to return the raw
AIMessage object alongside the parsed representation to access response metadata such as token counts. To do this, set include_raw=True when calling with_structured_output:Example: Nested structures
Example: Nested structures
Schemas can be nested:
Supported models
LangChain supports all major model providers, including OpenAI, Anthropic, Google, Azure, AWS Bedrock, and more. Each provider offers a variety of models with different capabilities. For a full list of supported models in LangChain, see the integrations page.Advanced topics
Multimodal
Certain models can process and return non-textual data such as images, audio, and video. You can pass non-textual data to a model by providing content blocks. See the multimodal section of the messages guide for details. can return multimodal data as part of their response. If invoked to do so, the resultingAIMessage will have content blocks with multimodal types.
Multimodal output
Reasoning
Newer models are capable of performing multi-step reasoning to arrive at a conclusion. This involves breaking down complex problems into smaller, more manageable steps. If supported by the underlying model, you can surface this reasoning process to better understand how the model arrived at its final answer.'low' or 'high') or integer token budgets.
For details, see the integrations page or reference for your respective chat model.
Local models
LangChain supports running models locally on your own hardware. This is useful for scenarios where either data privacy is critical, you want to invoke a custom model, or when you want to avoid the costs incurred when using a cloud-based model. Ollama is one of the easiest ways to run models locally. See the full list of local integrations on the integrations page.Prompt caching
Many providers offer prompt caching features to reduce latency and cost on repeat processing of the same tokens. These features can be implicit or explicit:- Implicit prompt caching: providers will automatically pass on cost savings if a request hits a cache. Examples: OpenAI and Gemini (Gemini 2.5 and above).
- Explicit caching: providers allow you to manually indicate cache points for greater control or to guarantee cost savings. Examples:
ChatOpenAI(viaprompt_cache_key), Anthropic’sAnthropicPromptCachingMiddlewareandcache_controloptions, AWS Bedrock, Gemini.
Server-side tool use
Some providers support server-side tool-calling loops: models can interact with web search, code interpreters, and other tools and analyze the results in a single conversational turn. If a model invokes a tool server-side, the content of the response message will include content representing the invocation and result of the tool. Accessing the content blocks of the response will return the server-side tool calls and results in a provider-agnostic format:Invoke with server-side tool use
Result
Rate limiting
Many chat model providers impose a limit on the number of invocations that can be made in a given time period. If you hit a rate limit, you will typically receive a rate limit error response from the provider, and will need to wait before making more requests. To help manage rate limits, chat model integrations accept arate_limiter parameter that can be provided during initialization to control the rate at which requests are made.
Initialize and use a rate limiter
Initialize and use a rate limiter
LangChain in comes with (an optional) built-in
InMemoryRateLimiter. This limiter is thread safe and can be shared by multiple threads in the same process.Define a rate limiter
Base URL or proxy
For many chat model integrations, you can configure the base URL for API requests, which allows you to use model providers that have OpenAI-compatible APIs or to use a proxy server.Base URL
Base URL
Many model providers offer OpenAI-compatible APIs (e.g., Together AI, vLLM). You can use
init_chat_model with these providers by specifying the appropriate base_url parameter:When using direct chat model class instantiation, the parameter name may vary by provider. Check the respective reference for details.
Proxy configuration
Proxy configuration
For deployments requiring HTTP proxies, some model integrations support proxy configuration:
Proxy support varies by integration. Check the specific model provider’s reference for proxy configuration options.
Log probabilities
Certain models can be configured to return token-level log probabilities representing the likelihood of a given token by setting thelogprobs parameter when initializing the model:
Token usage
A number of model providers return token usage information as part of the invocation response. When available, this information will be included on theAIMessage objects produced by the corresponding model. For more details, see the messages guide.
Some provider APIs, notably OpenAI and Azure OpenAI chat completions, require users opt-in to receiving token usage data in streaming contexts. See the streaming usage metadata section of the integration guide for details.
- Callback handler
- Context manager
Invocation config
When invoking a model, you can pass additional configuration through theconfig parameter using a RunnableConfig dictionary. This provides run-time control over execution behavior, callbacks, and metadata tracking.
Common configuration options include:
Invocation with config
- Debugging with LangSmith tracing
- Implementing custom logging or monitoring
- Controlling resource usage in production
- Tracking invocations across complex pipelines
Key configuration attributes
Key configuration attributes
Identifies this specific invocation in logs and traces. Not inherited by sub-calls.
Labels inherited by all sub-calls for filtering and organization in debugging tools.
Custom key-value pairs for tracking additional context, inherited by all sub-calls.
Controls the maximum number of parallel calls when using
batch() or batch_as_completed().Handlers for monitoring and responding to events during execution.
Maximum recursion depth for chains to prevent infinite loops in complex pipelines.
Configurable models
You can also create a runtime-configurable model by specifyingconfigurable_fields. If you don’t specify a model value, then 'model' and 'model_provider' will be configurable by default.
Configurable model with default values
Configurable model with default values
We can create a configurable model with default model values, specify which parameters are configurable, and add prefixes to configurable params:
Using a configurable model declaratively
Using a configurable model declaratively
We can call declarative operations like
bind_tools, with_structured_output, with_configurable, etc. on a configurable model and chain a configurable model in the same way that we would a regularly instantiated chat model object.