Skip to content

Commit 509b23f

Browse files
authored
Merge branch 'main' into dev/kernel_env
2 parents 7336b80 + e854ada commit 509b23f

File tree

9 files changed

+179
-149
lines changed

9 files changed

+179
-149
lines changed

.env.azure-example

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
OPENAI_API_KEY=XXXX
22
OPENAI_API_TYPE=azure
3-
OPENAI_BASE_URL=https://your-resource-name.openai.azure.com
3+
OPENAI_API_BASE=https://your-resource-name.openai.azure.com
44
OPENAI_API_VERSION=2023-03-15-preview
55
# OPENAI_EXTRA_HEADERS={"key": "value"}
66
AZURE_OPENAI_DEPLOYMENTS=[{"displayName": "GPT-3.5", "name": "your-gpt-3.5-deployment"}, {"displayName": "GPT-4", "name": "your-gpt-4-deployment"}]

.env.example

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
OPENAI_API_KEY=sk-XXXX
22
OPENAI_API_TYPE=open_ai
3-
OPENAI_BASE_URL=https://api.openai.com/v1
3+
OPENAI_API_BASE=https://api.openai.com/v1
44
OPENAI_API_VERSION=2023-03-15-preview
55
# OPENAI_EXTRA_HEADERS={"key": "value"}
66
OPENAI_MODELS=[{"displayName": "GPT-3.5", "name": "gpt-3.5-turbo"}, {"displayName": "GPT-4", "name": "gpt-4"}]

frontend/src/App.tsx

