EduuGomes commited on
Commit
e257575
·
verified ·
1 Parent(s): 022c4a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -167
app.py CHANGED
@@ -1,177 +1,168 @@
 
1
  import gradio as gr
 
2
  from openai import OpenAI
3
- import os
4
- from datetime import datetime
5
-
6
- # App title and description
7
- APP_TITLE = "NO GPU, Multi LLMs Uses"
8
- APP_DESCRIPTION = "Access and chat with multiple language models without requiring a GPU"
9
-
10
- # Load environment variables
11
- ACCESS_TOKEN = os.getenv("HF_TOKEN")
12
- client = OpenAI(
13
- base_url="https://api-inference.huggingface.co/v1/",
14
- api_key=ACCESS_TOKEN,
15
- )
16
-
17
- # Model categories for better organization
18
- MODEL_CATEGORIES = {
19
- "Qwen": [
20
- "Qwen/Qwen2.5-72B-Instruct",
21
- "Qwen/Qwen2.5-3B-Instruct",
22
- "Qwen/Qwen2.5-0.5B-Instruct",
23
- "Qwen/Qwen2.5-Coder-32B-Instruct",
24
- ],
25
- "Meta LLaMa": [
26
- "meta-llama/Llama-3.3-70B-Instruct",
27
- "meta-llama/Llama-3.1-70B-Instruct",
28
- "meta-llama/Llama-3.0-70B-Instruct",
29
- "meta-llama/Llama-3.2-3B-Instruct",
30
- "meta-llama/Llama-3.2-1B-Instruct",
31
- "meta-llama/Llama-3.1-8B-Instruct",
32
- ],
33
- "Mistral": [
34
- "mistralai/Mistral-Nemo-Instruct-2407",
35
- "mistralai/Mixtral-8x7B-Instruct-v0.1",
36
- "mistralai/Mistral-7B-Instruct-v0.3",
37
- "mistralai/Mistral-7B-Instruct-v0.2",
38
- ],
39
- "Microsoft Phi": [
40
- "microsoft/Phi-3.5-mini-instruct",
41
- "microsoft/Phi-3-mini-128k-instruct",
42
- "microsoft/Phi-3-mini-4k-instruct",
43
- ],
44
- "Other Models": [
45
-
46
- "NousResearch/Hermes-3-Llama-3.1-8B",
47
- "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO",
48
- "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
49
- "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B",
50
- "HuggingFaceH4/zephyr-7b-beta",
51
- "HuggingFaceTB/SmolLM2-360M-Instruct",
52
- "tiiuae/falcon-7b-instruct",
53
- "01-ai/Yi-1.5-34B-Chat",
54
- ]
55
- }
56
-
57
- # Flatten the model list
58
- ALL_MODELS = [m for models in MODEL_CATEGORIES.values() for m in models]
59
-
60
- def get_model_info(model_name):
61
- parts = model_name.split('/')
62
- if len(parts) != 2:
63
- return f"**Model:** {model_name}\n**Format:** Unknown"
64
- org, model = parts
65
- import re
66
- size_match = re.search(r'(\d+\.?\d*)B', model)
67
- size = size_match.group(1) + "B" if size_match else "Unknown"
68
- return f"**Organization:** {org}\n**Model:** {model}\n**Size:** {size}"
69
-
70
- def respond(
71
- message,
72
- history,
73
- system_message,
74
- max_tokens,
75
- temperature,
76
- top_p,
77
- frequency_penalty,
78
- seed,
79
- selected_model
80
- ):
81
- # Prepare messages
82
- if seed == -1:
83
- seed = None
84
- messages = [{"role": "system", "content": system_message}]
85
- for user_msg, assistant_msg in history:
86
- if user_msg:
87
- messages.append({"role": "user", "content": user_msg})
88
- if assistant_msg:
89
- messages.append({"role": "assistant", "content": assistant_msg})
90
- messages.append({"role": "user", "content": message})
91
-
92
- model_to_use = selected_model or ALL_MODELS[0]
93
-
94
- new_history = list(history) + [(message, "")]
95
- current_response = ""
96
  try:
