使用LangChain与AI21Jurassic模型进行交互

在本指南中,我们将探讨如何使用LangChain与AI21的Jurassic模型进行交互。为了使用Jamba模型,请使用ChatAI21对象。您可以在LangChain上查看AI21模型和工具的完整列表。

环境准备

首先,我们需要安装langchain-ai21库。

!pip install -qU langchain-ai21

环境设置

在开始之前,我们需要获取AI21的API密钥,并设置AI21_API_KEY环境变量。可以通过以下代码设置:

import os
from getpass import getpass

# 安全的方式输入您的AI21 API密钥
os.environ["AI21_API_KEY"] = getpass()

使用示例

这里,我们展示如何使用LangChain与AI21LLM模型进行交互:

from langchain_ai21 import AI21LLM
from langchain_core.prompts import PromptTemplate

# 定义一个简单的Prompt模板
template = """Question: {question}

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

prompt = PromptTemplate.from_template(template)

# 创建AI21LLM实例,选择使用j2-ultra模型
model = AI21LLM(model="j2-ultra")

# 组合Prompt和模型形成Chain
chain = prompt | model

# 输入问题并获取回答
response = chain.invoke({"question": "What is LangChain?"})

# 输出模型对问题的回答
print(response)

输出示例

运行上述代码后,您将获得类似以下的输出:

LangChain is a database for storing and processing documents.

AI21上下文回答

AI21的上下文回答模型允许您将文本或文档作为上下文输入,并基于该上下文返回问题的答案。如果答案不在文档中,模型将指出这一点,而不是提供错误的答案。

from langchain_ai21 import AI21ContextualAnswers

# 创建AI21ContextualAnswers实例
tsm = AI21ContextualAnswers()

# 调用模型,提供上下文和问题
response = tsm.invoke(input={"context": "Your context", "question": "Your question"})

# 输出上下文回答
print(response)

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

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"},
)

print(response)

相关资源

  • LLM概念指南
  • LLM使用指南

如果遇到问题欢迎在评论区交流。

—END—

你可能感兴趣的:(langchain,交互,python)