跳转到内容

langchain-deepseek

PyPI - Version PyPI - License PyPI - Downloads

注意

此软件包参考尚未完全迁移到 v1。

langchain_deepseek

LangChain DeepSeek 集成。

ChatDeepSeek

Bases: BaseChatOpenAI

DeepSeek 聊天模型集成,用于访问 DeepSeek API 托管的模型。

设置

安装 langchain-deepseek 并设置环境变量 DEEPSEEK_API_KEY

pip install -U langchain-deepseek
export DEEPSEEK_API_KEY="your-api-key"

关键初始化参数 — 补全参数:model:要使用的 DeepSeek 模型名称,例如 "deepseek-chat"。temperature:采样温度。max_tokens:要生成的最大 token 数。

关键初始化参数 — 客户端参数:timeout:请求超时时间。max_retries:最大重试次数。api_key:DeepSeek API 密钥。如果未传入,将从环境变量 DEEPSEEK_API_KEY 中读取。

有关支持的初始化参数及其描述的完整列表,请参见参数部分。

实例化
from langchain_deepseek import ChatDeepSeek

model = ChatDeepSeek(
    model="...",
    temperature=0,
    max_tokens=None,
    timeout=None,
    max_retries=2,
    # api_key="...",
    # other params...
)
调用
messages = [
    ("system", "You are a helpful translator. Translate the user sentence to French."),
    ("human", "I love programming."),
]
model.invoke(messages)

for chunk in model.stream(messages):
    print(chunk.text, end="")
stream = model.stream(messages)
full = next(stream)
for chunk in stream:
    full += chunk
full

异步
await model.ainvoke(messages)

# stream:
# async for chunk in (await model.astream(messages))

# batch:
# await model.abatch([messages])
工具调用
from pydantic import BaseModel, Field


class GetWeather(BaseModel):
    '''Get the current weather in a given location'''

    location: str = Field(..., description="The city and state, e.g. San Francisco, CA")


class GetPopulation(BaseModel):
    '''Get the current population in a given location'''

    location: str = Field(..., description="The city and state, e.g. San Francisco, CA")


model_with_tools = model.bind_tools([GetWeather, GetPopulation])
ai_msg = model_with_tools.invoke("Which city is hotter today and which is bigger: LA or NY?")
ai_msg.tool_calls

更多信息请参阅 ChatDeepSeek.bind_tools() 方法。

结构化输出
from typing import Optional

from pydantic import BaseModel, Field


class Joke(BaseModel):
    '''Joke to tell user.'''

    setup: str = Field(description="The setup of the joke")
    punchline: str = Field(description="The punchline to the joke")
    rating: int | None = Field(description="How funny the joke is, from 1 to 10")


structured_model = model.with_structured_output(Joke)
structured_model.invoke("Tell me a joke about cats")

更多信息请参阅 ChatDeepSeek.with_structured_output()

令牌使用情况

ai_msg = model.invoke(messages)
ai_msg.usage_metadata
{"input_tokens": 28, "output_tokens": 5, "total_tokens": 33}

方法 描述
validate_environment

验证必要的环境变量和客户端参数。

with_structured_output

返回与给定模式匹配的格式化输出的模型包装器。

model_name class-attribute instance-attribute

model_name: str = Field(alias='model')

模型名称

api_key class-attribute instance-attribute

api_key: SecretStr | None = Field(
    default_factory=secret_from_env("DEEPSEEK_API_KEY", default=None)
)

DeepSeek API 密钥

api_base class-attribute instance-attribute

api_base: str = Field(
    default_factory=from_env("DEEPSEEK_API_BASE", default=DEFAULT_API_BASE)
)

DeepSeek API 基础 URL

lc_secrets property

lc_secrets: dict[str, str]

构造函数参数名称到密钥 ID 的映射。

validate_environment

validate_environment() -> Self

验证必要的环境变量和客户端参数。

with_structured_output

with_structured_output(
    schema: _DictOrPydanticClass | None = None,
    *,
    method: Literal[
        "function_calling", "json_mode", "json_schema"
    ] = "function_calling",
    include_raw: bool = False,
    strict: bool | None = None,
    **kwargs: Any,
) -> Runnable[LanguageModelInput, _DictOrPydantic]

返回与给定模式匹配的格式化输出的模型包装器。

参数 描述
模式

输出模式。可以作为以下形式传入:

  • 一个 OpenAI 函数/工具模式,
  • 一个 JSON Schema,
  • 一个 TypedDict 类,
  • 或一个 Pydantic 类。

如果 schema 是一个 Pydantic 类,那么模型输出将是该类的 Pydantic 实例,并且模型生成的字段将由 Pydantic 类进行验证。否则,模型输出将是一个字典,并且不会被验证。

有关在指定 Pydantic 或 TypedDict 类时如何正确指定模式字段的类型和描述的更多信息,请参阅 langchain_core.utils.function_calling.convert_to_openai_tool

TYPE: _DictOrPydanticClass | None DEFAULT: None

method

用于引导模型生成的方法,可选值之一:

类型: Literal['function_calling', 'json_mode', 'json_schema'] 默认值: 'function_calling'

包含原始数据

如果为 False,则仅返回解析后的结构化输出。如果在模型输出解析期间发生错误,它将被引发。如果为 True,则将返回原始模型响应(一个 BaseMessage)和解析后的模型响应。如果在输出解析期间发生错误,它将被捕获并一并返回。

最终输出总是一个带有键 'raw''parsed''parsing_error'dict

类型: bool 默认值: False

strict

是否在生成函数调用时启用严格的模式遵循。此参数是为了与其他聊天模型兼容而包含的,如果指定,将根据 OpenAI API 规范传递给聊天补全 API。但是,DeepSeek API 可能会忽略该参数。

类型: bool | None 默认值: None

kwargs

不支持额外的关键字参数。

类型: Any 默认值: {}

返回 描述
Runnable[LanguageModelInput, _DictOrPydantic]

一个接受与 langchain_core.language_models.chat.BaseChatModel 相同输入的 Runnable。如果 include_rawFalseschema 是一个 Pydantic 类,则 Runnable 输出一个 schema 的实例(即一个 Pydantic 对象)。否则,如果 include_rawFalse,则 Runnable 输出一个 dict

如果 include_rawTrue,则 Runnable 输出一个带有以下键的 dict

  • 'raw': BaseMessage
  • 'parsed': 如果出现解析错误则为 None,否则类型取决于上面描述的 schema
  • 'parsing_error': BaseException | None
© . This site is unofficial and not affiliated with LangChain, Inc.