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|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import openai
|
3 |
+
import sys
|
4 |
+
|
5 |
+
import gradio as gr
|
6 |
+
from IPython import get_ipython
|
7 |
+
import json
|
8 |
+
import requests
|
9 |
+
from tenacity import retry, wait_random_exponential, stop_after_attempt
|
10 |
+
from IPython import get_ipython
|
11 |
+
# from termcolor import colored # doesn't actually work in Colab ¯\_(ツ)_/¯
|
12 |
+
|
13 |
+
GPT_MODEL = "gpt-3.5-turbo-1106"
|
14 |
+
|
15 |
+
openai.api_key = os.environ['OPENAI_API_KEY']
|
16 |
+
|
17 |
+
messages=[]
|
18 |
+
|
19 |
+
def exec_python(cell):
|
20 |
+
ipython = get_ipython()
|
21 |
+
print(ipython)
|
22 |
+
result = ipython.run_cell(cell)
|
23 |
+
log = str(result.result)
|
24 |
+
if result.error_before_exec is not None:
|
25 |
+
log += f"\n{result.error_before_exec}"
|
26 |
+
if result.error_in_exec is not None:
|
27 |
+
log += f"\n{result.error_in_exec}"
|
28 |
+
prompt = """You are a genius math tutor, Python code expert, and a helpful assistant.
|
29 |
+
answer = {ans}
|
30 |
+
Please answer user questions very well with explanations and match it with the multiple choices question.
|
31 |
+
""".format(ans = log)
|
32 |
+
return log
|
33 |
+
|
34 |
+
# Now let's define the function specification:
|
35 |
+
functions = [
|
36 |
+
{
|
37 |
+
"name": "exec_python",
|
38 |
+
"description": "run cell in ipython and return the execution result.",
|
39 |
+
"parameters": {
|
40 |
+
"type": "object",
|
41 |
+
"properties": {
|
42 |
+
"cell": {
|
43 |
+
"type": "string",
|
44 |
+
"description": "Valid Python cell to execute.",
|
45 |
+
}
|
46 |
+
},
|
47 |
+
"required": ["cell"],
|
48 |
+
},
|
49 |
+
},
|
50 |
+
]
|
51 |
+
|
52 |
+
# In order to run these functions automatically, we should maintain a dictionary:
|
53 |
+
functions_dict = {
|
54 |
+
"exec_python": exec_python,
|
55 |
+
}
|
56 |
+
|
57 |
+
def openai_api_calculate_cost(usage,model=GPT_MODEL):
|
58 |
+
pricing = {
|
59 |
+
# 'gpt-3.5-turbo-4k': {
|
60 |
+
# 'prompt': 0.0015,
|
61 |
+
# 'completion': 0.002,
|
62 |
+
# },
|
63 |
+
# 'gpt-3.5-turbo-16k': {
|
64 |
+
# 'prompt': 0.003,
|
65 |
+
# 'completion': 0.004,
|
66 |
+
# },
|
67 |
+
'gpt-3.5-turbo-1106': {
|
68 |
+
'prompt': 0.001,
|
69 |
+
'completion': 0.002,
|
70 |
+
},
|
71 |
+
# 'gpt-4-1106-preview': {
|
72 |
+
# 'prompt': 0.01,
|
73 |
+
# 'completion': 0.03,
|
74 |
+
# },
|
75 |
+
# 'gpt-4-32k': {
|
76 |
+
# 'prompt': 0.06,
|
77 |
+
# 'completion': 0.12,
|
78 |
+
# },
|
79 |
+
# 'text-embedding-ada-002-v2': {
|
80 |
+
# 'prompt': 0.0001,
|
81 |
+
# 'completion': 0.0001,
|
82 |
+
# }
|
83 |
+
}
|
84 |
+
|
85 |
+
try:
|
86 |
+
model_pricing = pricing[model]
|
87 |
+
except KeyError:
|
88 |
+
raise ValueError("Invalid model specified")
|
89 |
+
|
90 |
+
prompt_cost = usage['prompt_tokens'] * model_pricing['prompt'] / 1000
|
91 |
+
completion_cost = usage['completion_tokens'] * model_pricing['completion'] / 1000
|
92 |
+
|
93 |
+
total_cost = prompt_cost + completion_cost
|
94 |
+
print(f"\nTokens used: {usage['prompt_tokens']:,} prompt + {usage['completion_tokens']:,} completion = {usage['total_tokens']:,} tokens")
|
95 |
+
print(f"Total cost for {model}: ${total_cost:.4f}\n")
|
96 |
+
|
97 |
+
return total_cost
|
98 |
+
|
99 |
+
|
100 |
+
@retry(wait=wait_random_exponential(min=1, max=40), stop=stop_after_attempt(3))
|
101 |
+
def chat_completion_request(messages, functions=None, function_call=None, model=GPT_MODEL):
|
102 |
+
"""
|
103 |
+
This function sends a POST request to the OpenAI API to generate a chat completion.
|
104 |
+
Parameters:
|
105 |
+
- messages (list): A list of message objects. Each object should have a 'role' (either 'system', 'user', or 'assistant') and 'content'
|
106 |
+
(the content of the message).
|
107 |
+
- functions (list, optional): A list of function objects that describe the functions that the model can call.
|
108 |
+
- 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'
|
109 |
+
(the model will not call a function). If it's a dict, it should describe the function to call.
|
110 |
+
- model (str): The ID of the model to use.
|
111 |
+
Returns:
|
112 |
+
- response (requests.Response): The response from the OpenAI API. If the request was successful, the response's JSON will contain the chat completion.
|
113 |
+
"""
|
114 |
+
|
115 |
+
# Set up the headers for the API request
|
116 |
+
headers = {
|
117 |
+
"Content-Type": "application/json",
|
118 |
+
"Authorization": "Bearer " + openai.api_key,
|
119 |
+
}
|
120 |
+
|
121 |
+
# Set up the data for the API request
|
122 |
+
json_data = {"model": model, "messages": messages}
|
123 |
+
|
124 |
+
# If functions were provided, add them to the data
|
125 |
+
if functions is not None:
|
126 |
+
json_data.update({"functions": functions})
|
127 |
+
|
128 |
+
# If a function call was specified, add it to the data
|
129 |
+
if function_call is not None:
|
130 |
+
json_data.update({"function_call": function_call})
|
131 |
+
|
132 |
+
# Send the API request
|
133 |
+
try:
|
134 |
+
response = requests.post(
|
135 |
+
"https://api.openai.com/v1/chat/completions",
|
136 |
+
headers=headers,
|
137 |
+
json=json_data,
|
138 |
+
)
|
139 |
+
return response
|
140 |
+
except Exception as e:
|
141 |
+
print("Unable to generate ChatCompletion response")
|
142 |
+
print(f"Exception: {e}")
|
143 |
+
return e
|
144 |
+
|
145 |
+
def first_call(init_prompt, user_input):
|
146 |
+
# Set up a conversation
|
147 |
+
messages = []
|
148 |
+
messages.append({"role": "system", "content": init_prompt})
|
149 |
+
|
150 |
+
# Write a user message that perhaps our function can handle...?
|
151 |
+
messages.append({"role": "user", "content": user_input})
|
152 |
+
|
153 |
+
# Generate a response
|
154 |
+
chat_response = chat_completion_request(
|
155 |
+
messages, functions=functions
|
156 |
+
)
|
157 |
+
|
158 |
+
|
159 |
+
# Save the JSON to a variable
|
160 |
+
assistant_message = chat_response.json()["choices"][0]["message"]
|
161 |
+
|
162 |
+
# Append response to conversation
|
163 |
+
messages.append(assistant_message)
|
164 |
+
|
165 |
+
usage = chat_response.json()['usage']
|
166 |
+
cost1 = openai_api_calculate_cost(usage)
|
167 |
+
|
168 |
+
# Let's see what we got back before continuing
|
169 |
+
return assistant_message, cost1
|
170 |
+
|
171 |
+
|
172 |
+
def second_prompt_build(prompt, log):
|
173 |
+
prompt_second = prompt.format(ans = log)
|
174 |
+
return prompt_second
|
175 |
+
|
176 |
+
def function_call_process(assistant_message):
|
177 |
+
if assistant_message.get("function_call") != None:
|
178 |
+
|
179 |
+
# Retrieve the name of the relevant function
|
180 |
+
function_name = assistant_message["function_call"]["name"]
|
181 |
+
|
182 |
+
# Retrieve the arguments to send the function
|
183 |
+
# function_args = json.loads(assistant_message["function_call"]["arguments"], strict=False)
|
184 |
+
arg_dict = {'cell': assistant_message["function_call"]["arguments"]}
|
185 |
+
# print(function_args)
|
186 |
+
|
187 |
+
# Look up the function and call it with the provided arguments
|
188 |
+
result = functions_dict[function_name](**arg_dict)
|
189 |
+
return result
|
190 |
+
|
191 |
+
# print(result)
|
192 |
+
|
193 |
+
def second_call(prompt, result, function_name = "exec_python"):
|
194 |
+
# Add a new message to the conversation with the function result
|
195 |
+
messages.append({
|
196 |
+
"role": "function",
|
197 |
+
"name": function_name,
|
198 |
+
"content": str(result), # Convert the result to a string
|
199 |
+
})
|
200 |
+
|
201 |
+
# Call the model again to generate a user-facing message based on the function result
|
202 |
+
chat_response = chat_completion_request(
|
203 |
+
messages, functions=functions
|
204 |
+
)
|
205 |
+
assistant_message = chat_response.json()["choices"][0]["message"]
|
206 |
+
messages.append(assistant_message)
|
207 |
+
|
208 |
+
usage = chat_response.json()['usage']
|
209 |
+
cost2 = openai_api_calculate_cost(usage)
|
210 |
+
|
211 |
+
# Print the final conversation
|
212 |
+
# pretty_print_conversation(messages)
|
213 |
+
return assistant_message, cost2
|
214 |
+
|
215 |
+
|
216 |
+
def main_function(init_prompt, prompt, user_input):
|
217 |
+
first_call_result, cost1 = first_call(init_prompt, user_input)
|
218 |
+
function_call_process_result = function_call_process(first_call_result)
|
219 |
+
second_prompt_build_result = second_prompt_build(prompt, function_call_process_result)
|
220 |
+
second_call_result, cost2 = second_call(second_prompt_build_result, function_call_process_result)
|
221 |
+
return first_call_result, function_call_process_result, second_call_result, cost1, cost2
|
222 |
+
|
223 |
+
def gradio_function():
|
224 |
+
init_prompt = gr.Textbox(label="init_prompt (for 1st call)")
|
225 |
+
prompt = gr.Textbox(label="prompt (for 2nd call)")
|
226 |
+
user_input = gr.Textbox(label="User Input")
|
227 |
+
output_1st_call = gr.Textbox(label="output_1st_call")
|
228 |
+
output_fc_call = gr.Textbox(label="output_fc_call")
|
229 |
+
output_2nd_call = gr.Textbox(label="output_2nd_call")
|
230 |
+
cost = gr.Textbox(label="Cost 1")
|
231 |
+
cost2 = gr.Textbox(label="Cost 2")
|
232 |
+
|
233 |
+
|
234 |
+
iface = gr.Interface(
|
235 |
+
fn=main_function,
|
236 |
+
inputs=[init_prompt, prompt, user_input],
|
237 |
+
outputs=[output_1st_call, output_fc_call, output_2nd_call, cost, cost2],
|
238 |
+
title="Test",
|
239 |
+
description="Accuracy",
|
240 |
+
)
|
241 |
+
|
242 |
+
iface.launch(share=True)
|
243 |
+
|
244 |
+
if __name__ == "__main__":
|
245 |
+
gradio_function()
|