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