from openai import OpenAI # 需要1.2以上版本
import os
# 加载环境变量
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # 读取本地 .env 文件,里面定义了 OPENAI_API_KEY
client = OpenAI(
api_key=os.getenv("OPENAI_API_KEY"),
base_url=os.getenv("OPENAI_API_BASE")
)
# 上传文件
file = client.files.create(
file=open("llama2.pdf", "rb"),
purpose='assistants'
)
# 创建 Assistant
assistant = client.beta.assistants.create(
instructions="你是个问答机器人,你根据给定的知识回答用户问题。",
model="gpt-4-1106-preview",
tools=[{"type": "retrieval"}],
file_ids=[file.id]
)
# 创建 Thread
thread = client.beta.threads.create()
# 创建 User Message
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="Llama 2有多少参数"
)
# 创建 Run 实例,同时给 Assistant 提供指令
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
instructions="请用中文回答用户的问题。",
)
# 等待 Run 完成
while run.status != "completed":
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
# 获取 Run 的结果
messages = client.beta.threads.messages.list(
thread_id=thread.id
)
# 打印结果
for turn in reversed(messages.data):
print(f"{turn.role.upper()}: "+turn.content[0].text.value)
OpenAI Assistant API 内置RAG
最新推荐文章于 2024-09-10 15:09:02 发布