Skip to main content
本文档将帮助您开始使用 Contextual AI 的基础语言模型(Grounded Language Model)聊天模型 如需了解更多关于 Contextual AI 的信息,请访问我们的文档 本集成需要 contextual-client Python SDK。详情请参阅此处

概览

本集成调用 Contextual AI 的基础语言模型。

集成详情

可序列化JS 支持下载量版本
ChatContextuallangchain-contextualbetaPyPI - DownloadsPyPI - Version

模型功能

工具调用结构化输出图像输入音频输入视频输入Token 级流式输出原生异步Token 用量对数概率

安装配置

要访问 Contextual 模型,您需要创建 Contextual AI 账户、获取 API 密钥,并安装 langchain-contextual 集成包。

凭据

前往 app.contextual.ai 注册 Contextual 并生成 API 密钥。完成后,设置 CONTEXTUAL_AI_API_KEY 环境变量:
import getpass
import os

if not os.getenv("CONTEXTUAL_AI_API_KEY"):
    os.environ["CONTEXTUAL_AI_API_KEY"] = getpass.getpass(
        "Enter your Contextual API key: "
    )
如果希望自动追踪模型调用,可以设置您的 LangSmith API 密钥(取消注释以下代码):
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")

安装

LangChain Contextual 集成位于 langchain-contextual 包中:
pip install -qU langchain-contextual

实例化

现在可以实例化模型对象并生成聊天补全。 聊天客户端支持以下额外配置参数:
参数类型描述默认值
temperatureOptional[float]采样温度,影响响应的随机性。注意,较高的温度值可能降低基础性。0
top_pOptional[float]核采样参数,是温度的替代方案,同样影响响应的随机性。注意,较高的 top_p 值可能降低基础性。0.9
max_new_tokensOptional[int]模型在响应中可生成的最大 token 数。最小值为 1,最大值为 2048。1024
from langchain_contextual import ChatContextual

llm = ChatContextual(
    model="v1",  # defaults to `v1`
    api_key="",
    temperature=0,  # defaults to 0
    top_p=0.9,  # defaults to 0.9
    max_new_tokens=1024,  # defaults to 1024
)

调用

Contextual 基础语言模型在调用 ChatContextual.invoke 方法时支持额外的 kwargs 参数。 这些额外的输入参数如下:
参数类型描述
knowledgelist[str]必填:字符串列表,包含基础语言模型生成响应时可使用的知识来源。
system_promptOptional[str]可选:模型生成响应时应遵循的指令。请注意,我们不保证模型会严格遵循这些指令。
avoid_commentaryOptional[bool]可选(默认值为 False):指示模型是否应避免在响应中提供额外评论的标志。评论具有对话性质,不包含可验证的声明,因此不严格基于可用上下文。然而,评论可能提供有用的背景信息,从而提高响应的实用性。
# include a system prompt (optional)
system_prompt = "You are a helpful assistant that uses all of the provided knowledge to answer the user's query to the best of your ability."

# provide your own knowledge from your knowledge-base here in an array of string
knowledge = [
    "There are 2 types of dogs in the world: good dogs and best dogs.",
    "There are 2 types of cats in the world: good cats and best cats.",
]

# create your message
messages = [
    ("human", "What type of cats are there in the world and what are the types?"),
]

# invoke the GLM by providing the knowledge strings, optional system prompt
# if you want to turn off the GLM's commentary, pass True to the `avoid_commentary` argument
ai_msg = llm.invoke(
    messages, knowledge=knowledge, system_prompt=system_prompt, avoid_commentary=True
)

print(ai_msg.content)

链式调用

可以将 Contextual 模型与输出解析器进行链式组合。
from langchain_core.output_parsers import StrOutputParser

chain = llm | StrOutputParser

chain.invoke(
    messages, knowledge=knowledge, systemp_prompt=system_prompt, avoid_commentary=True
)

API 参考

有关 ChatContextual 所有功能和配置的详细文档,请访问 GitHub 页面:github.com/ContextualAI//langchain-contextual