-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat_with_function_calling_openai.py
More file actions
135 lines (115 loc) · 3.95 KB
/
chat_with_function_calling_openai.py
File metadata and controls
135 lines (115 loc) · 3.95 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import sys, json, os
import http.client
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
DEBUG = False
# Function to print the introductory message and read user's input
def intro():
user_input = input(">> ")
if user_input.lower() == "exit":
os.system("cls")
sys.exit()
return user_input
# Logger
def log(context, message):
if DEBUG:
print(f"\n[LOG:{context}] {message}\n")
# Function to query the Skyscanner API
def query(
fromEntityId=None,
toEntityId=None,
departDate=None,
wholeMonthDepart=None,
market=None,
locale=None,
currency=None,
):
conn = http.client.HTTPSConnection("sky-scanner3.p.rapidapi.com")
headers = {
"x-rapidapi-key": f"{os.getenv('SKY_SCANNER_API_KEY')}",
"x-rapidapi-host": "sky-scanner3.p.rapidapi.com",
}
req = "/flights/search-one-way?"
d = {
"fromEntityId": fromEntityId,
"toEntityId": toEntityId,
"departDate": departDate,
"wholeMonthDepart": wholeMonthDepart,
"market": market,
"locale": locale,
"currency": currency,
}
for i in d:
if d[i] is not None:
req += i + "=" + str(d[i]) + "&"
req = req[:-1]
conn.request("GET", req, headers=headers)
res = conn.getresponse()
data = res.read()
return data.decode("utf-8")
# Main chat function
def chat():
task = intro()
client = OpenAI(
# api_key=f"{os.getenv('OPENAI_API_KEY')}" # Replace with your OpenAI API key
api_key=f"{os.getenv('GEMINI_API_KEY')}", # Replace with your Gemini API key
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
)
response = client.chat.completions.create(
# model="gpt-4-turbo",
model="gemini-2.0-flash",
messages=[
{
"role": "system",
"content": "You are a helpful travel planning assistant.",
},
{
"role": "user",
"content": """Extract travel query parameters from the following input in this json format
{'fromEntityId': 'BOM'(mumbai) | 'DEL'(delhi) | 'PNQ'(pune) | 'BLR'(bengaluru) | 'MAA'(chennai), 'toEntityId': 'BOM'(mumbai) | 'DEL'(delhi) | 'PNQ'(pune) | 'BLR'(bengaluru) | 'MAA'(chennai), 'departDate': 'YYYY-MM-DD', 'wholeMonthDepart': 'YYYY-MM' #if departDate is absent, 'locale': '', 'currency': 'INR'}:
"""
+ str(task),
},
],
response_format={"type": "json_object"},
max_tokens=100,
)
params = response.choices[0].message.content.strip()
# Assuming the response text is a valid dictionary string, use eval (or safer parsing)
try:
params_dict = json.loads(params)
log("JSON_IN", params_dict)
except:
print("|> ", end="")
print("Sorry, I couldn't understand your request. Please provide more details.")
return
# Call the Skyscanner API with extracted parameters
result = query(**params_dict)
log("API_OUT", result[:800])
# Summarize the JSON output using GPT-4 Turbo
summary_response = client.chat.completions.create(
# model="gpt-4-turbo",
model="gemini-2.0-flash",
messages=[
{
"role": "system",
"content": "You are a helpful travel planning assistant.",
},
{
"role": "user",
"content": f"Summarize the following JSON output and present the flights to the user in a conversational format in 3 to 4 lines: \n{result}",
},
],
max_tokens=1024,
)
summary = summary_response.choices[0].message.content.strip()
# Print the summarized output
print("|> ", end="")
print(summary)
if __name__ == "__main__":
os.system("cls")
print("|> ", end="")
print("Hello. I am a travel planning assistant. How can I help you today?")
while True:
chat()