-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNPC_Code_Interpreter
291 lines (236 loc) · 12.6 KB
/
NPC_Code_Interpreter
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import os
import re
import tkinter as tk
from tkinter import scrolledtext, messagebox
from groq import Groq
import requests
from bs4 import BeautifulSoup
import datetime
import subprocess
class ChatApp:
def __init__(self, root):
self.client = Groq(api_key='YOUR_GROQ_API_KEY')
self.conversation_history = []
self.max_history_length = 10
self.web_search_api_key = 'YOUR_GOOGLE_CUSTOM_SEARCH_KEY'
self.web_search_cx = 'YOUR_GOOGLE_CUSTOM_SEARCH_ENGINE_ID'
self.root = root
self.root.title("NPC v0.10")
self.root.geometry("800x600")
self.root.grid_rowconfigure(0, weight=1)
self.root.grid_columnconfigure(0, weight=1)
self.root.grid_columnconfigure(1, weight=1)
self.chat_window = scrolledtext.ScrolledText(root, wrap=tk.WORD, state='disabled')
self.chat_window.grid(row=0, column=0, padx=10, pady=10, sticky='nsew')
self.web_results_window = scrolledtext.ScrolledText(root, wrap=tk.WORD, state='disabled')
self.web_results_window.grid(row=0, column=1, padx=10, pady=10, sticky='nsew')
self.web_results_window.grid_remove()
self.user_entry = tk.Text(root, wrap=tk.WORD, height=5)
self.user_entry.grid(row=1, column=0, columnspan=2, padx=10, pady=10, sticky='ew')
self.user_entry.bind("<Return>", self.insert_newline)
self.user_entry.bind("<Shift-Return>", self.check_shift_enter_key)
self.send_button = tk.Button(root, text="Send", command=self.send_input)
self.send_button.grid(row=2, column=0, columnspan=2, padx=10, pady=10)
self.toggle_button = tk.Button(root, text="Show Results", command=self.toggle_results_window)
self.toggle_button.grid(row=3, column=1, padx=10, pady=10, sticky='e')
self.run_code_button = tk.Button(root, text="Run Code", command=self.run_code)
self.run_code_button.grid(row=4, column=1, padx=10, pady=10, sticky='e')
self.run_code_button.grid_remove()
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
self.code_snippet = ""
self.code_output = "" # Variable to store code output
def insert_newline(self, event):
self.user_entry.insert(tk.INSERT, "\n")
return "break"
def check_shift_enter_key(self, event):
self.send_input()
return "break"
def advanced_summarize_history(self):
user_entries = [entry["content"] for entry in self.conversation_history if entry["role"] == "user"]
ai_entries = [entry["content"] for entry in self.conversation_history if entry["role"] == "assistant"]
user_summary = "User queries: " + " | ".join(user_entries[-self.max_history_length:])
ai_summary = "AI responses: " + " | ".join(ai_entries[-self.max_history_length:])
return f"{user_summary}\n{ai_summary}"
def send_input(self):
user_input = self.user_entry.get("1.0", tk.END).strip()
if user_input.lower() == 'quit':
self.root.quit()
return
self.user_entry.delete("1.0", tk.END)
if self.code_output:
user_input += f"\n\nPrevious Code Output:\n{self.code_output}"
self.conversation_history.append({"role": "user", "content": user_input})
self.chat_window.config(state='normal')
self.chat_window.insert(tk.END, f"\nYou: {user_input}\n", 'user')
self.chat_window.tag_config('user', foreground='blue')
self.chat_window.config(state='disabled')
self.chat_window.see(tk.END)
context_summary = self.advanced_summarize_history()
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
system_prompt = (
"1. You are a really obedient, knowledgeable and highly capable assistant. "
"2. For complex queries, take your time to think deeply and break down the problem into smaller, manageable steps. "
"3. Respond concisely and clearly, using bullet points and simple language when appropriate. "
"4. Ask clarifying questions if needed to ensure you fully understand the user's request. "
"5. Provide step-by-step solutions and explanations to help the user understand your reasoning. "
"6. Include any code you generate inside triple backticks (```). "
"7. After generating code, be very strict in checking the result, and be nitpicky about any possible improvements or bugs. "
"8. Use the special reserved word $STOP$ to indicate when the iterative code improvement loop should stop. "
f"9. The current date and time is {current_time}. "
)
messages = [
{"role": "system", "content": system_prompt},
{"role": "system", "content": f"Context summary:\n{context_summary}"},
*self.conversation_history
]
search_results = self.perform_web_search(user_input)
self.display_search_results(search_results)
try:
search_results_text = "\n\n".join(search_results)
messages.append({"role": "system", "content": f"Web search results:\n{search_results_text}"})
stream = self.client.chat.completions.create(
messages=messages,
model="llama3-70b-8192",
temperature=0.7,
max_tokens=1024,
top_p=0.9,
stop=None,
stream=True,
)
ai_response = ""
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
ai_response += delta
self.chat_window.config(state='normal')
self.chat_window.insert(tk.END, f"\nAI: {ai_response}\n", 'ai')
self.chat_window.tag_config('ai', foreground='green')
self.chat_window.config(state='disabled')
self.chat_window.see(tk.END)
self.conversation_history.append({"role": "assistant", "content": ai_response})
if len(self.conversation_history) > self.max_history_length * 2:
self.conversation_history = self.conversation_history[-self.max_history_length * 2:]
code_match = re.search(r'```(.*?)```', ai_response, re.DOTALL)
if code_match:
self.code_snippet = code_match.group(1).strip()
self.run_code_button.grid()
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def perform_web_search(self, query):
search_results = []
try:
search_url = f"https://www.googleapis.com/customsearch/v1?key={self.web_search_api_key}&cx={self.web_search_cx}&q={query}"
response = requests.get(search_url)
if response.status_code == 200:
results = response.json().get('items', [])
for result in results[:3]:
title = result.get('title')
snippet = result.get('snippet')
link = result.get('link')
page_content = self.fetch_page_content(link)
search_results.append(f"Title: {title}\nSnippet: {snippet}\nLink: {link}\nContent: {page_content}\n")
else:
search_results.append("Failed to retrieve search results.")
except Exception as e:
search_results.append(f"An error occurred during web search: {e}")
return search_results
def fetch_page_content(self, url):
try:
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
text_content = ' '.join(soup.stripped_strings)
return text_content[:1000] + "..." if len(text_content) > 1000 else text_content
else:
return "Failed to retrieve page content."
except Exception as e:
return f"An error occurred while fetching page content: {e}"
def display_search_results(self, results):
self.web_results_window.config(state='normal')
self.web_results_window.delete('1.0', tk.END)
for result in results:
self.web_results_window.insert(tk.END, f"Searcher LLM: {result}\n", 'result')
self.web_results_window.tag_config('result', foreground='purple')
self.web_results_window.config(state='disabled')
self.web_results_window.see(tk.END)
def toggle_results_window(self):
if self.web_results_window.winfo_viewable():
self.web_results_window.grid_remove()
self.toggle_button.config(text="Show Results")
else:
self.web_results_window.grid()
self.toggle_button.config(text="Hide Results")
def run_code(self):
if not self.code_snippet:
return
try:
process = subprocess.run(['python', '-c', self.code_snippet], capture_output=True, text=True)
output = process.stdout + process.stderr
self.chat_window.config(state='normal')
self.chat_window.insert(tk.END, f"\nCode Output:\n{output}\n", 'output')
self.chat_window.tag_config('output', foreground='orange')
self.chat_window.config(state='disabled')
self.chat_window.see(tk.END)
self.code_output = output
self.run_code_button.grid_remove()
self.iterate_code_improvement(output)
except Exception as e:
messagebox.showerror("Error", f"An error occurred while running the code: {e}")
def iterate_code_improvement(self, output):
system_prompt = (
"1. You are a really obedient, knowledgeable and highly capable assistant. "
"2. For complex queries, take your time to think deeply and break down the problem into smaller, manageable steps. "
"3. Respond concisely and clearly, using bullet points and simple language when appropriate. "
"4. Ask clarifying questions if needed to ensure you fully understand the user's request. "
"5. Provide step-by-step solutions and explanations to help the user understand your reasoning. "
"6. Include any code you generate inside triple backticks (```). "
"7. After generating code, be very strict in checking the result, and be nitpicky about any possible improvements or bugs. "
"8. Use the special reserved word $STOP$ to indicate when the iterative code improvement loop should stop. "
)
context_summary = self.advanced_summarize_history()
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
system_prompt += f"9. The current date and time is {current_time}. "
messages = [
{"role": "system", "content": system_prompt},
{"role": "system", "content": f"Context summary:\n{context_summary}"},
*self.conversation_history
]
while True:
try:
stream = self.client.chat.completions.create(
messages=messages,
model="llama3-70b-8192",
temperature=0.7,
max_tokens=1024,
top_p=0.9,
stop=None,
stream=True,
)
ai_response = ""
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
ai_response += delta
self.chat_window.config(state='normal')
self.chat_window.insert(tk.END, f"\nAI: {ai_response}\n", 'ai')
self.chat_window.tag_config('ai', foreground='green')
self.chat_window.config(state='disabled')
self.chat_window.see(tk.END)
self.conversation_history.append({"role": "assistant", "content": ai_response})
if "$STOP$" in ai_response:
break
code_match = re.search(r'```(.*?)```', ai_response, re.DOTALL)
if code_match:
self.code_snippet = code_match.group(1).strip()
self.run_code_button.grid()
break
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
break
def on_closing(self):
if messagebox.askokcancel("Quit", "Do you want to quit?"):
self.root.destroy()
if __name__ == "__main__":
root = tk.Tk()
app = ChatApp(root)
root.mainloop()