10-24.8.26Function Calling-作业 #73
Labels
No Label
bug
duplicate
enhancement
help wanted
invalid
question
wontfix
No Milestone
No project
No Assignees
1 Participants
Notifications
Due Date
No due date set.
Dependencies
No dependencies set.
Reference: HswOAuth/llm_course#73
Loading…
Reference in New Issue
Block a user
No description provided.
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
import os
import json
import requests
from openai import OpenAI
from dotenv import load_dotenv
api_key = os.getenv('OPENAI_API_KEY')
client = OpenAI(
# 将这里换成你在aiproxy api keys拿到的密钥
api_key=api_key,
base_url="https://openai.zhixueyouke.cn/v1/"
)
qq = input("请输入您的QQ号!")
这个代码的作用,就是你调用算命这个网址,根据算命的key和url 获取算命的结果,当然要传一个
def get_forecast(qq): # 拿到
提示词
messages = []
messages.append({"role": "system", "content": "你是一个QQ号算命的机器人,你需要根据用户提供的QQ号来回答该QQ号的情况"})
messages.append({"role": "user", "content": f"""测算一下{qq}的凶吉?"""})
编写tools
tools=[
{"type": "function",
"function": {
"name": "fun_interface",
"description": "给定的QQ号情况,获取QQ的吉凶情况",
"parameters": {
"type": "object",
"properties": {
"qq": {
"type": "string",
"description": "一串连续的数字,例如123456",
},
},
"required": ["qq"],
},
}
}
]
第一次对话
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools # 如果没有写tools 表示的普通对象,如果写了tools表示的就是Function calling
)
messages.append(response.choices[0].message)
print(messages,'111')
function_name = response.choices[0].message.tool_calls[0].function.name
print(function_name,'222')
function_id = response.choices[0].message.tool_calls[0].id
print(function_id,'333')
添加函数返回的结果
messages.append(
{
"tool_call_id": function_id,
"role":"tool",#表示是function call
"name": function_name,
"content": get_forecast(qq),
}
)
response = client.chat.completions.create(
messages= messages,
model="gpt-4o-mini",
)
print(response.choices[0].message.content,'444')
运行结果:
请输入您的QQ号!>? 1702345
[{'role': 'system', 'content': '你是一个QQ号算命的机器人,你需要根据用户提供的QQ号来回答该QQ号的情况'}, {'role': 'user', 'content': '测算一下1702345的凶吉?'}, ChatCompletionMessage(content=None, refusal=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_fBCWxa314xKlIMjoUGjnrnp9', function=Function(arguments='{"qq":"1702345"}', name='fun_interface'), type='function')])] 111
fun_interface 222
call_fBCWxa314xKlIMjoUGjnrnp9 333
根据你提供的QQ号1702345进行的测算结果如下:
请注意,本次测算结果仅供娱乐使用,请勿用于封建迷信和违法用途。 444