Spaces:
Sleeping
Sleeping
dragonSwing
commited on
Commit
•
fa0debb
1
Parent(s):
8e97414
Add application file
Browse files- .gitignore +195 -0
- app.py +149 -0
- langchain_app.py +162 -0
- requirements.txt +4 -0
.gitignore
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Created by https://www.toptal.com/developers/gitignore/api/python,visualstudiocode
|
2 |
+
# Edit at https://www.toptal.com/developers/gitignore?templates=python,visualstudiocode
|
3 |
+
|
4 |
+
### Python ###
|
5 |
+
# Byte-compiled / optimized / DLL files
|
6 |
+
__pycache__/
|
7 |
+
*.py[cod]
|
8 |
+
*$py.class
|
9 |
+
|
10 |
+
# C extensions
|
11 |
+
*.so
|
12 |
+
|
13 |
+
# Distribution / packaging
|
14 |
+
.Python
|
15 |
+
build/
|
16 |
+
develop-eggs/
|
17 |
+
dist/
|
18 |
+
downloads/
|
19 |
+
eggs/
|
20 |
+
.eggs/
|
21 |
+
lib/
|
22 |
+
lib64/
|
23 |
+
parts/
|
24 |
+
sdist/
|
25 |
+
var/
|
26 |
+
wheels/
|
27 |
+
share/python-wheels/
|
28 |
+
*.egg-info/
|
29 |
+
.installed.cfg
|
30 |
+
*.egg
|
31 |
+
MANIFEST
|
32 |
+
|
33 |
+
# PyInstaller
|
34 |
+
# Usually these files are written by a python script from a template
|
35 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
36 |
+
*.manifest
|
37 |
+
*.spec
|
38 |
+
|
39 |
+
# Installer logs
|
40 |
+
pip-log.txt
|
41 |
+
pip-delete-this-directory.txt
|
42 |
+
|
43 |
+
# Unit test / coverage reports
|
44 |
+
htmlcov/
|
45 |
+
.tox/
|
46 |
+
.nox/
|
47 |
+
.coverage
|
48 |
+
.coverage.*
|
49 |
+
.cache
|
50 |
+
nosetests.xml
|
51 |
+
coverage.xml
|
52 |
+
*.cover
|
53 |
+
*.py,cover
|
54 |
+
.hypothesis/
|
55 |
+
.pytest_cache/
|
56 |
+
cover/
|
57 |
+
|
58 |
+
# Translations
|
59 |
+
*.mo
|
60 |
+
*.pot
|
61 |
+
|
62 |
+
# Django stuff:
|
63 |
+
*.log
|
64 |
+
local_settings.py
|
65 |
+
db.sqlite3
|
66 |
+
db.sqlite3-journal
|
67 |
+
|
68 |
+
# Flask stuff:
|
69 |
+
instance/
|
70 |
+
.webassets-cache
|
71 |
+
|
72 |
+
# Scrapy stuff:
|
73 |
+
.scrapy
|
74 |
+
|
75 |
+
# Sphinx documentation
|
76 |
+
docs/_build/
|
77 |
+
|
78 |
+
# PyBuilder
|
79 |
+
.pybuilder/
|
80 |
+
target/
|
81 |
+
|
82 |
+
# Jupyter Notebook
|
83 |
+
.ipynb_checkpoints
|
84 |
+
|
85 |
+
# IPython
|
86 |
+
profile_default/
|
87 |
+
ipython_config.py
|
88 |
+
|
89 |
+
# pyenv
|
90 |
+
# For a library or package, you might want to ignore these files since the code is
|
91 |
+
# intended to run in multiple environments; otherwise, check them in:
|
92 |
+
# .python-version
|
93 |
+
|
94 |
+
# pipenv
|
95 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
96 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
97 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
98 |
+
# install all needed dependencies.
|
99 |
+
#Pipfile.lock
|
100 |
+
|
101 |
+
# poetry
|
102 |
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
103 |
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
104 |
+
# commonly ignored for libraries.
|
105 |
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
106 |
+
#poetry.lock
|
107 |
+
|
108 |
+
# pdm
|
109 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
110 |
+
#pdm.lock
|
111 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
112 |
+
# in version control.
|
113 |
+
# https://pdm.fming.dev/#use-with-ide
|
114 |
+
.pdm.toml
|
115 |
+
|
116 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
117 |
+
__pypackages__/
|
118 |
+
|
119 |
+
# Celery stuff
|
120 |
+
celerybeat-schedule
|
121 |
+
celerybeat.pid
|
122 |
+
|
123 |
+
# SageMath parsed files
|
124 |
+
*.sage.py
|
125 |
+
|
126 |
+
# Environments
|
127 |
+
.env
|
128 |
+
.venv
|
129 |
+
env/
|
130 |
+
venv/
|
131 |
+
ENV/
|
132 |
+
env.bak/
|
133 |
+
venv.bak/
|
134 |
+
|
135 |
+
# Spyder project settings
|
136 |
+
.spyderproject
|
137 |
+
.spyproject
|
138 |
+
|
139 |
+
# Rope project settings
|
140 |
+
.ropeproject
|
141 |
+
|
142 |
+
# mkdocs documentation
|
143 |
+
/site
|
144 |
+
|
145 |
+
# mypy
|
146 |
+
.mypy_cache/
|
147 |
+
.dmypy.json
|
148 |
+
dmypy.json
|
149 |
+
|
150 |
+
# Pyre type checker
|
151 |
+
.pyre/
|
152 |
+
|
153 |
+
# pytype static type analyzer
|
154 |
+
.pytype/
|
155 |
+
|
156 |
+
# Cython debug symbols
|
157 |
+
cython_debug/
|
158 |
+
|
159 |
+
# PyCharm
|
160 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
161 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
162 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
163 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
164 |
+
#.idea/
|
165 |
+
|
166 |
+
### Python Patch ###
|
167 |
+
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
168 |
+
poetry.toml
|
169 |
+
|
170 |
+
# ruff
|
171 |
+
.ruff_cache/
|
172 |
+
|
173 |
+
# LSP config files
|
174 |
+
pyrightconfig.json
|
175 |
+
|
176 |
+
### VisualStudioCode ###
|
177 |
+
.vscode/*
|
178 |
+
!.vscode/settings.json
|
179 |
+
!.vscode/tasks.json
|
180 |
+
!.vscode/launch.json
|
181 |
+
!.vscode/extensions.json
|
182 |
+
!.vscode/*.code-snippets
|
183 |
+
|
184 |
+
# Local History for Visual Studio Code
|
185 |
+
.history/
|
186 |
+
|
187 |
+
# Built Visual Studio Code Extensions
|
188 |
+
*.vsix
|
189 |
+
|
190 |
+
### VisualStudioCode Patch ###
|
191 |
+
# Ignore all local history of files
|
192 |
+
.history
|
193 |
+
.ionide
|
194 |
+
|
195 |
+
# End of https://www.toptal.com/developers/gitignore/api/python,visualstudiocode
|
app.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import openai
|
3 |
+
import requests
|
4 |
+
import csv
|
5 |
+
|
6 |
+
|
7 |
+
prompt_templates = {
|
8 |
+
"Default ChatGPT": "",
|
9 |
+
"Helpful Asistant": """
|
10 |
+
Assistant is a large language model trained by OpenAI.
|
11 |
+
|
12 |
+
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
|
13 |
+
|
14 |
+
Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.
|
15 |
+
|
16 |
+
Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
|
17 |
+
"""
|
18 |
+
}
|
19 |
+
|
20 |
+
def get_empty_state():
|
21 |
+
return {"total_tokens": 0, "messages": []}
|
22 |
+
|
23 |
+
def download_prompt_templates():
|
24 |
+
url = "https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv"
|
25 |
+
try:
|
26 |
+
response = requests.get(url)
|
27 |
+
reader = csv.reader(response.text.splitlines())
|
28 |
+
next(reader) # skip the header row
|
29 |
+
for row in reader:
|
30 |
+
if len(row) >= 2:
|
31 |
+
act = row[0].strip('"')
|
32 |
+
prompt = row[1].strip('"')
|
33 |
+
prompt_templates[act] = prompt
|
34 |
+
|
35 |
+
except requests.exceptions.RequestException as e:
|
36 |
+
print(f"An error occurred while downloading prompt templates: {e}")
|
37 |
+
return
|
38 |
+
|
39 |
+
choices = list(prompt_templates.keys())
|
40 |
+
choices = choices[:1] + sorted(choices[1:])
|
41 |
+
return gr.update(value=choices[0], choices=choices)
|
42 |
+
|
43 |
+
def on_token_change(user_token):
|
44 |
+
openai.api_key = user_token
|
45 |
+
|
46 |
+
def on_prompt_template_change(prompt_template):
|
47 |
+
if not isinstance(prompt_template, str): return
|
48 |
+
return prompt_templates[prompt_template]
|
49 |
+
|
50 |
+
def submit_message(user_token, prompt, prompt_template, temperature, max_tokens, context_length, state):
|
51 |
+
|
52 |
+
history = state['messages']
|
53 |
+
|
54 |
+
if not prompt:
|
55 |
+
return gr.update(value=''), [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], f"Total tokens used: {state['total_tokens']}", state
|
56 |
+
|
57 |
+
prompt_template = prompt_templates[prompt_template]
|
58 |
+
|
59 |
+
system_prompt = []
|
60 |
+
if prompt_template:
|
61 |
+
system_prompt = [{ "role": "system", "content": prompt_template }]
|
62 |
+
|
63 |
+
prompt_msg = { "role": "user", "content": prompt }
|
64 |
+
|
65 |
+
if not user_token:
|
66 |
+
history.append(prompt_msg)
|
67 |
+
history.append({
|
68 |
+
"role": "system",
|
69 |
+
"content": "Error: OpenAI API Key is not set."
|
70 |
+
})
|
71 |
+
return '', [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)], f"Total tokens used: 0", state
|
72 |
+
|
73 |
+
try:
|
74 |
+
completion = openai.ChatCompletion.create(model="gpt-3.5-turbo", messages=system_prompt + history[-context_length*2:] + [prompt_msg], temperature=temperature, max_tokens=max_tokens)
|
75 |
+
|
76 |
+
history.append(prompt_msg)
|
77 |
+
history.append(completion.choices[0].message.to_dict())
|
78 |
+
|
79 |
+
state['total_tokens'] += completion['usage']['total_tokens']
|
80 |
+
|
81 |
+
except Exception as e:
|
82 |
+
history.append(prompt_msg)
|
83 |
+
history.append({
|
84 |
+
"role": "system",
|
85 |
+
"content": f"Error: {e}"
|
86 |
+
})
|
87 |
+
|
88 |
+
total_tokens_used_msg = f"Total tokens used: {state['total_tokens']}"
|
89 |
+
chat_messages = [(history[i]['content'], history[i+1]['content']) for i in range(0, len(history)-1, 2)]
|
90 |
+
|
91 |
+
return '', chat_messages, total_tokens_used_msg, state
|
92 |
+
|
93 |
+
def clear_conversation():
|
94 |
+
return gr.update(value=None, visible=True), None, "", get_empty_state()
|
95 |
+
|
96 |
+
|
97 |
+
css = """
|
98 |
+
#col-container {max-width: 1400px; margin-left: auto; margin-right: auto;}
|
99 |
+
#chatbox {min-height: 400px;}
|
100 |
+
#header {text-align: center;}
|
101 |
+
#prompt_template_preview {padding: 1rem; border-width: 1px; border-style: solid; border-color: #e0e0e0; border-radius: 4px;}
|
102 |
+
#total_tokens_str {text-align: right; font-size: 0.8rem; color: #666;}
|
103 |
+
#label {font-size: 0.8rem; padding: 0.5em; margin: 0;}
|
104 |
+
.message { font-size: 1.2rem; }
|
105 |
+
"""
|
106 |
+
|
107 |
+
with gr.Blocks(css=css) as demo:
|
108 |
+
|
109 |
+
state = gr.State(get_empty_state())
|
110 |
+
|
111 |
+
|
112 |
+
with gr.Column(elem_id="col-container"):
|
113 |
+
gr.Markdown("""## OpenAI ChatGPT Demo
|
114 |
+
Using the ofiicial API (gpt-3.5-turbo model)
|
115 |
+
Prompt templates from [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts).""",
|
116 |
+
elem_id="header")
|
117 |
+
|
118 |
+
with gr.Row():
|
119 |
+
with gr.Column(scale=0.3):
|
120 |
+
gr.Markdown("Enter your OpenAI API Key. You can get one [here](https://platform.openai.com/account/api-keys).", elem_id="label")
|
121 |
+
user_token = gr.Textbox(value='', placeholder="OpenAI API Key", type="password", show_label=False)
|
122 |
+
prompt_template = gr.Dropdown(label="Set a custom insruction for the chatbot:", choices=list(prompt_templates.keys()))
|
123 |
+
prompt_template_preview = gr.Markdown(elem_id="prompt_template_preview")
|
124 |
+
with gr.Accordion("Advanced parameters", open=False):
|
125 |
+
temperature = gr.Slider(minimum=0, maximum=2.0, value=0.7, step=0.1, label="Temperature", info="Higher = more creative/chaotic")
|
126 |
+
max_tokens = gr.Slider(minimum=100, maximum=4096, value=1000, step=1, label="Max tokens per response")
|
127 |
+
context_length = gr.Slider(minimum=1, maximum=10, value=2, step=1, label="Context length", info="Number of previous messages to send to the chatbot. Be careful with high values, it can blow up the token budget quickly.")
|
128 |
+
with gr.Column(scale=0.7):
|
129 |
+
chatbot = gr.Chatbot(elem_id="chatbox")
|
130 |
+
input_message = gr.Textbox(show_label=False, placeholder="Enter text and press enter", visible=True).style(container=False)
|
131 |
+
btn_submit = gr.Button("Submit")
|
132 |
+
total_tokens_str = gr.Markdown(elem_id="total_tokens_str")
|
133 |
+
btn_clear_conversation = gr.Button("🔃 Start New Conversation")
|
134 |
+
|
135 |
+
gr.HTML('''<br><br><br><center>You can duplicate this Space to skip the queue:<a href="https://huggingface.co/spaces/dragonSwing/chatgpt-grad?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a><br>
|
136 |
+
<p><img src="https://visitor-badge.glitch.me/badge?page_id=dragonswing.chatgpt_api_grad_hf" alt="visitors"></p></center>''')
|
137 |
+
|
138 |
+
btn_submit.click(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, context_length, state], [input_message, chatbot, total_tokens_str, state])
|
139 |
+
input_message.submit(submit_message, [user_token, input_message, prompt_template, temperature, max_tokens, context_length, state], [input_message, chatbot, total_tokens_str, state])
|
140 |
+
btn_clear_conversation.click(clear_conversation, [], [input_message, chatbot, total_tokens_str, state])
|
141 |
+
prompt_template.change(on_prompt_template_change, inputs=[prompt_template], outputs=[prompt_template_preview])
|
142 |
+
user_token.change(on_token_change, inputs=[user_token], outputs=[])
|
143 |
+
|
144 |
+
|
145 |
+
demo.load(download_prompt_templates, inputs=None, outputs=[prompt_template], queue=False)
|
146 |
+
|
147 |
+
|
148 |
+
demo.queue(concurrency_count=10)
|
149 |
+
demo.launch(height='800px')
|
langchain_app.py
ADDED
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import requests
|
3 |
+
import csv
|
4 |
+
import os
|
5 |
+
from langchain import ConversationChain, PromptTemplate
|
6 |
+
from langchain.chat_models import ChatOpenAI
|
7 |
+
from langchain.memory import ConversationBufferWindowMemory
|
8 |
+
|
9 |
+
prompt_templates = {
|
10 |
+
"Default ChatGPT": "",
|
11 |
+
"Helpful Asistant": """
|
12 |
+
Assistant is a large language model trained by OpenAI.
|
13 |
+
|
14 |
+
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
|
15 |
+
|
16 |
+
Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.
|
17 |
+
|
18 |
+
Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
|
19 |
+
"""
|
20 |
+
}
|
21 |
+
|
22 |
+
# TODO: Add system prompt input when langchain support multiple inputs for ConversationalChain
|
23 |
+
chat_template = """
|
24 |
+
Assistant is a large language model trained by OpenAI.
|
25 |
+
|
26 |
+
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
|
27 |
+
|
28 |
+
Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.
|
29 |
+
|
30 |
+
Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
|
31 |
+
|
32 |
+
{history}
|
33 |
+
Human: {input}
|
34 |
+
Assistant:"""
|
35 |
+
|
36 |
+
chat_prompt = PromptTemplate(
|
37 |
+
input_variables=["system_prompt", "history", "input"],
|
38 |
+
template=chat_template
|
39 |
+
)
|
40 |
+
|
41 |
+
memory = ConversationBufferWindowMemory(k=2)
|
42 |
+
|
43 |
+
def get_empty_state():
|
44 |
+
return {"total_tokens": 0, "messages": []}
|
45 |
+
|
46 |
+
def download_prompt_templates():
|
47 |
+
url = "https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv"
|
48 |
+
try:
|
49 |
+
response = requests.get(url)
|
50 |
+
reader = csv.reader(response.text.splitlines())
|
51 |
+
next(reader) # skip the header row
|
52 |
+
for row in reader:
|
53 |
+
if len(row) >= 2:
|
54 |
+
act = row[0].strip('"')
|
55 |
+
prompt = row[1].strip('"')
|
56 |
+
prompt_templates[act] = prompt
|
57 |
+
|
58 |
+
except requests.exceptions.RequestException as e:
|
59 |
+
print(f"An error occurred while downloading prompt templates: {e}")
|
60 |
+
return
|
61 |
+
|
62 |
+
choices = list(prompt_templates.keys())
|
63 |
+
choices = choices[:1] + sorted(choices[1:])
|
64 |
+
return gr.update(value=choices[0], choices=choices)
|
65 |
+
|
66 |
+
def on_token_change(user_token):
|
67 |
+
os.environ["OPENAI_API_KEY"] = user_token
|
68 |
+
|
69 |
+
def on_prompt_template_change(prompt_template):
|
70 |
+
if not isinstance(prompt_template, str): return
|
71 |
+
return prompt_templates[prompt_template]
|
72 |
+
|
73 |
+
def submit_message(chat_history, prompt, prompt_template, temperature, max_tokens, context_length):
|
74 |
+
memory.k = context_length
|
75 |
+
chatgpt_chain = ConversationChain(
|
76 |
+
llm=ChatOpenAI(temperature=temperature, max_tokens=max_tokens),
|
77 |
+
prompt=chat_prompt,
|
78 |
+
verbose=False,
|
79 |
+
memory=memory,
|
80 |
+
)
|
81 |
+
|
82 |
+
if not prompt:
|
83 |
+
return gr.update(value=''), chat_history, f""
|
84 |
+
|
85 |
+
system_prompt = prompt_templates[prompt_template]
|
86 |
+
|
87 |
+
if not os.environ["OPENAI_API_KEY"]:
|
88 |
+
return '', chat_history.append((prompt, "Error: OpenAI API Key is not set.")), f"Total tokens used: 0"
|
89 |
+
|
90 |
+
try:
|
91 |
+
response = chatgpt_chain.predict(
|
92 |
+
system_prompt=system_prompt,
|
93 |
+
input=prompt
|
94 |
+
)
|
95 |
+
|
96 |
+
chat_history.append((prompt, response))
|
97 |
+
|
98 |
+
|
99 |
+
except Exception as e:
|
100 |
+
chat_history.append((prompt, f"Error: {e}"))
|
101 |
+
|
102 |
+
total_tokens_used_msg = f""
|
103 |
+
|
104 |
+
return '', chat_history, total_tokens_used_msg
|
105 |
+
|
106 |
+
def clear_conversation():
|
107 |
+
memory.clear()
|
108 |
+
return gr.update(value=None, visible=True), None, ""
|
109 |
+
|
110 |
+
|
111 |
+
css = """
|
112 |
+
#col-container {max-width: 90%; margin-left: auto; margin-right: auto;}
|
113 |
+
#chatbox {min-height: 400px;}
|
114 |
+
#header {text-align: center;}
|
115 |
+
#prompt_template_preview {padding: 1rem; border-width: 1px; border-style: solid; border-color: #e0e0e0; border-radius: 4px;}
|
116 |
+
#total_tokens_str {text-align: right; font-size: 0.8rem; color: #666;}
|
117 |
+
#label {font-size: 0.8rem; padding: 0.5em; margin: 0;}
|
118 |
+
.message { font-size: 1.2rem; }
|
119 |
+
"""
|
120 |
+
|
121 |
+
with gr.Blocks(css=css) as demo:
|
122 |
+
|
123 |
+
state = gr.State(get_empty_state())
|
124 |
+
|
125 |
+
|
126 |
+
with gr.Column(elem_id="col-container"):
|
127 |
+
gr.Markdown("""## OpenAI ChatGPT Demo
|
128 |
+
Using the ofiicial API (gpt-3.5-turbo model)
|
129 |
+
Prompt templates from [awesome-chatgpt-prompts](https://github.com/f/awesome-chatgpt-prompts).""",
|
130 |
+
elem_id="header")
|
131 |
+
|
132 |
+
with gr.Row():
|
133 |
+
with gr.Column(scale=0.3):
|
134 |
+
gr.Markdown("Enter your OpenAI API Key. You can get one [here](https://platform.openai.com/account/api-keys).", elem_id="label")
|
135 |
+
user_token = gr.Textbox(value='', placeholder="OpenAI API Key", type="password", show_label=False)
|
136 |
+
prompt_template = gr.Dropdown(label="Set a custom insruction for the chatbot:", choices=list(prompt_templates.keys()))
|
137 |
+
prompt_template_preview = gr.Markdown(elem_id="prompt_template_preview", value=prompt_templates["Default ChatGPT"])
|
138 |
+
with gr.Accordion("Advanced parameters", open=False):
|
139 |
+
temperature = gr.Slider(minimum=0, maximum=2.0, value=0.7, step=0.1, label="Temperature", info="Higher = more creative/chaotic")
|
140 |
+
max_tokens = gr.Slider(minimum=100, maximum=4096, value=1000, step=1, label="Max tokens per response")
|
141 |
+
context_length = gr.Slider(minimum=1, maximum=10, value=2, step=1, label="Context length", info="Number of previous messages to send to the chatbot. Be careful with high values, it can blow up the token budget quickly.")
|
142 |
+
with gr.Column(scale=0.7):
|
143 |
+
chatbot = gr.Chatbot(elem_id="chatbox")
|
144 |
+
input_message = gr.Textbox(show_label=False, placeholder="Enter text and press enter", visible=True).style(container=False)
|
145 |
+
btn_submit = gr.Button("Submit")
|
146 |
+
total_tokens_str = gr.Markdown(elem_id="total_tokens_str")
|
147 |
+
btn_clear_conversation = gr.Button("🔃 Start New Conversation")
|
148 |
+
|
149 |
+
gr.HTML('''<br><br><br><center>You can duplicate this Space to skip the queue:<a href="https://huggingface.co/spaces/dragonSwing/chatgpt-grad?duplicate=true"><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a><br>
|
150 |
+
<p><img src="https://visitor-badge.glitch.me/badge?page_id=dragonswing.chatgpt_api_grad_hf" alt="visitors"></p></center>''')
|
151 |
+
|
152 |
+
btn_submit.click(submit_message, [chatbot, input_message, prompt_template, temperature, max_tokens, context_length], [input_message, chatbot, total_tokens_str])
|
153 |
+
input_message.submit(submit_message, [chatbot, input_message, prompt_template, temperature, max_tokens, context_length], [input_message, chatbot, total_tokens_str])
|
154 |
+
btn_clear_conversation.click(clear_conversation, [], [input_message, chatbot, total_tokens_str])
|
155 |
+
prompt_template.change(on_prompt_template_change, inputs=[prompt_template], outputs=[prompt_template_preview])
|
156 |
+
user_token.change(on_token_change, inputs=[user_token], outputs=[])
|
157 |
+
|
158 |
+
demo.load(download_prompt_templates, inputs=None, outputs=[prompt_template], queue=False)
|
159 |
+
|
160 |
+
|
161 |
+
demo.queue(concurrency_count=10)
|
162 |
+
demo.launch(height='800px')
|
requirements.txt
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
langchain
|
3 |
+
openai
|
4 |
+
requests
|