import json
import os
import time
import requests
from openai import OpenAI
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
# 一个发送邮件的函数工具
def send_email(quote, recipient="霍格沃兹测试开发学社@email.com"):
# Print the quote and recipient for debugging purposes
print(f"生成消息:\n {quote}\n\n发送邮件给: {recipient}")
# Return a success message
return "发送邮件给" + recipient
# 工具的提示词。为了让大模型更好理解工作的作用。
tools = [{
"type": "function",
"function": {
"name": "send_email",
"description": "Sends a quote via email",
"parameters": {
"type": "object",
"properties": {
"quote": {
"type": "string",
"description": "A generated funny quote"
}
},
"required": [
"quote"
]
}
}
}]
# 1. 创建助手
assistant = client.beta.assistants.create(
name="Wise Guy",
instructions="你是一位聪明的哲学家,会产生有趣的引言。",
model="gpt-3.5-turbo-1106",
tools=tools
)
# 2. 创建线程
thread = client.beta.threads.create()
# 3. 传入 prompt 并执行线程
message = client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="创建一个笑话并且使用邮件发送",
)
# 4. 执行消息
run_res = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id, )
# 5. 等待回复
def wait_on_run(run):
while run.status == "queued" or run.status == "in_progress":
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id,
)
print(f"执行的状态为:{run.status}")
time.sleep(0.5)
return run
# 6. 获取回复的结果
run_res = wait_on_run(run_res)
# 7. 如果回复的结果需要调用工具
if run_res.status == "requires_action":
# 提交工具的返回信息
tool_call = run_res.required_action.submit_tool_outputs.tool_calls[0]
name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print("等待返回的参数:", name)
print(f"函数参数为:{arguments}")
# 调用发送邮件工具
task = send_email(**arguments)
# 提交工具执行后的结果信息。
run = client.beta.threads.runs.submit_tool_outputs(
thread_id=thread.id,
run_id=run_res.id,
tool_outputs=[
{
"tool_call_id": tool_call.id,
"output": "done",
}
],
)
print("==========调用 chatgpt 执行内容")
run = wait_on_run(run)
print("==========获取返回信息")
print(client.beta.threads.messages.list(thread_id=thread.id, order="asc").model_dump_json(indent=2))
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.