from openai import OpenAI
# 定義模型的 function 宣告
def schedule_meeting_function = {
"name": "schedule_meeting",
"description": "Schedules a meeting with specified attendees at a given time and date.",
"parameters": {
"type": "object",
"properties": {
"attendees": {
"type": "array",
"items": {"type": "string"},
"description": "List of people attending the meeting.",
},
"date": {
"type": "string",
"description": "Date of the meeting (e.g., '2024-07-29')",
},
"time": {
"type": "string",
"description": "Time of the meeting (e.g., '15:00')",
},
"topic": {
"type": "string",
"description": "The subject or topic of the meeting.",
},
},
"required": ["attendees", "date", "time", "topic"],
},
}
# 配置 client
client = OpenAI(
api_key="sk-***", # 換成你在 AiHubMix 生成的密鑰
base_url="https://aihubmix.com/v1",
)
# 用 OpenAI 相容格式發送帶有 function 宣告的請求
response = client.chat.completions.create(
model="gemini-2.0-flash",
messages=[
{"role": "user", "content": "Schedule a meeting with Bob and Alice for 03/14/2025 at 10:00 AM about the Q3 planning."}
],
tools=[{"type": "function", "function": schedule_meeting_function}],
tool_choice="auto" ## 📍 此處追加了 Aihubmix 相容,更穩定的請求方式
)
# 檢查是否有 function call
if response.choices[0].message.tool_calls:
tool_call = response.choices[0].message.tool_calls[0]
function_call = tool_call.function
print(f"Function to call: {function_call.name}")
print(f"Arguments: {function_call.arguments}")
print(response.usage)
# 在實際應用中,這裡可以調用你的 function:
# result = schedule_meeting(**json.loads(function_call.arguments))
else:
print("No function call found in the response.")
print(response.choices[0].message.content)