AI21LLM
此服務已棄用。
請參閱此頁面以取得更新後的 ChatAI21 物件。 ::
此範例說明如何使用 LangChain 與 AI21
Jurassic 模型互動。若要使用 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()
使用方式
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 參考: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 參考:StrOutputParser