多配置 API#
本指南描述了如何在使用同一服务器 API 调用时使用多个配置。
动机#
运行 guardrails 服务器时,创建可在多个“完整”配置中重复使用的原子配置非常方便。在本指南中,我们使用这些示例配置
input_checking
:使用自检输入防护栏。output_checking
:使用自检输出防护栏。main
:使用gpt-3.5-turbo-instruct
模型,不带任何 guardrails。
# Get rid of the TOKENIZERS_PARALLELISM warning
import warnings
warnings.filterwarnings('ignore')
先决条件#
安装
openai
包
pip install openai
设置
OPENAI_API_KEY
环境变量
export OPENAI_API_KEY=$OPENAI_API_KEY # Replace with your own key
如果您在 notebook 中运行此程序,请修补 AsyncIO 循环。
import nest_asyncio
nest_asyncio.apply()
设置#
在本指南中,服务器是按如下所示以编程方式启动的。这等同于(从项目根目录)
nemoguardrails server --config=examples/server_configs/atomic
import os
from nemoguardrails.server.api import app
from threading import Thread
import uvicorn
def run_server():
current_path = %pwd
app.rails_config_path = os.path.normpath(os.path.join(current_path, "..", "..", "..", "examples", "server_configs", "atomic"))
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
# Start the server in a separate thread so that you can still use the notebook
thread = Thread(target=run_server)
thread.start()
您可以使用 /v1/rails/configs
端点检查可用配置
import requests
base_url = "http://127.0.0.1:8000"
response = requests.get(f"{base_url}/v1/rails/configs")
print(response.json())
[{'id': 'output_checking'}, {'id': 'main'}, {'id': 'input_checking'}]
您可以使用单个配置进行调用,如下所示
response = requests.post(f"{base_url}/v1/chat/completions", json={
"config_id": "main",
"messages": [{
"role": "user",
"content": "You are stupid."
}]
})
print(response.json())
要使用多个配置,您必须在请求正文中使用 config_ids
字段而不是 config_id
,如下所示
response = requests.post(f"{base_url}/v1/chat/completions", json={
"config_ids": ["main", "input_checking"],
"messages": [{
"role": "user",
"content": "You are stupid."
}]
})
print(response.json())
{'messages': [{'role': 'assistant', 'content': "I'm sorry, I can't respond to that."}]}
正如您所看到的,在第一个调用中,LLM 对用户的请求进行了响应。它确实拒绝了响应,但理想情况下,我们根本不希望请求到达 LLM。在第二个调用中,输入防护栏启动并阻止了该请求。
结论#
本指南展示了如何使用多个配置 ID 向 guardrails 服务器发出请求。这在多种情况下都很有用,并且鼓励在各种多个配置之间重复使用,而无需复制代码。