97
- for chunk in client.chat.completions.create(
98
- model=model_to_use,
99
- max_tokens=max_tokens,
100
- stream=True,
101
- temperature=temperature,
102
- top_p=top_p,
103
- frequency_penalty=frequency_penalty,
104
- seed=seed,
105
- messages=messages,
106
- ):
107
- delta = chunk.choices[0].delta.content
108
- if delta:
109
- current_response += delta
110
- new_history[-1] = (message, current_response)
111
- yield new_history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  except Exception as e:
113
- err = f"Error: {e}"
114
- new_history[-1] = (message, err)
115
- yield new_history
116
-
117
- with gr.Blocks(title=APP_TITLE, theme=gr.themes.Soft()) as demo:
118
- gr.Markdown(f"## {APP_TITLE}\n\n{APP_DESCRIPTION}")
119
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  with gr.Row():
121
- with gr.Column(scale=2):
122
- # Model selection via Dropdown
123
- selected_model = gr.Dropdown(
124
- choices=ALL_MODELS,
125
- value=ALL_MODELS[0],
126
- label="Select Model"
127
- )
128
- model_info = gr.Markdown(get_model_info(ALL_MODELS[0]))
129
-
130
- def update_info(model_name):
131
- return get_model_info(model_name)
132
- selected_model.change(
133
- fn=update_info,
134
- inputs=[selected_model],
135
- outputs=[model_info]
136
- )
137
-
138
- # Conversation settings
139
- system_message = gr.Textbox(
140
- value="You are a helpful assistant.",
141
- label="System Prompt",
142
- lines=2
143
- )
144
-
145
- max_tokens = gr.Slider(1, 4096, value=512, label="Max New Tokens")
146
- temperature = gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature")
147
- top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-P")
148
- freq_penalty = gr.Slider(-2.0, 2.0, value=0.0, step=0.1, label="Frequency Penalty")
149
- seed = gr.Slider(-1, 65535, value=-1, step=1, label="Seed (-1 random)")
150
-
151
- with gr.Column(scale=3):
152
  chatbot = gr.Chatbot()
153
- msg = gr.Textbox(placeholder="Type your message here...", show_label=False)
154
- send_btn = gr.Button("Send")
155
-
156
- send_btn.click(
157
- fn=respond,
158
- inputs=[
159
- msg, chatbot, system_message,
160
- max_tokens, temperature, top_p,
161
- freq_penalty, seed, selected_model
162
- ],
163
- outputs=[chatbot],
164
- queue=True
 
 
 
 
 
 
 
165
  )
166
- msg.submit(
167
- fn=respond,
168
- inputs=[
169
- msg, chatbot, system_message,
170
- max_tokens, temperature, top_p,
171
- freq_penalty, seed, selected_model
172
- ],
173
- outputs=[chatbot],
174
- queue=True
 
 
 
 
 
 
 
 
 
 
 
175
  )
176
 
 
177
  demo.launch()
 
1
+ import os
2
  import gradio as gr
3
+
4
  from openai import OpenAI
5
+
6
+ from optillm.cot_reflection import cot_reflection
7
+ from optillm.rto import round_trip_optimization
8
+ from optillm.z3_solver import Z3SymPySolverSystem
9
+ from optillm.self_consistency import advanced_self_consistency_approach
10
+ from optillm.plansearch import plansearch
11
+ from optillm.leap import leap
12
+ from optillm.reread import re2_approach
13
+
14
+
15
+ API_KEY = os.environ.get("OPENROUTER_API_KEY")
16
+
17
+ def compare_responses(message, model1, approach1, model2, approach2, system_message, max_tokens, temperature, top_p):
18
+ response1 = respond(message, [], model1, approach1, system_message, max_tokens, temperature, top_p)
19
+ response2 = respond(message, [], model2, approach2, system_message, max_tokens, temperature, top_p)
20
+ return response1, response2
21
+
22
+ def parse_conversation(messages):
23
+ system_prompt = ""
24
+ conversation = []
25
+
26
+ for message in messages:
27
+ role = message['role']
28
+ content = message['content']
29
+
30
+ if role == 'system':
31
+ system_prompt = content
32
+ elif role in ['user', 'assistant']:
33
+ conversation.append(f"{role.capitalize()}: {content}")
34
+
35
+ initial_query = "\n".join(conversation)
36
+ return system_prompt, initial_query
37
+
38
+ def respond(message, history, model, approach, system_message, max_tokens, temperature, top_p):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  try:
40
+ client = OpenAI(api_key=API_KEY, base_url="https://openrouter.ai/api/v1")
41
+ messages = [{"role": "system", "content": system_message}]
42
+
43
+ for val in history:
44
+ if val[0]:
45
+ messages.append({"role": "user", "content": val[0]})
46
+ if val[1]:
47
+ messages.append({"role": "assistant", "content": val[1]})
48
+
49
+ messages.append({"role": "user", "content": message})
50
+
51
+ if approach == "none":
52
+ response = client.chat.completions.create(
53
+ extra_headers={
54
+ "HTTP-Referer": "https://github.com/codelion/optillm",
55
+ "X-Title": "optillm"
56
+ },
57
+ model=model,
58
+ messages=messages,
59
+ max_tokens=max_tokens,
60
+ temperature=temperature,
61
+ top_p=top_p,
62
+ )
63
+ return response.choices[0].message.content
64
+ else:
65
+ system_prompt, initial_query = parse_conversation(messages)
66
+
67
+ if approach == 'rto':
68
+ final_response, _ = round_trip_optimization(system_prompt, initial_query, client, model)
69
+ elif approach == 'z3':
70
+ z3_solver = Z3SymPySolverSystem(system_prompt, client, model)
71
+ final_response, _ = z3_solver.process_query(initial_query)
72
+ elif approach == "self_consistency":
73
+ final_response, _ = advanced_self_consistency_approach(system_prompt, initial_query, client, model)
74
+ elif approach == "cot_reflection":
75
+ final_response, _ = cot_reflection(system_prompt, initial_query, client, model)
76
+ elif approach == 'plansearch':
77
+ response, _ = plansearch(system_prompt, initial_query, client, model)
78
+ final_response = response[0]
79
+ elif approach == 'leap':
80
+ final_response, _ = leap(system_prompt, initial_query, client, model)
81
+ elif approach == 're2':
82
+ final_response, _ = re2_approach(system_prompt, initial_query, client, model)
83
+
84
+ return final_response
85
+
86
  except Exception as e:
