Skip to main content

Prediction Guard

本页面介绍如何在 LangChain 中使用Prediction Guard生态系统。 它分为两个部分:安装和设置,以及对特定Prediction Guard包装器的引用。

安装和设置

  • 使用 pip install predictionguard 安装 Python SDK
  • 获取 Prediction Guard 访问令牌(如 这里 所述)并将其设置为环境变量 (PREDICTIONGUARD_TOKEN)

LLM Wrapper

存在一个Prediction Guard LLM 包装器,您可以通过以下方式访问它:

from langchain_community.llms import PredictionGuard

在初始化 LLM 时,您可以将Prediction Guard模型的名称作为参数提供:

pgllm = PredictionGuard(model="MPT-7B-Instruct")

您还可以直接将访问令牌作为参数提供:

pgllm = PredictionGuard(model="MPT-7B-Instruct", token="<your access token>")

最后,您可以提供一个“输出”参数,用于结构化/控制 LLM 的输出:

pgllm = PredictionGuard(model="MPT-7B-Instruct", output={"type": "boolean"})

示例用法

受控或受保护的 LLM 包装器的基本用法:

import os

import predictionguard as pg
from langchain_community.llms import PredictionGuard
from langchain_core.prompts import PromptTemplate
from langchain.chains import LLMChain

# 您的 Prediction Guard API 密钥。请在 predictionguard.com 获取一个
os.environ["PREDICTIONGUARD_TOKEN"] = "<your Prediction Guard access token>"

# 定义一个提示模板
template = """根据上下文回应以下查询。

上下文:每条评论、私信 + 邮件建议都引导我们发布这个令人兴奋的公告!🎉 我们正式增加了两个新的蜡烛订阅盒选项!📦
独家蜡烛盒 - $80
每月蜡烛盒 - $45 (新!)
本月香味盒 - $28 (新!)
前往故事获取每个盒子的所有详情!👆 附加优惠:使用代码 50OFF 享受首个盒子 50% 的折扣!🎉

查询:{query}

结果:"""
prompt = PromptTemplate.from_template(template)

# 通过“保护”或控制 LLM 的输出。请参阅
# Prediction Guard 文档 (https://docs.predictionguard.com) 了解如何
# 使用整数、浮点数、布尔值、JSON 和其他类型及结构控制输出。
pgllm = PredictionGuard(model="MPT-7B-Instruct",
output={
"type": "categorical",
"categories": [
"产品公告",
"道歉",
"关系"
]
})
pgllm(prompt.format(query="这是什么类型的帖子?"))

使用 Prediction Guard 包装器的基本 LLM 链接:

import os

from langchain_core.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain_community.llms import PredictionGuard

# 可选,添加您的 OpenAI API 密钥。此项为可选,因为 Prediction Guard 允许
# 您访问所有最新的开放访问模型(请参见 https://docs.predictionguard.com)
os.environ["OPENAI_API_KEY"] = "<your OpenAI api key>"

# 您的 Prediction Guard API 密钥。请在 predictionguard.com 获取一个
os.environ["PREDICTIONGUARD_TOKEN"] = "<your Prediction Guard access token>"

pgllm = PredictionGuard(model="OpenAI-gpt-3.5-turbo-instruct")

template = """问题:{question}

答案:让我们一步步思考。"""
prompt = PromptTemplate.from_template(template)
llm_chain = LLMChain(prompt=prompt, llm=pgllm, verbose=True)

question = "贾斯汀·比伯出生那年,哪支 NFL 球队赢得了超级碗?"

llm_chain.predict(question=question)

此页面是否有帮助?


您还可以留下详细的反馈 在 GitHub 上