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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import openai
|
3 |
+
import sys
|
4 |
+
import re
|
5 |
+
|
6 |
+
import gradio as gr
|
7 |
+
from IPython import get_ipython
|
8 |
+
import json
|
9 |
+
import requests
|
10 |
+
from tenacity import retry, wait_random_exponential, stop_after_attempt
|
11 |
+
from IPython import get_ipython
|
12 |
+
# from termcolor import colored # doesn't actually work in Colab ¯\_(ツ)_/¯
|
13 |
+
import ast
|
14 |
+
|
15 |
+
GPT_MODEL = "gpt-3.5-turbo-1106"
|
16 |
+
|
17 |
+
openai.api_key = os.environ['OPENAI_API_KEY']
|
18 |
+
|
19 |
+
def exec_python(cell):
|
20 |
+
# result = 0
|
21 |
+
print(cell)
|
22 |
+
# print(type(cell))
|
23 |
+
# code = json.loads(cell)
|
24 |
+
# print(code)
|
25 |
+
# exec(code["cell"])
|
26 |
+
inputcode = cell
|
27 |
+
print(inputcode)
|
28 |
+
code = inputcode
|
29 |
+
# code_string = code["cell"]
|
30 |
+
local_namespace = {}
|
31 |
+
try:
|
32 |
+
exec(code, globals(), local_namespace)
|
33 |
+
except Exception as e:
|
34 |
+
return "Please figure and solve it step by step with explanation by yourself. Remember, you must give the correct answer!"
|
35 |
+
print(local_namespace)
|
36 |
+
if not local_namespace:
|
37 |
+
return "Please figure and solve it step by step with explanation by yourself. Remember, you must give the correct answer!"
|
38 |
+
else:
|
39 |
+
theanswers = local_namespace.values()
|
40 |
+
print(theanswers)
|
41 |
+
local_ans = list(theanswers)[-1]
|
42 |
+
print(local_ans)
|
43 |
+
return local_ans
|
44 |
+
|
45 |
+
# Now let's define the function specification:
|
46 |
+
functions = [
|
47 |
+
{
|
48 |
+
"name": "exec_python",
|
49 |
+
"description": "run python code and return the execution result.",
|
50 |
+
"parameters": {
|
51 |
+
"type": "object",
|
52 |
+
"properties": {
|
53 |
+
"cell": {
|
54 |
+
"type": "string",
|
55 |
+
"description": "Valid Python code to execute.",
|
56 |
+
}
|
57 |
+
},
|
58 |
+
"required": ["cell"],
|
59 |
+
},
|
60 |
+
},
|
61 |
+
]
|
62 |
+
|
63 |
+
# In order to run these functions automatically, we should maintain a dictionary:
|
64 |
+
functions_dict = {
|
65 |
+
"exec_python": exec_python,
|
66 |
+
}
|
67 |
+
|
68 |
+
def openai_api_calculate_cost(usage,model):
|
69 |
+
pricing = {
|
70 |
+
# 'gpt-3.5-turbo-4k': {
|
71 |
+
# 'prompt': 0.0015,
|
72 |
+
# 'completion': 0.002,
|
73 |
+
# },
|
74 |
+
# 'gpt-3.5-turbo-16k': {
|
75 |
+
# 'prompt': 0.003,
|
76 |
+
# 'completion': 0.004,
|
77 |
+
# },
|
78 |
+
'gpt-3.5-turbo-1106': {
|
79 |
+
'prompt': 0.001,
|
80 |
+
'completion': 0.002,
|
81 |
+
},
|
82 |
+
'gpt-4-1106-preview': {
|
83 |
+
'prompt': 0.01,
|
84 |
+
'completion': 0.03,
|
85 |
+
},
|
86 |
+
'gpt-4': {
|
87 |
+
'prompt': 0.03,
|
88 |
+
'completion': 0.06,
|
89 |
+
},
|
90 |
+
# 'gpt-4-32k': {
|
91 |
+
# 'prompt': 0.06,
|
92 |
+
# 'completion': 0.12,
|
93 |
+
# },
|
94 |
+
# 'text-embedding-ada-002-v2': {
|
95 |
+
# 'prompt': 0.0001,
|
96 |
+
# 'completion': 0.0001,
|
97 |
+
# }
|
98 |
+
}
|
99 |
+
|
100 |
+
try:
|
101 |
+
model_pricing = pricing[model]
|
102 |
+
except KeyError:
|
103 |
+
raise ValueError("Invalid model specified")
|
104 |
+
|
105 |
+
prompt_cost = usage['prompt_tokens'] * model_pricing['prompt'] / 1000
|
106 |
+
completion_cost = usage['completion_tokens'] * model_pricing['completion'] / 1000
|
107 |
+
|
108 |
+
total_cost = prompt_cost + completion_cost
|
109 |
+
print(f"\nTokens used: {usage['prompt_tokens']:,} prompt + {usage['completion_tokens']:,} completion = {usage['total_tokens']:,} tokens")
|
110 |
+
print(f"Total cost for {model}: ${total_cost:.4f}\n")
|
111 |
+
|
112 |
+
return total_cost
|
113 |
+
|
114 |
+
|
115 |
+
@retry(wait=wait_random_exponential(min=1, max=40), stop=stop_after_attempt(3))
|
116 |
+
def chat_completion_request(messages, model, functions=None, function_call=None, temperature=0.2, top_p=0.1):
|
117 |
+
"""
|
118 |
+
This function sends a POST request to the OpenAI API to generate a chat completion.
|
119 |
+
Parameters:
|
120 |
+
- messages (list): A list of message objects. Each object should have a 'role' (either 'system', 'user', or 'assistant') and 'content'
|
121 |
+
(the content of the message).
|
122 |
+
- functions (list, optional): A list of function objects that describe the functions that the model can call.
|
123 |
+
- function_call (str or dict, optional): If it's a string, it can be either 'auto' (the model decides whether to call a function) or 'none'
|
124 |
+
(the model will not call a function). If it's a dict, it should describe the function to call.
|
125 |
+
- model (str): The ID of the model to use.
|
126 |
+
Returns:
|
127 |
+
- response (requests.Response): The response from the OpenAI API. If the request was successful, the response's JSON will contain the chat completion.
|
128 |
+
"""
|
129 |
+
|
130 |
+
# Set up the headers for the API request
|
131 |
+
headers = {
|
132 |
+
"Content-Type": "application/json",
|
133 |
+
"Authorization": "Bearer " + openai.api_key,
|
134 |
+
}
|
135 |
+
|
136 |
+
# Set up the data for the API request
|
137 |
+
# json_data = {"model": model, "messages": messages}
|
138 |
+
# json_data = {"model": model, "messages": messages, "response_format":{"type": "json_object"}}
|
139 |
+
json_data = {"model": model, "messages": messages, "temperature": temperature, "top_p":top_p}
|
140 |
+
|
141 |
+
# If functions were provided, add them to the data
|
142 |
+
if functions is not None:
|
143 |
+
json_data.update({"functions": functions})
|
144 |
+
|
145 |
+
# If a function call was specified, add it to the data
|
146 |
+
if function_call is not None:
|
147 |
+
json_data.update({"function_call": function_call})
|
148 |
+
|
149 |
+
# Send the API request
|
150 |
+
try:
|
151 |
+
response = requests.post(
|
152 |
+
"https://api.openai.com/v1/chat/completions",
|
153 |
+
headers=headers,
|
154 |
+
json=json_data,
|
155 |
+
)
|
156 |
+
return response
|
157 |
+
except Exception as e:
|
158 |
+
print("Unable to generate ChatCompletion response")
|
159 |
+
print(f"Exception: {e}")
|
160 |
+
return e
|
161 |
+
|
162 |
+
def first_call(init_prompt, user_input, input_temperature, input_top_p, model_dropdown_1):
|
163 |
+
# Set up a conversation
|
164 |
+
messages = []
|
165 |
+
messages.append({"role": "system", "content": init_prompt})
|
166 |
+
|
167 |
+
# Write a user message that perhaps our function can handle...?
|
168 |
+
messages.append({"role": "user", "content": user_input})
|
169 |
+
|
170 |
+
# Generate a response
|
171 |
+
chat_response = chat_completion_request(
|
172 |
+
messages, model_dropdown_1, functions=functions, function_call='auto', temperature=float(input_temperature), top_p=float(input_top_p)
|
173 |
+
)
|
174 |
+
|
175 |
+
|
176 |
+
# Save the JSON to a variable
|
177 |
+
|
178 |
+
assistant_message = chat_response.json()["choices"][0]["message"]
|
179 |
+
|
180 |
+
# Append response to conversation
|
181 |
+
messages.append(assistant_message)
|
182 |
+
|
183 |
+
usage = chat_response.json()['usage']
|
184 |
+
cost1 = openai_api_calculate_cost(usage,model_dropdown_1)
|
185 |
+
|
186 |
+
finish_response_status = chat_response.json()["choices"][0]["finish_reason"]
|
187 |
+
# Let's see what we got back before continuing
|
188 |
+
return assistant_message, cost1, messages, finish_response_status
|
189 |
+
|
190 |
+
def is_valid_dict_string(s):
|
191 |
+
try:
|
192 |
+
ast.literal_eval(s)
|
193 |
+
return True
|
194 |
+
except (SyntaxError, ValueError):
|
195 |
+
return False
|
196 |
+
|
197 |
+
def function_call_process(assistant_message):
|
198 |
+
if assistant_message.get("function_call") != None:
|
199 |
+
|
200 |
+
# Retrieve the name of the relevant function
|
201 |
+
function_name = assistant_message["function_call"]["name"]
|
202 |
+
|
203 |
+
# Retrieve the arguments to send the function
|
204 |
+
# function_args = json.loads(assistant_message["function_call"]["arguments"], strict=False)
|
205 |
+
|
206 |
+
# if isinstance(assistant_message["function_call"]["arguments"], dict):
|
207 |
+
# arg_dict = json.loads(r"{jsonload}".format(jsonload=assistant_message["function_call"]["arguments"]), strict=False)
|
208 |
+
# else:
|
209 |
+
# arg_dict = {'cell': assistant_message["function_call"]["arguments"]}
|
210 |
+
# arg_dict = assistant_message["function_call"]["arguments"]
|
211 |
+
# print(function_args)
|
212 |
+
|
213 |
+
if is_valid_dict_string(assistant_message["function_call"]["arguments"])==True:
|
214 |
+
arg_dict = json.loads(r"{jsonload}".format(jsonload=assistant_message["function_call"]["arguments"]), strict=False)
|
215 |
+
arg_dict = arg_dict['cell']
|
216 |
+
print("arg_dict : " + arg_dict)
|
217 |
+
else:
|
218 |
+
arg_dict = assistant_message["function_call"]["arguments"]
|
219 |
+
print(arg_dict)
|
220 |
+
|
221 |
+
# Look up the function and call it with the provided arguments
|
222 |
+
result = functions_dict[function_name](arg_dict)
|
223 |
+
return result
|
224 |
+
|
225 |
+
# print(result)
|
226 |
+
def second_prompt_build(prompt, log):
|
227 |
+
prompt_second = prompt.format(ans = log)
|
228 |
+
# prompt_second = prompt % log
|
229 |
+
return prompt_second
|
230 |
+
|
231 |
+
def second_call(prompt, prompt_second, messages, model_dropdown_2, function_name = "exec_python"):
|
232 |
+
# Add a new message to the conversation with the function result
|
233 |
+
messages.append({
|
234 |
+
"role": "function",
|
235 |
+
"name": function_name,
|
236 |
+
"content": str(prompt_second), # Convert the result to a string
|
237 |
+
})
|
238 |
+
|
239 |
+
# Call the model again to generate a user-facing message based on the function result
|
240 |
+
chat_response = chat_completion_request(
|
241 |
+
messages, model_dropdown_2, functions=functions
|
242 |
+
)
|
243 |
+
print("second call : "+ str(chat_response.json()))
|
244 |
+
assistant_message = chat_response.json()["choices"][0]["message"]
|
245 |
+
messages.append(assistant_message)
|
246 |
+
|
247 |
+
usage = chat_response.json()['usage']
|
248 |
+
cost2 = openai_api_calculate_cost(usage,model_dropdown_2)
|
249 |
+
|
250 |
+
# Print the final conversation
|
251 |
+
# pretty_print_conversation(messages)
|
252 |
+
return assistant_message, cost2, messages
|
253 |
+
|
254 |
+
def format_math_in_sentence(sentence):
|
255 |
+
# Regular expression to find various math expressions
|
256 |
+
math_pattern = re.compile(r'\\[a-zA-Z]+\{[^\}]+\}|\\frac\{[^\}]+\}\{[^\}]+\}')
|
257 |
+
|
258 |
+
# Find all math expressions in the sentence
|
259 |
+
math_matches = re.findall(math_pattern, sentence)
|
260 |
+
|
261 |
+
# Wrap each math expression with Markdown formatting
|
262 |
+
for math_match in math_matches:
|
263 |
+
markdown_math = f"${math_match}$"
|
264 |
+
sentence = sentence.replace(math_match, markdown_math)
|
265 |
+
|
266 |
+
return sentence
|
267 |
+
|
268 |
+
def main_function(init_prompt, prompt, user_input,input_temperature_1, input_top_p_1, model_dropdown_1, model_dropdown_2):
|
269 |
+
first_call_result, cost1, messages, finish_response_status = first_call(init_prompt, user_input, input_temperature_1, input_top_p_1, model_dropdown_1)
|
270 |
+
print("finish_response_status "+finish_response_status)
|
271 |
+
print(messages)
|
272 |
+
if finish_response_status == 'stop':
|
273 |
+
function_call_process_result = "Tidak dipanggil"
|
274 |
+
second_prompt_build_result = "Tidak dipanggil"
|
275 |
+
second_call_result = {'status':'Tidak dipanggil'}
|
276 |
+
cost2 = 0
|
277 |
+
finalmessages = {'status':'Tidak dipanggil'}
|
278 |
+
finalcostresult = cost1
|
279 |
+
finalcostrpresult = finalcostresult * 15000
|
280 |
+
else:
|
281 |
+
function_call_process_result = function_call_process(first_call_result)
|
282 |
+
second_prompt_build_result = second_prompt_build(prompt, function_call_process_result)
|
283 |
+
second_call_result, cost2, finalmessages = second_call(second_prompt_build_result, function_call_process_result, messages, model_dropdown_2)
|
284 |
+
finalcostresult = cost1 + cost2
|
285 |
+
finalcostrpresult = finalcostresult * 15000
|
286 |
+
veryfinaloutput = format_math_in_sentence(str(finalmessages[-1].get("content", "")))
|
287 |
+
return first_call_result, function_call_process_result, second_prompt_build_result, second_call_result, cost1, cost2, finalmessages, finalcostresult, finalcostrpresult, veryfinaloutput
|
288 |
+
|
289 |
+
def gradio_function():
|
290 |
+
init_prompt = gr.Textbox(label="init_prompt (for 1st call)")
|
291 |
+
prompt = gr.Textbox(label="prompt (for 2nd call)")
|
292 |
+
user_input = gr.Textbox(label="User Input")
|
293 |
+
input_temperature_1 = gr.Textbox(label="temperature_1")
|
294 |
+
input_top_p_1 = gr.Textbox(label="top_p_1")
|
295 |
+
# input_temperature_2 = gr.Textbox(label="temperature_2")
|
296 |
+
# input_top_p_2 = gr.Textbox(label="top_p_2")
|
297 |
+
output_1st_call = gr.JSON(label="Assistant (output_1st_call)")
|
298 |
+
output_fc_call = gr.Textbox(label="Function Call (exec_python) Result (output_fc_call)")
|
299 |
+
output_fc_call_with_prompt = gr.Textbox(label="Building 2nd Prompt (output_fc_call_with_2nd_prompt)")
|
300 |
+
output_2nd_call = gr.JSON(label="Assistant (output_2nd_call_buat_user)")
|
301 |
+
cost = gr.Textbox(label="Cost 1")
|
302 |
+
cost2 = gr.Textbox(label="Cost 2")
|
303 |
+
finalcost = gr.Textbox(label="Final Cost ($)")
|
304 |
+
finalcostrp = gr.Textbox(label="Final Cost (Rp)")
|
305 |
+
finalmessages = gr.JSON(label="Final Messages")
|
306 |
+
model_dropdown_1 = gr.Dropdown(["gpt-4", "gpt-4-1106-preview", "gpt-3.5-turbo-1106"], label="Model 1", info="Pilih model 1!")
|
307 |
+
model_dropdown_2 = gr.Dropdown(["gpt-4", "gpt-4-1106-preview", "gpt-3.5-turbo-1106"], label="Model 2", info="Pilih model 2!")
|
308 |
+
prettieroutput = gr.Markdown()
|
309 |
+
|
310 |
+
iface = gr.Interface(
|
311 |
+
fn=main_function,
|
312 |
+
inputs=[init_prompt, prompt, user_input,input_temperature_1, input_top_p_1, model_dropdown_1, model_dropdown_2],
|
313 |
+
outputs=[output_1st_call, output_fc_call, output_fc_call_with_prompt, output_2nd_call, cost, cost2, finalmessages, finalcost, finalcostrp, prettieroutput],
|
314 |
+
title="Test",
|
315 |
+
description="Accuracy",
|
316 |
+
)
|
317 |
+
|
318 |
+
iface.launch(share=True, debug=True)
|
319 |
+
|
320 |
+
if __name__ == "__main__":
|
321 |
+
gradio_function()
|