Skip to main content

AI21LLM

本示例介绍了如何使用LangChain与AI21侏罗纪模型进行交互。要使用Jamba模型,请使用ChatAI21对象

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

安装

!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()

使用方法

<!--IMPORTS:[{"imported": "PromptTemplate", "source": "langchain_core.prompts", "docs": "https://python.langchain.com/api_reference/core/prompts/langchain_core.prompts.prompt.PromptTemplate.html", "title": "AI21LLM"}]-->
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"})

您还可以将其与链、输出解析器和向量数据库一起使用

<!--IMPORTS:[{"imported": "StrOutputParser", "source": "langchain_core.output_parsers", "docs": "https://python.langchain.com/api_reference/core/output_parsers/langchain_core.output_parsers.string.StrOutputParser.html", "title": "AI21LLM"}]-->
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"},
)

相关


Was this page helpful?


You can also leave detailed feedback on GitHub.

扫我,入群扫我,找书