Spaces:
Running
Running
Gregor Betz
commited on
Commit
·
8bd8cd0
1
Parent(s):
b28fd93
First code commit
Browse files- README.md +9 -4
- app.py +385 -0
- backend/logging.py +69 -0
- backend/messages_processing.py +60 -0
- backend/models.py +109 -0
- backend/svg_processing.py +32 -0
- requirements.txt +11 -0
README.md
CHANGED
@@ -1,10 +1,15 @@
|
|
1 |
---
|
2 |
-
title: Benjamin
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
sdk_version: 4.37.2
|
|
|
|
|
|
|
|
|
|
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
license: agpl-3.0
|
|
|
1 |
---
|
2 |
+
title: Benjamin
|
3 |
+
emoji: 🪁
|
4 |
+
colorFrom: blue
|
5 |
+
colorTo: yellow
|
6 |
sdk: gradio
|
7 |
sdk_version: 4.37.2
|
8 |
+
hf_oauth: true
|
9 |
+
hf_oauth_scopes:
|
10 |
+
- email
|
11 |
+
- read-repos
|
12 |
+
- inference-api
|
13 |
app_file: app.py
|
14 |
pinned: false
|
15 |
license: agpl-3.0
|
app.py
ADDED
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import asyncio
|
4 |
+
import copy
|
5 |
+
import logging
|
6 |
+
import os
|
7 |
+
import uuid
|
8 |
+
import ujson
|
9 |
+
|
10 |
+
import aiohttp
|
11 |
+
from datasets import load_dataset
|
12 |
+
import gradio as gr
|
13 |
+
import pandas as pd
|
14 |
+
|
15 |
+
from backend.logging import log_messages, log_feedback
|
16 |
+
from backend.messages_processing import add_details, history_to_langchain_format
|
17 |
+
from backend.models import get_chat_model_wrapper, LLMBackends
|
18 |
+
from backend.svg_processing import postprocess_svg
|
19 |
+
|
20 |
+
logging.basicConfig(level=logging.DEBUG)
|
21 |
+
|
22 |
+
|
23 |
+
RESTRICT_ACCESS = False
|
24 |
+
|
25 |
+
INFERENCE_SERVER_URL = "https://api-inference.huggingface.co/models/{model_id}"
|
26 |
+
MODEL_ID = "HuggingFaceH4/zephyr-7b-beta"
|
27 |
+
TOURIST_MODEL_KWARGS = {
|
28 |
+
"max_tokens": 800,
|
29 |
+
"temperature": 0.6,
|
30 |
+
}
|
31 |
+
|
32 |
+
GUIDE_KWARGS = {
|
33 |
+
"expert_model": "meta-llama/Meta-Llama-3-70B-Instruct",
|
34 |
+
# "accounts/fireworks/models/nous-hermes-2-mixtral-8x7b-dpo-fp8",
|
35 |
+
# "accounts/fireworks/models/llama-v3-8b-instruct-hf",
|
36 |
+
# "accounts/fireworks/models/nous-hermes-2-mixtral-8x7b-dpo-fp8",
|
37 |
+
"inference_server_url": "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-70B-Instruct",
|
38 |
+
# "https://api.fireworks.ai/inference/v1",
|
39 |
+
"llm_backend": "HFChat",
|
40 |
+
"classifier_kwargs": {
|
41 |
+
"model_id": "MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli",
|
42 |
+
# "inference_server_url": "https://sa710i91bnjvbhir.us-east-1.aws.endpoints.huggingface.cloud",
|
43 |
+
"inference_server_url": "https://api-inference.huggingface.co/models/MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli",
|
44 |
+
"batch_size": 8,
|
45 |
+
},
|
46 |
+
}
|
47 |
+
|
48 |
+
EXAMPLES = [
|
49 |
+
("We're a nature-loving family with three kids, have some money left, and no plans "
|
50 |
+
"for next week-end. Should we visit Disneyland?"),
|
51 |
+
"Should I stop eating animals?",
|
52 |
+
"Bob needs a reliable and cheap car. Should he buy a Mercedes?",
|
53 |
+
('Gavin has an insurance policy that includes coverage for "General Damages," '
|
54 |
+
'which includes losses from "missed employment due to injuries that occur '
|
55 |
+
'under regular working conditions."\n\n'
|
56 |
+
'Gavin works as an A/C repair technician in a small town. One day, Gavin is '
|
57 |
+
'hired to repair an air conditioner located on the second story of a building. '
|
58 |
+
'Because Gavin is an experienced repairman, he knows that the safest way to '
|
59 |
+
'access the unit is with a sturdy ladder. While climbing the ladder, Gavin '
|
60 |
+
'loses his balance and falls, causing significant injury. Because of this, he '
|
61 |
+
'subsequently has to stop working for weeks. Gavin files a claim with his '
|
62 |
+
'insurance company for lost income.\n\n'
|
63 |
+
'Does Gavin\'s insurance policy cover his claim for lost income?'),
|
64 |
+
"How many arguments did you consider in your internal reasoning? (Brief answer, please.)",
|
65 |
+
"Did you consider any counterarguments in your internal reasoning?",
|
66 |
+
"From all the arguments you considered and assessed, which one is the most important?",
|
67 |
+
"Did you refute any arguments or reasons for lack of plausibility?"
|
68 |
+
]
|
69 |
+
|
70 |
+
TITLE = """<div align=left>
|
71 |
+
<h1>🪁 Benjamin Chatbot with Logikon <i>Guided Reasoning™️</i></h1>
|
72 |
+
</div>"""
|
73 |
+
|
74 |
+
TERMS_OF_SERVICE ="""<h2>Terms of Service</h2>
|
75 |
+
|
76 |
+
<p>This app is provided by Logikon AI for educational and research purposes only.
|
77 |
+
The app is powered by Logikon's <i>Guided Reasoning™️</i> technology, which is a novel approach to
|
78 |
+
reasoning with language models. The app is a work in progress and may not always provide accurate or reliable information.
|
79 |
+
By accepting these terms of service, you agree not to use the app:</p>
|
80 |
+
|
81 |
+
<ol>
|
82 |
+
<li>In any way that violates any applicable national, federal, state, local or international law or regulation;</li>
|
83 |
+
<li>For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;</li>
|
84 |
+
<li>To generate and/or disseminate malware (e.g. ransomware) or any other content to be used for the purpose of harming electronic systems;</li>
|
85 |
+
<li>To generate or disseminate verifiably false information and/or content with the purpose of harming others;</li>
|
86 |
+
<li>To generate or disseminate personal identifiable information that can be used to harm an individual;</li>
|
87 |
+
<li>To generate or disseminate information and/or content (e.g. images, code, posts, articles), and place the information and/or content in any public context (e.g. bot generating tweets) without expressly and intelligibly disclaiming that the information and/or content is machine generated;</li>
|
88 |
+
<li>To defame, disparage or otherwise harass others;</li>
|
89 |
+
<li>To impersonate or attempt to impersonate (e.g. deepfakes) others without their consent;</li>
|
90 |
+
<li>For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;</li>
|
91 |
+
<li>For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;</li>
|
92 |
+
<li>To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;</li>
|
93 |
+
<li>For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;</li>
|
94 |
+
<li>To provide medical advice and medical results interpretation;</li>
|
95 |
+
<li>To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use). </li>
|
96 |
+
</ol>
|
97 |
+
|
98 |
+
<p>By using the feedback buttons, you agree that </p>
|
99 |
+
"""
|
100 |
+
|
101 |
+
CHATBOT_INSTRUCTIONS = (
|
102 |
+
"1️⃣ In the first turn, ask a question or present a decision problem.\n"
|
103 |
+
"2️⃣ In the following turns, ask the chatbot to explain its reasoning.\n\n"
|
104 |
+
"💡 Note that this demo bot is hard-wired to deliberate with Guided Reasoning™️ "
|
105 |
+
"in the first turn only.\n\n"
|
106 |
+
"🔐 Chat conversations and feedback are logged (anonymously).\n"
|
107 |
+
"Please don't share sensitive or identity revealing information.\n\n"
|
108 |
+
"🙏 Benjamin is powered by the free API inference services of 🤗.\n"
|
109 |
+
"In case you encounter issues due to rate limits... simply try again later.\n"
|
110 |
+
"[We're searching sponsors to run Benjamin on 🚀 dedicated infrastructure.]\n\n"
|
111 |
+
"💬 We'd love to hear your feedback!\n"
|
112 |
+
"Please use the 👋 Community tab above to reach out.\n"
|
113 |
+
)
|
114 |
+
|
115 |
+
|
116 |
+
|
117 |
+
if RESTRICT_ACCESS:
|
118 |
+
df_users = pd.DataFrame(load_dataset("logikon/benjamin_access", token=os.environ["HF_DATASETS_TOKEN"])["train"])
|
119 |
+
logging.info(f"Loaded user database with {len(df_users)} entries.")
|
120 |
+
|
121 |
+
logging.info(f"Reasoning guide expert model is {GUIDE_KWARGS['expert_model']}.")
|
122 |
+
|
123 |
+
def new_conversation_id():
|
124 |
+
conversation_id = str(uuid.uuid4())
|
125 |
+
print(f"New conversation with conversation ID: {conversation_id}")
|
126 |
+
return conversation_id
|
127 |
+
|
128 |
+
def access_granted(profile: gr.OAuthProfile | None, oauth_token: gr.OAuthToken | None) -> bool:
|
129 |
+
if RESTRICT_ACCESS:
|
130 |
+
known = profile.username in df_users.hf_account.unique()
|
131 |
+
access = df_users[df_users.hf_account.eq(profile.username)].status.eq("access").iloc[0] if known else False
|
132 |
+
else:
|
133 |
+
known = False
|
134 |
+
access = True
|
135 |
+
logging.info(f"User {profile.username} known: {known}, access: {access}")
|
136 |
+
if access:
|
137 |
+
os.environ["HF_TOKEN"] = oauth_token.token
|
138 |
+
print("set HF_TOKEN to oauth token")
|
139 |
+
return access
|
140 |
+
|
141 |
+
async def gr_server_health() -> bool:
|
142 |
+
try:
|
143 |
+
url = os.environ["GR_ENDPOINT"] + "/health"
|
144 |
+
headers = {'Content-type': 'application/json', "Authorization": f"Bearer {os.environ['GR_SESAM_OPEN']}"}
|
145 |
+
async with aiohttp.ClientSession(json_serialize=ujson.dumps) as session:
|
146 |
+
async with session.get(url, headers=headers) as resp:
|
147 |
+
content = await resp.text()
|
148 |
+
if ujson.loads(content).get("status") == "ok":
|
149 |
+
return True
|
150 |
+
else:
|
151 |
+
logging.error(f"Server health check failed: {content}")
|
152 |
+
return False
|
153 |
+
except Exception as e:
|
154 |
+
logging.error(f"When checking server health: Error: {e}")
|
155 |
+
return False
|
156 |
+
|
157 |
+
|
158 |
+
async def log_like_dislike(conversation_id: gr.State, x: gr.LikeData, profile: gr.OAuthProfile | None):
|
159 |
+
if profile:
|
160 |
+
print(conversation_id, profile.name, x.index, x.liked)
|
161 |
+
asyncio.create_task(
|
162 |
+
log_feedback(
|
163 |
+
liked=x.liked,
|
164 |
+
conversation_id=conversation_id,
|
165 |
+
step=x.index,
|
166 |
+
metadata={"timestamp": pd.Timestamp.now().timestamp()}
|
167 |
+
)
|
168 |
+
)
|
169 |
+
|
170 |
+
|
171 |
+
def add_message(history, message, conversation_id):
|
172 |
+
if len(history) == 0:
|
173 |
+
# reset conversation id
|
174 |
+
conversation_id = new_conversation_id()
|
175 |
+
|
176 |
+
print(f"add_message: {history} \n {message}")
|
177 |
+
if message["text"] is not None:
|
178 |
+
history.append((message["text"], None))
|
179 |
+
return history, gr.MultimodalTextbox(value=None, interactive=False), conversation_id
|
180 |
+
|
181 |
+
|
182 |
+
async def bot(
|
183 |
+
history,
|
184 |
+
tourist_model_id,
|
185 |
+
tourist_inference_url,
|
186 |
+
tourist_inference_token,
|
187 |
+
tourist_backend,
|
188 |
+
tourist_temperature,
|
189 |
+
conversation_id,
|
190 |
+
profile: gr.OAuthProfile | None,
|
191 |
+
oauth_token: gr.OAuthToken | None,
|
192 |
+
progress=gr.Progress(),
|
193 |
+
):
|
194 |
+
|
195 |
+
if not oauth_token:
|
196 |
+
raise gr.Error("Please sign in to use the chatbot.")
|
197 |
+
|
198 |
+
if not access_granted(profile, oauth_token):
|
199 |
+
raise gr.Error("You've not been granted access to use the chatbot. Please reach out to Logikon AI team.")
|
200 |
+
|
201 |
+
if not await gr_server_health():
|
202 |
+
raise gr.Error("The backend server is not healthy. Please try again later.")
|
203 |
+
|
204 |
+
|
205 |
+
print(f"Token (type={type(oauth_token.token)}): ||{oauth_token.token}||")
|
206 |
+
print(f"History (conversation: {conversation_id}): {history}")
|
207 |
+
history_langchain_format = history_to_langchain_format(history)
|
208 |
+
|
209 |
+
# use guide always and exclusively at first turn
|
210 |
+
if len(history_langchain_format) <= 1:
|
211 |
+
|
212 |
+
url = os.environ["GR_ENDPOINT"] + "/guide"
|
213 |
+
headers = {'Content-type': 'application/json', "Authorization": f"Bearer {os.environ['GR_SESAM_OPEN']}"}
|
214 |
+
tourist_config = {
|
215 |
+
"model_id": tourist_model_id,
|
216 |
+
"inference_server_url": tourist_inference_url,
|
217 |
+
"llm_backend": tourist_backend,
|
218 |
+
"api_key": tourist_inference_token if tourist_inference_token else oauth_token.token,
|
219 |
+
**TOURIST_MODEL_KWARGS,
|
220 |
+
"temperature": tourist_temperature,
|
221 |
+
}
|
222 |
+
guide_config = copy.deepcopy(GUIDE_KWARGS)
|
223 |
+
guide_config["api_key"] = oauth_token.token # expert model api key
|
224 |
+
guide_config["classifier_kwargs"]["api_key"] = oauth_token.token # classifier api key
|
225 |
+
input_data = {
|
226 |
+
"message": history[-1][0],
|
227 |
+
"tourist_config": tourist_config,
|
228 |
+
"guide_config": guide_config
|
229 |
+
}
|
230 |
+
try:
|
231 |
+
artifacts = {}
|
232 |
+
progress_step = 0
|
233 |
+
gr.Info("👀 Checking LLM availability... (may take a few minutes).")
|
234 |
+
async with aiohttp.ClientSession(json_serialize=ujson.dumps) as session:
|
235 |
+
async with session.post(url, headers=headers, json=input_data) as resp:
|
236 |
+
while True:
|
237 |
+
line = await resp.content.readline()
|
238 |
+
if line:
|
239 |
+
data = ujson.loads(line)
|
240 |
+
if data:
|
241 |
+
if "error" in data:
|
242 |
+
msg = data["error"]
|
243 |
+
if "token" in msg:
|
244 |
+
gr.Warning(
|
245 |
+
"↩️ Please sign out, reload the chatbot, and sign in again.",
|
246 |
+
duration=0
|
247 |
+
)
|
248 |
+
if "health checks" in msg:
|
249 |
+
gr.Warning(
|
250 |
+
"❌ LLMs are currently unavailable due to rate limits or cold start times. "
|
251 |
+
"↩️ Please reload and try again in a minute.",
|
252 |
+
duration=0
|
253 |
+
)
|
254 |
+
raise gr.Error(msg)
|
255 |
+
elif data.get("type") == "progress":
|
256 |
+
print(data.get("value"))
|
257 |
+
gr.Info(data.get("value"), duration=12)
|
258 |
+
progress((progress_step,4))
|
259 |
+
progress_step += 1
|
260 |
+
elif data.get("type") is not None:
|
261 |
+
artifacts[data.get("type")] = data.get("value")
|
262 |
+
|
263 |
+
else:
|
264 |
+
break
|
265 |
+
except asyncio.TimeoutError:
|
266 |
+
msg = "Guided reasoning process took too long. Please try again."
|
267 |
+
raise gr.Error(msg)
|
268 |
+
except Exception as e:
|
269 |
+
msg = f"Error during guided reasoning: {e}"
|
270 |
+
raise gr.Error(msg)
|
271 |
+
|
272 |
+
svg = postprocess_svg(artifacts.get("svg_argmap"))
|
273 |
+
protocol = artifacts.get("protocol", "I'm sorry, I failed to reason about the problem.")
|
274 |
+
response = artifacts.pop("response", "")
|
275 |
+
if not response:
|
276 |
+
response = "I'm sorry, I failed to draft a response."
|
277 |
+
response = add_details(response, protocol, svg)
|
278 |
+
|
279 |
+
# otherwise, just chat
|
280 |
+
else:
|
281 |
+
chat_model_kwargs = {
|
282 |
+
"model_id": tourist_model_id,
|
283 |
+
"inference_server_url": tourist_inference_url,
|
284 |
+
"token": tourist_inference_token if tourist_inference_token else oauth_token.token,
|
285 |
+
"backend": tourist_backend,
|
286 |
+
**TOURIST_MODEL_KWARGS,
|
287 |
+
"temperature": tourist_temperature,
|
288 |
+
}
|
289 |
+
chat_model = get_chat_model_wrapper(**chat_model_kwargs)
|
290 |
+
try:
|
291 |
+
response = chat_model.invoke(history_langchain_format).content
|
292 |
+
except Exception as e:
|
293 |
+
msg = f"Error during chatbot inference: {e}"
|
294 |
+
gr.Error(msg)
|
295 |
+
raise ValueError(msg)
|
296 |
+
|
297 |
+
print(f"Response: {response}")
|
298 |
+
history[-1][1] = response
|
299 |
+
|
300 |
+
asyncio.create_task(log_messages(
|
301 |
+
history[-1],
|
302 |
+
conversation_id,
|
303 |
+
len(history),
|
304 |
+
{
|
305 |
+
"tourist_llm": tourist_model_id,
|
306 |
+
"guide_llm": GUIDE_KWARGS["expert_model"],
|
307 |
+
"timestamp": pd.Timestamp.now().timestamp(),
|
308 |
+
}
|
309 |
+
))
|
310 |
+
|
311 |
+
return history
|
312 |
+
|
313 |
+
|
314 |
+
|
315 |
+
with gr.Blocks() as demo:
|
316 |
+
|
317 |
+
# preamble
|
318 |
+
gr.Markdown(TITLE)
|
319 |
+
login = gr.LoginButton()
|
320 |
+
login.activate()
|
321 |
+
conversation_id = gr.State(str(uuid.uuid4()))
|
322 |
+
tos_approved = gr.State(False)
|
323 |
+
|
324 |
+
|
325 |
+
with gr.Tab(label="Chatbot", visible=False) as chatbot_tab:
|
326 |
+
|
327 |
+
# chatbot
|
328 |
+
chatbot = gr.Chatbot(
|
329 |
+
[],
|
330 |
+
elem_id="chatbot",
|
331 |
+
bubble_full_width=False,
|
332 |
+
placeholder=CHATBOT_INSTRUCTIONS,
|
333 |
+
)
|
334 |
+
chat_input = gr.MultimodalTextbox(interactive=True, file_types=["image"], placeholder="Enter message ...", show_label=False)
|
335 |
+
clear = gr.ClearButton([chat_input, chatbot])
|
336 |
+
gr.Examples([{"text": e, "files":[]} for e in EXAMPLES], chat_input)
|
337 |
+
|
338 |
+
# configs
|
339 |
+
with gr.Accordion("Client LLM Configuration", open=False):
|
340 |
+
gr.Markdown("Configure your client LLM that underpins this chatbot and is guided through the reasoning process.")
|
341 |
+
with gr.Row():
|
342 |
+
with gr.Column(2):
|
343 |
+
tourist_backend = gr.Dropdown(choices=[b.value for b in LLMBackends], value=LLMBackends.HFChat.value, label="LLM Inference Backend")
|
344 |
+
tourist_model_id = gr.Textbox(MODEL_ID, label="Model ID", max_lines=1)
|
345 |
+
tourist_inference_url = gr.Textbox(INFERENCE_SERVER_URL.format(model_id=MODEL_ID), label="Inference Server URL", max_lines=1)
|
346 |
+
tourist_inference_token = gr.Textbox("", label="Inference Token", max_lines=1, placeholder="Not required with HF Inference Api (default)", type="password")
|
347 |
+
with gr.Column(1):
|
348 |
+
tourist_temperature = gr.Slider(0, 1.0, value = TOURIST_MODEL_KWARGS["temperature"], label="Temperature")
|
349 |
+
|
350 |
+
# logic
|
351 |
+
chat_msg = chat_input.submit(add_message, [chatbot, chat_input, conversation_id], [chatbot, chat_input, conversation_id])
|
352 |
+
bot_msg = chat_msg.then(
|
353 |
+
bot,
|
354 |
+
[
|
355 |
+
chatbot,
|
356 |
+
tourist_model_id,
|
357 |
+
tourist_inference_url,
|
358 |
+
tourist_inference_token,
|
359 |
+
tourist_backend,
|
360 |
+
tourist_temperature,
|
361 |
+
conversation_id
|
362 |
+
],
|
363 |
+
chatbot,
|
364 |
+
api_name="bot_response"
|
365 |
+
)
|
366 |
+
bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])
|
367 |
+
|
368 |
+
chatbot.like(log_like_dislike, [conversation_id], None)
|
369 |
+
|
370 |
+
# we're resetting conversation id when drafting first response in bot()
|
371 |
+
# clear.click(new_conversation_id, outputs = [conversation_id])
|
372 |
+
|
373 |
+
with gr.Tab(label="Terms of Service") as tos_tab:
|
374 |
+
|
375 |
+
gr.HTML(TERMS_OF_SERVICE)
|
376 |
+
tos_checkbox = gr.Checkbox(label="I agree to the terms of service")
|
377 |
+
tos_checkbox.input(
|
378 |
+
lambda x: (x, gr.Checkbox(label="I agree to the terms of service", interactive=False), gr.Tab("Chatbot", visible=True)),
|
379 |
+
tos_checkbox,
|
380 |
+
[tos_approved, tos_checkbox, chatbot_tab]
|
381 |
+
)
|
382 |
+
|
383 |
+
if __name__ == "__main__":
|
384 |
+
demo.queue(default_concurrency_limit=8)
|
385 |
+
demo.launch(show_error=True)
|
backend/logging.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"log chat messages and feedbacks to a dataset"
|
2 |
+
|
3 |
+
from typing import Tuple
|
4 |
+
|
5 |
+
import os
|
6 |
+
import tempfile
|
7 |
+
import ujson
|
8 |
+
import uuid
|
9 |
+
|
10 |
+
import huggingface_hub
|
11 |
+
import pandas as pd
|
12 |
+
|
13 |
+
LOGS_DATSET_PATH = "logikon/benjamin-logs"
|
14 |
+
|
15 |
+
|
16 |
+
async def log_messages(
|
17 |
+
messages: Tuple[str, str],
|
18 |
+
conversation_id: str,
|
19 |
+
step: int,
|
20 |
+
metadata: dict = None
|
21 |
+
):
|
22 |
+
|
23 |
+
data = {
|
24 |
+
"conversation_id": conversation_id,
|
25 |
+
"step": step,
|
26 |
+
"human": messages[0],
|
27 |
+
"ai": messages[1],
|
28 |
+
"metadata": list(metadata.items()) if metadata else []
|
29 |
+
}
|
30 |
+
|
31 |
+
with tempfile.TemporaryFile(mode="w+") as f:
|
32 |
+
ujson.dump(data, f)
|
33 |
+
f.flush()
|
34 |
+
|
35 |
+
api = huggingface_hub.HfApi()
|
36 |
+
api.upload_file(
|
37 |
+
path_or_fileobj=f.buffer,
|
38 |
+
path_in_repo=os.path.join("data", pd.Timestamp.now().date().isoformat(), conversation_id, f"step_{step}.json"),
|
39 |
+
repo_id=LOGS_DATSET_PATH,
|
40 |
+
repo_type="dataset",
|
41 |
+
token=os.environ["HF_DATASETS_TOKEN"]
|
42 |
+
)
|
43 |
+
|
44 |
+
async def log_feedback(
|
45 |
+
liked: bool,
|
46 |
+
conversation_id: str,
|
47 |
+
step: int,
|
48 |
+
metadata: dict = None
|
49 |
+
):
|
50 |
+
|
51 |
+
data = {
|
52 |
+
"conversation_id": conversation_id,
|
53 |
+
"step": step,
|
54 |
+
"liked": liked,
|
55 |
+
"metadata": list(metadata.items()) if metadata else []
|
56 |
+
}
|
57 |
+
|
58 |
+
with tempfile.TemporaryFile(mode="w+") as f:
|
59 |
+
ujson.dump(data, f)
|
60 |
+
f.flush()
|
61 |
+
|
62 |
+
api = huggingface_hub.HfApi()
|
63 |
+
api.upload_file(
|
64 |
+
path_or_fileobj=f.buffer,
|
65 |
+
path_in_repo=os.path.join("data", pd.Timestamp.now().date().isoformat(), conversation_id, f"feedback_{step[0]}_{str(uuid.uuid4())}.json"),
|
66 |
+
repo_id=LOGS_DATSET_PATH,
|
67 |
+
repo_type="dataset",
|
68 |
+
token=os.environ["HF_DATASETS_TOKEN"]
|
69 |
+
)
|
backend/messages_processing.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Tuple
|
2 |
+
|
3 |
+
import logging
|
4 |
+
|
5 |
+
from langchain_core.messages import AIMessage, HumanMessage
|
6 |
+
|
7 |
+
def add_details(response: str, reasoning: str, svg_argmap: str) -> str:
|
8 |
+
"""Add reasoning details to the response message shown in chat."""
|
9 |
+
response_with_details = (
|
10 |
+
f"<p>{response}</p>"
|
11 |
+
'<details id="reasoning">'
|
12 |
+
"<summary><i>Internal reasoning trace</i></summary>"
|
13 |
+
f"<code>{reasoning}</code></details>"
|
14 |
+
'<details id="svg_argmap">'
|
15 |
+
"<summary><i>Argument map</i></summary>"
|
16 |
+
f"\n<div>\n{svg_argmap}\n</div>\n</details>"
|
17 |
+
)
|
18 |
+
return response_with_details
|
19 |
+
|
20 |
+
|
21 |
+
def get_details(response_with_details: str) -> Tuple[str, dict[str, str]]:
|
22 |
+
"""Extract response and details from response_with_details shown in chat."""
|
23 |
+
if "<details id=" not in response_with_details:
|
24 |
+
return response_with_details, {}
|
25 |
+
details_dict = {}
|
26 |
+
response, *details_raw = response_with_details.split('<details id="')
|
27 |
+
for details in details_raw:
|
28 |
+
details_id, details_content = details.split('"', maxsplit=1)
|
29 |
+
details_content = details_content.strip()
|
30 |
+
if details_content.endswith("</code></details>"):
|
31 |
+
details_content = details_content.split("<code>")[1].strip()
|
32 |
+
details_content = details_content[:-len("</code></details>")].strip()
|
33 |
+
elif details_content.endswith("</div></details>"):
|
34 |
+
details_content = details_content.split("<div>")[1].strip()
|
35 |
+
details_content = details_content[:-len("</div></details>")].strip()
|
36 |
+
else:
|
37 |
+
logging.warning(f"Unrecognized details content: {details_content}")
|
38 |
+
details_content = "UNRECOGNIZED DETAILS CONTENT"
|
39 |
+
details_dict[details_id] = details_content
|
40 |
+
return response, details_dict
|
41 |
+
|
42 |
+
|
43 |
+
def history_to_langchain_format(history: list[tuple[str, str]]) -> list:
|
44 |
+
history_langchain_format = [] # History in LangChain format, as shown to the LLM
|
45 |
+
for human, ai in history:
|
46 |
+
history_langchain_format.append(HumanMessage(content=human))
|
47 |
+
if ai is None:
|
48 |
+
continue
|
49 |
+
response, details = get_details(ai)
|
50 |
+
logging.debug(f"Details: {details}")
|
51 |
+
content = response
|
52 |
+
if "reasoning" in details:
|
53 |
+
content += (
|
54 |
+
"\n\n"
|
55 |
+
"#+BEGIN_INTERNAL_TRACE // Internal reasoning trace (hidden from user)\n"
|
56 |
+
f"{details.get('reasoning', '')}\n"
|
57 |
+
"#+END_INTERNAL_TRACE"
|
58 |
+
)
|
59 |
+
history_langchain_format.append(AIMessage(content=content))
|
60 |
+
return history_langchain_format
|
backend/models.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Dict
|
2 |
+
from enum import Enum
|
3 |
+
|
4 |
+
from langchain_community.chat_models.huggingface import ChatHuggingFace
|
5 |
+
from langchain_community.llms.huggingface_endpoint import HuggingFaceEndpoint
|
6 |
+
from langchain_core import pydantic_v1
|
7 |
+
from langchain_core.language_models.chat_models import BaseChatModel
|
8 |
+
from langchain_core.utils import get_from_dict_or_env
|
9 |
+
from langchain_openai import ChatOpenAI
|
10 |
+
|
11 |
+
|
12 |
+
class LLMBackends(Enum):
|
13 |
+
"""LLMBackends
|
14 |
+
|
15 |
+
Enum for LLMBackends.
|
16 |
+
"""
|
17 |
+
|
18 |
+
VLLM = "VLLM"
|
19 |
+
HFChat = "HFChat"
|
20 |
+
Fireworks = "Fireworks"
|
21 |
+
|
22 |
+
|
23 |
+
class LazyChatHuggingFace(ChatHuggingFace):
|
24 |
+
"""LazyChatHuggingFace"""
|
25 |
+
|
26 |
+
def __init__(self, **kwargs: Any):
|
27 |
+
BaseChatModel.__init__(self, **kwargs)
|
28 |
+
|
29 |
+
from transformers import AutoTokenizer
|
30 |
+
|
31 |
+
if not self.model_id:
|
32 |
+
self._resolve_model_id()
|
33 |
+
|
34 |
+
self.tokenizer = (
|
35 |
+
AutoTokenizer.from_pretrained(self.model_id)
|
36 |
+
if self.tokenizer is None
|
37 |
+
else self.tokenizer
|
38 |
+
)
|
39 |
+
|
40 |
+
class LazyHuggingFaceEndpoint(HuggingFaceEndpoint):
|
41 |
+
"""LazyHuggingFaceEndpoint"""
|
42 |
+
# We're using a lazy endpoint to avoid logging in with hf_token,
|
43 |
+
# which might in fact be a hf_oauth token that does only permit inference,
|
44 |
+
# not logging in.
|
45 |
+
|
46 |
+
@pydantic_v1.root_validator()
|
47 |
+
def validate_environment(cls, values: Dict) -> Dict: # noqa: UP006, N805
|
48 |
+
"""Validate that package is installed and that the API token is valid."""
|
49 |
+
try:
|
50 |
+
from huggingface_hub import AsyncInferenceClient, InferenceClient
|
51 |
+
|
52 |
+
except ImportError:
|
53 |
+
msg = (
|
54 |
+
"Could not import huggingface_hub python package. "
|
55 |
+
"Please install it with `pip install huggingface_hub`."
|
56 |
+
)
|
57 |
+
raise ImportError(msg) # noqa: B904
|
58 |
+
|
59 |
+
huggingfacehub_api_token = get_from_dict_or_env(
|
60 |
+
values, "huggingfacehub_api_token", "HUGGINGFACEHUB_API_TOKEN"
|
61 |
+
)
|
62 |
+
|
63 |
+
values["client"] = InferenceClient(
|
64 |
+
model=values["model"],
|
65 |
+
timeout=values["timeout"],
|
66 |
+
token=huggingfacehub_api_token,
|
67 |
+
**values["server_kwargs"],
|
68 |
+
)
|
69 |
+
values["async_client"] = AsyncInferenceClient(
|
70 |
+
model=values["model"],
|
71 |
+
timeout=values["timeout"],
|
72 |
+
token=huggingfacehub_api_token,
|
73 |
+
**values["server_kwargs"],
|
74 |
+
)
|
75 |
+
|
76 |
+
return values
|
77 |
+
|
78 |
+
|
79 |
+
def get_chat_model_wrapper(
|
80 |
+
model_id: str,
|
81 |
+
inference_server_url: str,
|
82 |
+
token: str,
|
83 |
+
backend: str = "HuggingFaceEndpoint",
|
84 |
+
**model_init_kwargs
|
85 |
+
):
|
86 |
+
|
87 |
+
backend = LLMBackends(backend)
|
88 |
+
|
89 |
+
if backend == LLMBackends.HFChat:
|
90 |
+
llm = LazyHuggingFaceEndpoint(
|
91 |
+
endpoint_url=inference_server_url,
|
92 |
+
task="text-generation",
|
93 |
+
huggingfacehub_api_token=token,
|
94 |
+
**model_init_kwargs,
|
95 |
+
)
|
96 |
+
|
97 |
+
from transformers import AutoTokenizer
|
98 |
+
|
99 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, token=token)
|
100 |
+
chat_model = LazyChatHuggingFace(llm=llm, model_id=model_id, tokenizer=tokenizer)
|
101 |
+
elif backend in [LLMBackends.VLLM, LLMBackends.Fireworks]:
|
102 |
+
chat_model = ChatOpenAI(
|
103 |
+
model=model_id,
|
104 |
+
openai_api_base=inference_server_url, # type: ignore
|
105 |
+
openai_api_key=token, # type: ignore
|
106 |
+
**model_init_kwargs,
|
107 |
+
)
|
108 |
+
|
109 |
+
return chat_model
|
backend/svg_processing.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
|
3 |
+
# check: https://github.com/vasturiano/d3-zoomable/blob/master/example/svg/index.html
|
4 |
+
|
5 |
+
def remove_links_svg(svg):
|
6 |
+
svg = svg.replace("</a>","")
|
7 |
+
svg = svg.replace("\n\n","\n")
|
8 |
+
regex = r"<a xlink[^>]*>"
|
9 |
+
svg = re.sub(regex, "", svg, count=0, flags=re.MULTILINE)
|
10 |
+
return svg
|
11 |
+
|
12 |
+
def resize_svg(svg, max_width=800):
|
13 |
+
regex = r"<svg width=\"(?P<width>[\d]+)pt\" height=\"(?P<height>[\d]+)pt\""
|
14 |
+
match = next(re.finditer(regex, svg, re.MULTILINE))
|
15 |
+
width = int(match.group("width"))
|
16 |
+
height = int(match.group("height"))
|
17 |
+
if width <= max_width:
|
18 |
+
return svg
|
19 |
+
|
20 |
+
scale = max_width / width
|
21 |
+
s_width = round(scale * width)
|
22 |
+
s_height = round(scale * height)
|
23 |
+
s_svg = svg.replace(match.group(), f'<svg width="{s_width}pt" height="{s_height}pt"')
|
24 |
+
return s_svg
|
25 |
+
|
26 |
+
def postprocess_svg(svg):
|
27 |
+
if not svg:
|
28 |
+
return ""
|
29 |
+
svg = "<svg" + svg.split("<svg", maxsplit=1)[1]
|
30 |
+
svg = remove_links_svg(svg)
|
31 |
+
svg = resize_svg(svg, max_width=800)
|
32 |
+
return svg
|
requirements.txt
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# https://github.com/gradio-app/gradio/pull/7887
|
2 |
+
gradio@https://gradio-builds.s3.amazonaws.com/9560433a8b9b71e088f233b73a030a9b198c500c/gradio-4.26.0-py3-none-any.whl
|
3 |
+
aiohttp
|
4 |
+
datasets
|
5 |
+
huggingface_hub
|
6 |
+
langchain
|
7 |
+
langchain_community
|
8 |
+
langchain_openai
|
9 |
+
sentencepiece
|
10 |
+
transformers
|
11 |
+
ujson
|