Lines changed: 12 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -41,13 +41,13 @@ function App() {
4141
let [messages, setMessages] = useState<Array<MessageDict>>(
4242
Array.from([
4343
{
44-
text: "Hello! I'm a GPT Code assistant. Ask me to do something for you! Pro tip: you can upload a file and I'll be able to use it.",
45-
role: "system",
44+
text: "Hello! I am a GPT Code assistant. Ask me to do something for you! Pro tip: you can upload a file and I'll be able to use it.",
45+
role: "generator",
4646
type: "message",
4747
},
4848
{
4949
text: "If I get stuck just type 'reset' and I'll restart the kernel.",
50-
role: "system",
50+
role: "generator",
5151
type: "message",
5252
},
5353
])
@@ -77,7 +77,7 @@ function App() {
7777

7878
const handleCommand = (command: string) => {
7979
if (command == "reset") {
80-
addMessage({text: "Restarting the kernel.", type: "message", role: "system"});
80+
addMessage({ text: "Restarting the kernel.", type: "message", role: "system" });
8181
setWaitingForSystem(WaitingStates.StartingKernel);
8282

8383
fetch(`${Config.API_ADDRESS}/restart`, {
@@ -118,21 +118,22 @@ function App() {
118118
}),
119119
});
120120

121-
122-
123121
const data = await response.json();
124122
const code = data.code;
125123

126-
addMessage({ text: code, type: "code", role: "system" });
127-
addMessage({ text: data.text, type: "message", role: "system" });
124+
addMessage({ text: data.text, type: "message", role: "generator" });
128125

129126
if (response.status != 200) {
130127
setWaitingForSystem(WaitingStates.Idle);
131128
return;
132129
}
133130

134-
submitCode(code);
135-
setWaitingForSystem(WaitingStates.RunningCode);
131+
if (!!code) {
132+
submitCode(code);
133+
setWaitingForSystem(WaitingStates.RunningCode);
134+
} else {
135+
setWaitingForSystem(WaitingStates.Idle);
136+
}
136137
} catch (error) {
137138
console.error(
138139
"There has been a problem with your fetch operation:",
@@ -159,26 +160,8 @@ function App() {
159160
}
160161

161162
function completeUpload(message: string) {
162-
addMessage({
163-
text: message,
164-
type: "message",
165-
role: "system",
166-
});
167-
163+
addMessage({ text: message, type: "message", role: "upload" });
168164
setWaitingForSystem(WaitingStates.Idle);
169-
170-
// Inform prompt server
171-
fetch(`${Config.WEB_ADDRESS}/inject-context`, {
172-
method: "POST",
173-
headers: {
174-
"Content-Type": "application/json",
175-
},
176-
body: JSON.stringify({
177-
prompt: message,
178-
}),
179-
})
180-
.then(() => {})
181-
.catch((error) => console.error("Error:", error));
182165
}
183166

184167
function startUpload(_: string) {

frontend/src/components/Chat.css

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
div.message.generator {
2+
background: rgba(247,247,248);
3+
}
4+
15
div.message.system {
26
background: rgba(247,247,248);
37
}
@@ -20,6 +24,10 @@ div.avatar svg {
2024
overflow-x: hidden;
2125
}
2226

27+
div.message.generator div.avatar {
28+
background: #74a89b;
29+
}
30+
2331
div.message.system div.avatar {
2432
background: #74a89b;
2533
}

frontend/src/components/Chat.tsx

Lines changed: 55 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import "./Chat.css";
22

33
import VoiceChatIcon from "@mui/icons-material/VoiceChat";
44
import PersonIcon from "@mui/icons-material/Person";
5+
import TerminalIcon from '@mui/icons-material/Terminal';
6+
import FileUploadIcon from '@mui/icons-material/FileUpload';
57
import { MessageDict } from "../App";
68

79
import remarkGfm from 'remark-gfm';
@@ -20,48 +22,83 @@ function Message(props: {
2022
const isMarkdown = (input: string) => {
2123
const mdRegex = /\[.*\]\(.*\)|\*\*.*\*\*|__.*__|\#.*|\!\[.*\]\(.*\)|`.*`|\- .*|\|.*\|/g;
2224
return mdRegex.test(input);
23-
}
25+
};
26+
27+
let ICONS = {
28+
"upload": <FileUploadIcon />,
29+
"generator": <VoiceChatIcon />,
30+
"system": <TerminalIcon />,
31+
"user": <PersonIcon />,
32+
};
2433

2534
return (
26-
<div className={"message " + (role == "system" ? "system" : "user")}>
35+
<div className={"message " + role}>
2736
<div className="avatar-holder">
2837
<div className="avatar">
29-
{role == "system" ? <VoiceChatIcon /> : <PersonIcon />}
38+
{ ICONS[role as keyof typeof ICONS] }
3039
</div>
3140
</div>
3241
<div className="message-body">
33-
{props.type == "code" && (
34-
<div>
35-
I generated the following code:
36-
<SyntaxHighlighter wrapLongLines={true} language="python">
37-
{text}
38-
</SyntaxHighlighter>
39-
</div>
40-
)}
41-
4242
{props.type == "message" &&
4343
(props.showLoader ? (
4444
<div>
4545
{text} {props.showLoader ? <div className="loader"></div> : null}
4646
</div>
4747
) : (
4848
isMarkdown(text) ?
49-
<ReactMarkdown
50-
children={text}
51-
remarkPlugins={[remarkGfm]}
52-
/> :
49+
<ReactMarkdown
50+
children={text}
51+
remarkPlugins={[remarkGfm]}
52+
components={{
53+
code({node, inline, className, children, style, ...props}) {
54+
const match = /language-(\w+)/.exec(className || '')
55+
return !inline ? (
56+
<SyntaxHighlighter
57+
{...props}
58+
children={String(children).replace(/\n$/, '')}
59+
wrapLongLines={true}
60+
language={match ? match[1] : "python"}
61+
PreTag="div"
62+
/>
63+
) : (
64+
<code {...props} className={className}>
65+
{children}
66+
</code>
67+
)
68+
}
69+
}}
70+
/>
71+
:
5372
<div className="cell-output" dangerouslySetInnerHTML={{ __html: text }}></div>
5473
))}
5574

56-
{(props.type == "message_raw") &&
75+
{props.type == "message_error" &&
76+
(props.showLoader ? (
77+
<div>
78+
{text} {props.showLoader ? <div className="loader"></div> : null}
79+
</div>
80+
) : (
81+
<div>
82+
Execution Error:
83+
<SyntaxHighlighter
84+
{...props}
85+
children={text}
86+
wrapLongLines={true}
87+
language={"python"}
88+
PreTag="div"
89+
/>
90+
</div>
91+
))}
92+
93+
{props.type == "message_raw" &&
5794
(props.showLoader ? (
5895
<div>
5996
{text} {props.showLoader ? <div className="loader"></div> : null}
6097
</div>
6198
) : (
6299
<div className="cell-output" dangerouslySetInnerHTML={{ __html: text }}></div>
63100
))}
64-
101+
65102
{props.type == "image/png" &&
66103
<div className="cell-output-image" dangerouslySetInnerHTML={{ __html: `<img src='data:image/png;base64,${text}' />` }}></div>
67104
}

gpt_code_ui/kernel_program/kernel_manager.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def flush_kernel_msgs(kc, tries=1, timeout=0.2):
150150
elif msg["msg_type"] == "error":
151151
send_message(
152152
utils.escape_ansi("\n".join(msg["content"]["traceback"])),
153-
"message_raw",
153+
"message_error",
154154
)
155155
except queue.Empty:
156156
hit_empty += 1

gpt_code_ui/kernel_program/main.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ def start_kernel_manager():
6262
utils.store_pid(kernel_manager_process.pid, "kernel_manager")
6363

6464

65+
6566
def cleanup_kernel_program():
6667
kernel_manager.cleanup_spawned_processes()
6768

@@ -79,10 +80,10 @@ def on_recv(conn, ident, message):
7980
logger.debug("Kernel is ready.")
8081
result_queue.put({
8182
"value": "Kernel is ready.",
82-
"type": "message"
83+
"type": "message_status"
8384
})
8485

85-
elif message["type"] in ["message", "message_raw", "image/png", "image/jpeg"]:
86+
elif message["type"] in ["message", "message_raw", "message_error", "image/png", "image/jpeg"]:
8687
# TODO: 1:1 kernel <> channel mapping
8788
logger.debug("%s of type %s" % (message["value"], message["type"]))
8889

gpt_code_ui/main.py

Lines changed: 28 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,23 @@
1616

1717
APP_URL = "http://localhost:%s" % APP_PORT
1818

19+
1920
def run_webapp():
2021
try:
2122
app.run(host="0.0.0.0", port=APP_PORT, use_reloader=False)
22-
except Exception as e:
23-
logging.exception("Error running the webapp:")
23+
except Exception:
24+
logging.exception("Error running the webapp")
2425
sys.exit(1)
2526

27+
2628
def run_kernel_program():
2729
try:
2830
asyncio.run(kernel_program_main())
29-
except Exception as e:
30-
logging.exception("Error running the kernel_program:")
31+
except Exception:
32+
logging.exception("Error running the kernel_program")
3133
sys.exit(1)
3234

35+
3336
def setup_logging():
3437
log_format = "%(asctime)s [%(levelname)s]: %(message)s"
3538
logging.basicConfig(level=logging.INFO, format=log_format)
@@ -38,32 +41,33 @@ def setup_logging():
3841
file_handler.setFormatter(logging.Formatter(log_format))
3942
logging.getLogger().addHandler(file_handler)
4043

44+
4145
def print_color(text, color="gray"):
4246
# Default to gray
43-
code="242"
47+
code = "242"
4448

4549
if color == "green":
46-
code="35"
47-
50+
code = "35"
51+
4852
gray_code = "\033[38;5;%sm" % code
4953
reset_code = "\033[0m"
5054
print(f"{gray_code}{text}{reset_code}")
5155

5256

5357
def print_banner():
54-
55-
print("""
58+
print("""
5659
█▀▀ █▀█ ▀█▀ ▄▄ █▀▀ █▀█ █▀▄ █▀▀
5760
█▄█ █▀▀ ░█░ ░░ █▄▄ █▄█ █▄▀ ██▄
58-
""")
61+
""")
62+
63+
print("> Open GPT-Code UI in your browser %s" % APP_URL)
64+
print("")
65+
print("You can inspect detailed logs in app.log.")
66+
print("")
67+
print("Find your OpenAI API key at https://platform.openai.com/account/api-keys")
68+
print("")
69+
print_color("Contribute to GPT-Code UI at https://github.com/ricklamers/gpt-code-ui")
5970

60-
print("> Open GPT-Code UI in your browser %s" % APP_URL)
61-
print("")
62-
print("You can inspect detailed logs in app.log.")
63-
print("")
64-
print("Find your OpenAI API key at https://platform.openai.com/account/api-keys")
65-
print("")
66-
print_color("Contribute to GPT-Code UI at https://github.com/ricklamers/gpt-code-ui")
6771

6872
def main():
6973
setup_logging()
@@ -80,20 +84,19 @@ def main():
8084
try:
8185
app.test_client().get("/")
8286
break
83-
except:
87+
except Exception:
8488
time.sleep(0.1)
85-
86-
print_banner()
87-
89+
90+
print_banner()
91+
8892
webbrowser.open(APP_URL)
8993

9094
webapp_process.join()
9195
kernel_program_process.join()
9296

93-
9497
except KeyboardInterrupt:
9598
print("Terminating processes...")
96-
99+
97100
cleanup_kernel_program()
98101
kernel_program_process.terminate()
99102

@@ -103,6 +106,7 @@ def main():
103106
kernel_program_process.join()
104107

105108
print("Processes terminated.")
106-
109+
110+
107111
if __name__ == '__main__':
108112
main()

0 commit comments

Comments
 (0)