Skip to main content
Open In ColabOpen on GitHub

AI21LLM

此服务已弃用。

请参阅此页面了解更新后的 ChatAI21 对象。:::

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

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

Installation

!pip install -qU langchain-ai21

环境设置

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

import os
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?"})
API Reference:PromptTemplate
'\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"},
)
API Reference:StrOutputParser