87
+ error_message = f"Error in respond function: {str(e)}\nType: {type(e).__name__}"
88
+ print(error_message)
89
+
90
+ def create_model_dropdown():
91
+ return gr.Dropdown(
92
+ [ "meta-llama/llama-3.1-8b-instruct:free", "nousresearch/hermes-3-llama-3.1-405b:free","meta-llama/llama-3.2-1b-instruct:free",
93
+ "mistralai/mistral-7b-instruct:free","mistralai/pixtral-12b:free","meta-llama/llama-3.1-70b-instruct:free",
94
+ "qwen/qwen-2-7b-instruct:free", "qwen/qwen-2-vl-7b-instruct:free", "google/gemma-2-9b-it:free", "liquid/lfm-40b:free", "meta-llama/llama-3.1-405b-instruct:free",
95
+ "openchat/openchat-7b:free", "meta-llama/llama-3.2-90b-vision-instruct:free", "meta-llama/llama-3.2-11b-vision-instruct:free",
96
+ "meta-llama/llama-3-8b-instruct:free", "meta-llama/llama-3.2-3b-instruct:free", "microsoft/phi-3-medium-128k-instruct:free",
97
+ "microsoft/phi-3-mini-128k-instruct:free", "huggingfaceh4/zephyr-7b-beta:free"],
98
+ value="meta-llama/llama-3.2-1b-instruct:free", label="Model"
99
+ )
100
+
101
+ def create_approach_dropdown():
102
+ return gr.Dropdown(
103
+ ["none", "leap", "plansearch", "cot_reflection", "rto", "self_consistency", "z3", "re2"],
104
+ value="none", label="Approach"
105
+ )
106
+
107
+ html = """<iframe src="https://ghbtns.com/github-btn.html?user=codelion&repo=optillm&type=star&count=true&size=large" frameborder="0" scrolling="0" width="170" height="30" title="GitHub"></iframe>
108
+ """
109
+
110
+ with gr.Blocks() as demo:
111
+ gr.Markdown("# optillm - Optimizing LLM Inference")
112
+ gr.HTML(html)
113
+
114
  with gr.Row():
115
+ system_message = gr.Textbox(value="", label="System message")
116
+ max_tokens = gr.Slider(minimum=1, maximum=4096, value=1024, step=1, label="Max new tokens")
117
+ temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
118
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
119
+
120
+ with gr.Tabs():
121
+ with gr.TabItem("Chat"):
122
+ model = create_model_dropdown()
123
+ approach = create_approach_dropdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  chatbot = gr.Chatbot()
125
+ msg = gr.Textbox()
126
+ with gr.Row():
127
+ submit = gr.Button("Submit")
128
+ clear = gr.Button("Clear")
129
+
130
+ def user(user_message, history):
131
+ return "", history + [[user_message, None]]
132
+
133
+ def bot(history, model, approach, system_message, max_tokens, temperature, top_p):
134
+ user_message = history[-1][0]
135
+ bot_message = respond(user_message, history[:-1], model, approach, system_message, max_tokens, temperature, top_p)
136
+ history[-1][1] = bot_message
137
+ return history
138
+
139
+ msg.submit(user, [msg, chatbot], [msg, chatbot]).then(
140
+ bot, [chatbot, model, approach, system_message, max_tokens, temperature, top_p], chatbot
141
+ )
142
+ submit.click(user, [msg, chatbot], [msg, chatbot]).then(
143
+ bot, [chatbot, model, approach, system_message, max_tokens, temperature, top_p], chatbot
144
  )
145
+ clear.click(lambda: None, None, chatbot, queue=False)
146
+
147
+ with gr.TabItem("Compare"):
148
+ with gr.Row():
149
+ model1 = create_model_dropdown()
150
+ approach1 = create_approach_dropdown()
151
+ model2 = create_model_dropdown()
152
+ approach2 = create_approach_dropdown()
153
+
154
+ compare_input = gr.Textbox(label="Enter your message for comparison")
155
+ compare_button = gr.Button("Compare")
156
+
157
+ with gr.Row():
158
+ output1 = gr.Textbox(label="Response 1")
159
+ output2 = gr.Textbox(label="Response 2")
160
+
161
+ compare_button.click(
162
+ compare_responses,
163
+ inputs=[compare_input, model1, approach1, model2, approach2, system_message, max_tokens, temperature, top_p],
164
+ outputs=[output1, output2]
165
  )
166
 
167
+ if __name__ == "__main__":
168
  demo.launch()