Gregor Betz
commited on
initial commit
Browse files- README.md +3 -3
- app.py +313 -0
- backend/logging.py +69 -0
- backend/messages_processing.py +60 -0
- backend/models.py +127 -0
- backend/svg_processing.py +32 -0
- requirements.txt +1 -0
README.md
CHANGED
@@ -1,7 +1,7 @@
|
|
1 |
---
|
2 |
-
title: Guir Chat
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
colorTo: purple
|
6 |
sdk: gradio
|
7 |
sdk_version: 4.43.0
|
|
|
1 |
---
|
2 |
+
title: Guir Chat (Template)
|
3 |
+
emoji: 🪂
|
4 |
+
colorFrom: blue
|
5 |
colorTo: purple
|
6 |
sdk: gradio
|
7 |
sdk_version: 4.43.0
|
app.py
ADDED
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from __future__ import annotations
|
2 |
+
|
3 |
+
import asyncio
|
4 |
+
import copy
|
5 |
+
import logging
|
6 |
+
import os
|
7 |
+
import uuid
|
8 |
+
|
9 |
+
import gradio as gr # type: ignore
|
10 |
+
|
11 |
+
from logikon.backends.chat_models_with_grammar import create_logits_model, LogitsModel, LLMBackends
|
12 |
+
from logikon.guides.proscons.recursive_balancing_guide import RecursiveBalancingGuide, RecursiveBalancingGuideConfig
|
13 |
+
|
14 |
+
from backend.messages_processing import add_details, history_to_langchain_format
|
15 |
+
from backend.svg_processing import postprocess_svg
|
16 |
+
|
17 |
+
logging.basicConfig(level=logging.DEBUG)
|
18 |
+
|
19 |
+
|
20 |
+
# Default client
|
21 |
+
INFERENCE_SERVER_URL = "https://api-inference.huggingface.co/models/{model_id}"
|
22 |
+
MODEL_ID = "HuggingFaceH4/zephyr-7b-beta"
|
23 |
+
CLIENT_MODEL_KWARGS = {
|
24 |
+
"max_tokens": 800,
|
25 |
+
"temperature": 0.6,
|
26 |
+
}
|
27 |
+
|
28 |
+
GUIDE_KWARGS = {
|
29 |
+
"expert_model": "accounts/fireworks/models/llama-v3p1-70b-instruct",
|
30 |
+
# "meta-llama/Meta-Llama-3.1-70B-Instruct",
|
31 |
+
# "accounts/fireworks/models/nous-hermes-2-mixtral-8x7b-dpo-fp8",
|
32 |
+
# "accounts/fireworks/models/llama-v3-8b-instruct-hf",
|
33 |
+
# "accounts/fireworks/models/nous-hermes-2-mixtral-8x7b-dpo-fp8",
|
34 |
+
"inference_server_url": "https://api.fireworks.ai/inference/v1",
|
35 |
+
# "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3.1-70B-Instruct",
|
36 |
+
# "https://api.fireworks.ai/inference/v1",
|
37 |
+
"llm_backend": "Fireworks",
|
38 |
+
"classifier_kwargs": {
|
39 |
+
"model_id": "MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli",
|
40 |
+
"inference_server_url": "https://sa710i91bnjvbhir.us-east-1.aws.endpoints.huggingface.cloud",
|
41 |
+
# "inference_server_url": "https://api-inference.huggingface.co/models/MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli",
|
42 |
+
"batch_size": 128,
|
43 |
+
},
|
44 |
+
}
|
45 |
+
|
46 |
+
EXAMPLES = [
|
47 |
+
("We're a nature-loving family with three kids, have some money left, and no plans "
|
48 |
+
"for next week-end. Should we visit Disneyland?"),
|
49 |
+
"Should I stop eating animals?",
|
50 |
+
"Bob needs a reliable and cheap car. Should he buy a Mercedes?",
|
51 |
+
('Gavin has an insurance policy that includes coverage for "General Damages," '
|
52 |
+
'which includes losses from "missed employment due to injuries that occur '
|
53 |
+
'under regular working conditions."\n\n'
|
54 |
+
'Gavin works as an A/C repair technician in a small town. One day, Gavin is '
|
55 |
+
'hired to repair an air conditioner located on the second story of a building. '
|
56 |
+
'Because Gavin is an experienced repairman, he knows that the safest way to '
|
57 |
+
'access the unit is with a sturdy ladder. While climbing the ladder, Gavin '
|
58 |
+
'loses his balance and falls, causing significant injury. Because of this, he '
|
59 |
+
'subsequently has to stop working for weeks. Gavin files a claim with his '
|
60 |
+
'insurance company for lost income.\n\n'
|
61 |
+
'Does Gavin\'s insurance policy cover his claim for lost income?'),
|
62 |
+
"How many arguments did you consider in your internal reasoning? (Brief answer, please.)",
|
63 |
+
"Did you consider any counterarguments in your internal reasoning?",
|
64 |
+
"From all the arguments you considered and assessed, which one is the most important?",
|
65 |
+
"Did you refute any arguments or reasons for lack of plausibility?"
|
66 |
+
]
|
67 |
+
|
68 |
+
TITLE = """<div align=left>
|
69 |
+
<h1>🪂 Benjamin Chatbot with Logikon <i>Guided Reasoning™️</i></h1>
|
70 |
+
</div>"""
|
71 |
+
|
72 |
+
TERMS_OF_SERVICE ="""<h2>Terms of Service</h2>
|
73 |
+
|
74 |
+
<p>This app is provided by Logikon AI for educational and research purposes only.
|
75 |
+
The app is powered by Logikon's <i>Guided Reasoning™️</i> technology, which is a novel approach to
|
76 |
+
reasoning with language models. The app is a work in progress and may not always provide accurate or reliable information.
|
77 |
+
By accepting these terms of service, you agree not to use the app:</p>
|
78 |
+
|
79 |
+
<ol>
|
80 |
+
<li>In any way that violates any applicable national, federal, state, local or international law or regulation;</li>
|
81 |
+
<li>For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;</li>
|
82 |
+
<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>
|
83 |
+
<li>To generate or disseminate verifiably false information and/or content with the purpose of harming others;</li>
|
84 |
+
<li>To generate or disseminate personal identifiable information that can be used to harm an individual;</li>
|
85 |
+
<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>
|
86 |
+
<li>To defame, disparage or otherwise harass others;</li>
|
87 |
+
<li>To impersonate or attempt to impersonate (e.g. deepfakes) others without their consent;</li>
|
88 |
+
<li>For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;</li>
|
89 |
+
<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>
|
90 |
+
<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>
|
91 |
+
<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>
|
92 |
+
<li>To provide medical advice and medical results interpretation;</li>
|
93 |
+
<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>
|
94 |
+
</ol>
|
95 |
+
|
96 |
+
<p>By using the feedback buttons, you agree that </p>
|
97 |
+
"""
|
98 |
+
|
99 |
+
CHATBOT_INSTRUCTIONS = (
|
100 |
+
"1️⃣ In the first turn, ask a question or present a decision problem.\n"
|
101 |
+
"2️⃣ In the following turns, ask the chatbot to explain its reasoning.\n\n"
|
102 |
+
"💡 Note that this demo bot is hard-wired to deliberate with Guided Reasoning™️ "
|
103 |
+
"in the first turn only.\n\n"
|
104 |
+
"🔐 Chat conversations and feedback are logged (anonymously).\n"
|
105 |
+
"Please don't share sensitive or identity revealing information.\n\n"
|
106 |
+
"🙏 Benjamin is powered by the free API inference services of 🤗.\n"
|
107 |
+
"In case you encounter issues due to rate limits... simply try again later.\n"
|
108 |
+
"[We're searching sponsors to run Benjamin on 🚀 dedicated infrastructure.]\n\n"
|
109 |
+
"💬 We'd love to hear your feedback!\n"
|
110 |
+
"Please use the 👋 Community tab above to reach out.\n"
|
111 |
+
)
|
112 |
+
|
113 |
+
|
114 |
+
logging.info(f"Reasoning guide expert model is {GUIDE_KWARGS['expert_model']}.")
|
115 |
+
|
116 |
+
|
117 |
+
def new_conversation_id():
|
118 |
+
conversation_id = str(uuid.uuid4())
|
119 |
+
print(f"New conversation with conversation ID: {conversation_id}")
|
120 |
+
return conversation_id
|
121 |
+
|
122 |
+
|
123 |
+
def setup_client_llm(
|
124 |
+
client_model_id,
|
125 |
+
client_inference_url,
|
126 |
+
client_inference_token,
|
127 |
+
client_backend,
|
128 |
+
client_temperature,
|
129 |
+
) -> LogitsModel | None:
|
130 |
+
try:
|
131 |
+
llm = create_logits_model(
|
132 |
+
model_id=client_model_id,
|
133 |
+
inference_server_url=client_inference_url,
|
134 |
+
api_key=client_inference_token,
|
135 |
+
llm_backend=client_backend,
|
136 |
+
max_tokens=CLIENT_MODEL_KWARGS["max_tokens"],
|
137 |
+
temperature=client_temperature,
|
138 |
+
)
|
139 |
+
except Exception as e:
|
140 |
+
logging.error(f"When setting up client llm: Error: {e}")
|
141 |
+
return False
|
142 |
+
return llm
|
143 |
+
|
144 |
+
|
145 |
+
async def log_like_dislike(conversation_id: gr.State, x: gr.LikeData):
|
146 |
+
print(conversation_id, x.index, x.liked)
|
147 |
+
# add your own feedback logging here
|
148 |
+
|
149 |
+
|
150 |
+
def add_message(history, message, conversation_id):
|
151 |
+
if len(history) == 0:
|
152 |
+
# reset conversation id
|
153 |
+
conversation_id = new_conversation_id()
|
154 |
+
|
155 |
+
print(f"add_message: {history} \n {message}")
|
156 |
+
if message["text"] is not None:
|
157 |
+
history.append((message["text"], None))
|
158 |
+
return history, gr.MultimodalTextbox(value=None, interactive=False), conversation_id
|
159 |
+
|
160 |
+
|
161 |
+
async def bot(
|
162 |
+
history,
|
163 |
+
client_model_id,
|
164 |
+
client_inference_url,
|
165 |
+
client_inference_token,
|
166 |
+
client_backend,
|
167 |
+
client_temperature,
|
168 |
+
conversation_id,
|
169 |
+
progress=gr.Progress(),
|
170 |
+
):
|
171 |
+
|
172 |
+
client_llm = setup_client_llm(
|
173 |
+
client_model_id,
|
174 |
+
client_inference_url,
|
175 |
+
client_inference_token,
|
176 |
+
client_backend,
|
177 |
+
client_temperature,
|
178 |
+
)
|
179 |
+
|
180 |
+
if not client_llm:
|
181 |
+
raise gr.Error(
|
182 |
+
"Failed to set up tourist LLM.",
|
183 |
+
duration=0
|
184 |
+
)
|
185 |
+
|
186 |
+
print(f"History (conversation: {conversation_id}): {history}")
|
187 |
+
history_langchain_format = history_to_langchain_format(history)
|
188 |
+
|
189 |
+
# use guide always and exclusively at first turn
|
190 |
+
if len(history_langchain_format) <= 1:
|
191 |
+
|
192 |
+
guide_kwargs = copy.deepcopy(GUIDE_KWARGS)
|
193 |
+
guide_kwargs["api_key"] = os.getenv("FW_TOKEN") # expert model api key
|
194 |
+
guide_kwargs["classifier_kwargs"]["api_key"] = os.getenv("HF_TOKEN") # classifier api key
|
195 |
+
|
196 |
+
guide_config = RecursiveBalancingGuideConfig(**guide_kwargs)
|
197 |
+
guide = RecursiveBalancingGuide(tourist_llm=client_llm, config=guide_config)
|
198 |
+
|
199 |
+
message = history[-1][0]
|
200 |
+
|
201 |
+
try:
|
202 |
+
artifacts = {}
|
203 |
+
progress_step = 0
|
204 |
+
async for otype, ovalue in guide.guide(message):
|
205 |
+
logging.getLogger(__name__).debug(f"Guide output: {otype.value} - {ovalue}")
|
206 |
+
if otype == "progress":
|
207 |
+
print(f"Progress: {ovalue}")
|
208 |
+
gr.Info(ovalue, duration=12)
|
209 |
+
progress((progress_step,4))
|
210 |
+
progress_step += 1
|
211 |
+
elif otype is not None:
|
212 |
+
artifacts[otype] = ovalue
|
213 |
+
else:
|
214 |
+
break
|
215 |
+
except asyncio.TimeoutError:
|
216 |
+
msg = "Guided reasoning process took too long. Please try again."
|
217 |
+
raise gr.Error(msg)
|
218 |
+
except Exception as e:
|
219 |
+
msg = f"Error during guided reasoning: {e}"
|
220 |
+
raise gr.Error(msg)
|
221 |
+
|
222 |
+
svg = postprocess_svg(artifacts.get("svg_argmap"))
|
223 |
+
protocol = artifacts.get("protocol", "I'm sorry, I failed to reason about the problem.")
|
224 |
+
response = artifacts.pop("response", "")
|
225 |
+
if not response:
|
226 |
+
response = "I'm sorry, I failed to draft a response (see logs for details)."
|
227 |
+
response = add_details(response, protocol, svg)
|
228 |
+
|
229 |
+
# otherwise, just chat
|
230 |
+
else:
|
231 |
+
try:
|
232 |
+
response = client_llm.invoke(history_langchain_format).content
|
233 |
+
except Exception as e:
|
234 |
+
msg = f"Error during chatbot inference: {e}"
|
235 |
+
gr.Error(msg)
|
236 |
+
raise ValueError(msg)
|
237 |
+
|
238 |
+
print(f"Response: {response}")
|
239 |
+
history[-1][1] = response
|
240 |
+
|
241 |
+
return history
|
242 |
+
|
243 |
+
|
244 |
+
|
245 |
+
with gr.Blocks() as demo:
|
246 |
+
|
247 |
+
# preamble
|
248 |
+
gr.Markdown(TITLE)
|
249 |
+
conversation_id = gr.State(str(uuid.uuid4()))
|
250 |
+
tos_approved = gr.State(False)
|
251 |
+
|
252 |
+
|
253 |
+
with gr.Tab(label="Chatbot", visible=False) as chatbot_tab:
|
254 |
+
|
255 |
+
# chatbot
|
256 |
+
chatbot = gr.Chatbot(
|
257 |
+
[],
|
258 |
+
elem_id="chatbot",
|
259 |
+
bubble_full_width=False,
|
260 |
+
placeholder=CHATBOT_INSTRUCTIONS,
|
261 |
+
)
|
262 |
+
chat_input = gr.MultimodalTextbox(interactive=True, file_types=["image"], placeholder="Enter message ...", show_label=False)
|
263 |
+
clear = gr.ClearButton([chat_input, chatbot])
|
264 |
+
gr.Examples([{"text": e, "files":[]} for e in EXAMPLES], chat_input)
|
265 |
+
|
266 |
+
# configs
|
267 |
+
with gr.Accordion("Client LLM Configuration", open=False):
|
268 |
+
gr.Markdown("Configure your client LLM that underpins this chatbot and is guided through the reasoning process.")
|
269 |
+
with gr.Row():
|
270 |
+
with gr.Column(2):
|
271 |
+
client_backend = gr.Dropdown(choices=[b.value for b in LLMBackends], value=LLMBackends.HFChat.value, label="LLM Inference Backend")
|
272 |
+
client_model_id = gr.Textbox(MODEL_ID, label="Model ID", max_lines=1)
|
273 |
+
client_inference_url = gr.Textbox(INFERENCE_SERVER_URL.format(model_id=MODEL_ID), label="Inference Server URL", max_lines=1)
|
274 |
+
client_inference_token = gr.Textbox("", label="Inference Token", max_lines=1, placeholder="Not required with HF Inference Api (default)", type="password")
|
275 |
+
with gr.Column(1):
|
276 |
+
client_temperature = gr.Slider(0, 1.0, value = CLIENT_MODEL_KWARGS["temperature"], label="Temperature")
|
277 |
+
|
278 |
+
# logic
|
279 |
+
chat_msg = chat_input.submit(add_message, [chatbot, chat_input, conversation_id], [chatbot, chat_input, conversation_id])
|
280 |
+
bot_msg = chat_msg.then(
|
281 |
+
bot,
|
282 |
+
[
|
283 |
+
chatbot,
|
284 |
+
client_model_id,
|
285 |
+
client_inference_url,
|
286 |
+
client_inference_token,
|
287 |
+
client_backend,
|
288 |
+
client_temperature,
|
289 |
+
conversation_id
|
290 |
+
],
|
291 |
+
chatbot,
|
292 |
+
api_name="bot_response"
|
293 |
+
)
|
294 |
+
bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])
|
295 |
+
|
296 |
+
chatbot.like(log_like_dislike, [conversation_id], None)
|
297 |
+
|
298 |
+
# we're resetting conversation id when drafting first response in bot()
|
299 |
+
# clear.click(new_conversation_id, outputs = [conversation_id])
|
300 |
+
|
301 |
+
with gr.Tab(label="Terms of Service") as tos_tab:
|
302 |
+
|
303 |
+
gr.HTML(TERMS_OF_SERVICE)
|
304 |
+
tos_checkbox = gr.Checkbox(label="I agree to the terms of service")
|
305 |
+
tos_checkbox.input(
|
306 |
+
lambda x: (x, gr.Checkbox(label="I agree to the terms of service", interactive=False), gr.Tab("Chatbot", visible=True)),
|
307 |
+
tos_checkbox,
|
308 |
+
[tos_approved, tos_checkbox, chatbot_tab]
|
309 |
+
)
|
310 |
+
|
311 |
+
if __name__ == "__main__":
|
312 |
+
demo.queue(default_concurrency_limit=8)
|
313 |
+
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,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_huggingface import ChatHuggingFace, HuggingFaceEndpoint
|
10 |
+
|
11 |
+
|
12 |
+
from langchain_openai import ChatOpenAI
|
13 |
+
|
14 |
+
|
15 |
+
class LLMBackends(Enum):
|
16 |
+
"""LLMBackends
|
17 |
+
|
18 |
+
Enum for LLMBackends.
|
19 |
+
"""
|
20 |
+
|
21 |
+
VLLM = "VLLM"
|
22 |
+
HFChat = "HFChat"
|
23 |
+
Fireworks = "Fireworks"
|
24 |
+
|
25 |
+
|
26 |
+
class LazyChatHuggingFace(ChatHuggingFace):
|
27 |
+
"""LazyChatHuggingFace"""
|
28 |
+
|
29 |
+
def __init__(self, **kwargs: Any):
|
30 |
+
BaseChatModel.__init__(self, **kwargs)
|
31 |
+
|
32 |
+
from transformers import AutoTokenizer
|
33 |
+
|
34 |
+
if not self.model_id:
|
35 |
+
self._resolve_model_id()
|
36 |
+
|
37 |
+
self.tokenizer = (
|
38 |
+
AutoTokenizer.from_pretrained(self.model_id)
|
39 |
+
if self.tokenizer is None
|
40 |
+
else self.tokenizer
|
41 |
+
)
|
42 |
+
|
43 |
+
class LazyHuggingFaceEndpoint(HuggingFaceEndpoint):
|
44 |
+
"""LazyHuggingFaceEndpoint"""
|
45 |
+
# We're using a lazy endpoint to avoid logging in with hf_token,
|
46 |
+
# which might in fact be a hf_oauth token that does only permit inference,
|
47 |
+
# not logging in.
|
48 |
+
|
49 |
+
@pydantic_v1.root_validator(pre=True)
|
50 |
+
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
|
51 |
+
return super().build_extra(values)
|
52 |
+
|
53 |
+
@pydantic_v1.root_validator()
|
54 |
+
def validate_environment(cls, values: Dict) -> Dict: # noqa: UP006, N805
|
55 |
+
"""Validate that package is installed and that the API token is valid."""
|
56 |
+
try:
|
57 |
+
from huggingface_hub import AsyncInferenceClient, InferenceClient
|
58 |
+
|
59 |
+
except ImportError:
|
60 |
+
msg = (
|
61 |
+
"Could not import huggingface_hub python package. "
|
62 |
+
"Please install it with `pip install huggingface_hub`."
|
63 |
+
)
|
64 |
+
raise ImportError(msg) # noqa: B904
|
65 |
+
|
66 |
+
huggingfacehub_api_token = get_from_dict_or_env(
|
67 |
+
values, "huggingfacehub_api_token", "HF_TOKEN"
|
68 |
+
)
|
69 |
+
|
70 |
+
values["client"] = InferenceClient(
|
71 |
+
model=values["model"],
|
72 |
+
timeout=values["timeout"],
|
73 |
+
token=huggingfacehub_api_token,
|
74 |
+
**values["server_kwargs"],
|
75 |
+
)
|
76 |
+
values["async_client"] = AsyncInferenceClient(
|
77 |
+
model=values["model"],
|
78 |
+
timeout=values["timeout"],
|
79 |
+
token=huggingfacehub_api_token,
|
80 |
+
**values["server_kwargs"],
|
81 |
+
)
|
82 |
+
|
83 |
+
return values
|
84 |
+
|
85 |
+
|
86 |
+
def get_chat_model_wrapper(
|
87 |
+
model_id: str,
|
88 |
+
inference_server_url: str,
|
89 |
+
token: str,
|
90 |
+
backend: str = "HFChat",
|
91 |
+
**model_init_kwargs
|
92 |
+
):
|
93 |
+
|
94 |
+
backend = LLMBackends(backend)
|
95 |
+
|
96 |
+
if backend == LLMBackends.HFChat:
|
97 |
+
# llm = LazyHuggingFaceEndpoint(
|
98 |
+
# endpoint_url=inference_server_url,
|
99 |
+
# task="text-generation",
|
100 |
+
# huggingfacehub_api_token=token,
|
101 |
+
# **model_init_kwargs,
|
102 |
+
# )
|
103 |
+
|
104 |
+
llm = LazyHuggingFaceEndpoint(
|
105 |
+
repo_id=model_id,
|
106 |
+
task="text-generation",
|
107 |
+
huggingfacehub_api_token=token,
|
108 |
+
**model_init_kwargs,
|
109 |
+
)
|
110 |
+
|
111 |
+
from transformers import AutoTokenizer
|
112 |
+
|
113 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, token=token)
|
114 |
+
chat_model = LazyChatHuggingFace(llm=llm, model_id=model_id, tokenizer=tokenizer)
|
115 |
+
|
116 |
+
elif backend in [LLMBackends.VLLM, LLMBackends.Fireworks]:
|
117 |
+
chat_model = ChatOpenAI(
|
118 |
+
model=model_id,
|
119 |
+
openai_api_base=inference_server_url, # type: ignore
|
120 |
+
openai_api_key=token, # type: ignore
|
121 |
+
**model_init_kwargs,
|
122 |
+
)
|
123 |
+
|
124 |
+
else:
|
125 |
+
raise ValueError(f"Backend {backend} not supported")
|
126 |
+
|
127 |
+
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 @@
|
|
|
|
|
1 |
+
logikon==0.2.0
|