以编程方式使用文档

:::caution 此服务已弃用。 查看 此页面 获取更新后的 ChatAI21 对象。 :::

此示例介绍如何使用 LangChain 与 AI21 Jurassic 模型进行交互。要使用 Jamba 模型,请使用 ChatAI21 对象 instead.

在 LangChain 上查看完整的 AI21 模型和工具列表。

安装

!pip install -qU langchain-ai21

环境设置

我们需要获取一个 AI21 API 密钥 并设置 AI21_API_KEY 环境变量:

from getpass import getpass

if "AI21_API_KEY" not in os.environ:
    os.environ["AI21_API_KEY"] = getpass()

用法

from langchain_ai21 import AI21LLM
from langchain_core.prompts import PromptTemplate

template = """Question: {question}

Answer: Let's think step by step."""

prompt = PromptTemplate.from_template(template)

model = AI21LLM(model="j2-ultra")

chain = prompt | model

chain.invoke({"question": "What is LangChain?"})
'\nLangChain is a (database)\nLangChain is a database for storing and processing documents'

AI21 上下文回答

您可以使用 AI21 的上下文回答模型来接收文本或文档,作为上下文, 以及一个问题,并完全基于此上下文返回答案。

这意味着如果您的答案不在文档中, 模型将指出这一点(而不是提供错误答案)

from langchain_ai21 import AI21ContextualAnswers

tsm = AI21ContextualAnswers()

response = tsm.invoke(input={"context": "Your context", "question": "Your question"})

您还可以将其与链和输出解析器以及向量数据库结合使用

from langchain_ai21 import AI21ContextualAnswers
from langchain_core.output_parsers import StrOutputParser

tsm = AI21ContextualAnswers()
chain = tsm | StrOutputParser()

response = chain.invoke(
    {"context": "Your context", "question": "Your question"},
)