File size: 7,210 Bytes
19e2c7f
 
 
 
 
 
 
 
 
 
 
 
 
 
0f7936b
19e2c7f
 
 
 
 
 
 
 
 
 
 
 
52a8794
19e2c7f
 
 
 
 
 
 
 
 
0b100ba
52a8794
19e2c7f
ce93394
19e2c7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce93394
 
 
19e2c7f
ce93394
19e2c7f
 
 
6a2a933
19e2c7f
ce93394
19e2c7f
ce93394
 
 
 
 
19e2c7f
 
 
ce93394
19e2c7f
 
 
 
1d0e9b8
19e2c7f
 
ce93394
19e2c7f
 
 
 
ce93394
19e2c7f
ce93394
 
19e2c7f
ce93394
19e2c7f
 
 
 
 
 
 
 
 
 
 
ce93394
19e2c7f
 
 
ce93394
19e2c7f
 
 
 
ce93394
19e2c7f
ce93394
19e2c7f
 
 
 
 
 
ce93394
 
19e2c7f
ce93394
19e2c7f
 
 
ce93394
19e2c7f
 
0b100ba
ce93394
19e2c7f
ce93394
19e2c7f
 
ce93394
19e2c7f
 
 
 
 
 
 
ce93394
 
 
19e2c7f
ce93394
19e2c7f
 
 
ce93394
19e2c7f
 
 
 
 
 
 
ce93394
 
 
19e2c7f
ce93394
19e2c7f
 
 
ce93394
19e2c7f
 
 
 
 
 
2e040aa
 
 
 
 
 
19e2c7f
 
 
ce93394
19e2c7f
 
ce93394
19e2c7f
 
 
 
 
ce93394
19e2c7f
 
 
 
 
 
 
c299f6a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import gradio as gr
import requests
import json
import os
import threading
import queue
import time

# Load all configuration from environment variables
TOGETHER_API_KEY = os.environ.get('TOGETHER_API_KEY', '')
TOGETHER_API_URL = os.environ.get('TOGETHER_API_URL', 'https://api.together.xyz/v1/chat/completions')

MODEL_A_NAME = os.environ.get('MODEL_A_NAME', '')
MODEL_B_NAME = os.environ.get('MODEL_B_NAME', '')
MODEL_C_NAME = os.environ.get('MODEL_C_NAME', '')

# Display names for the UI
MODEL_A_DISPLAY = os.environ.get('MODEL_A_DISPLAY', '')
MODEL_B_DISPLAY = os.environ.get('MODEL_B_DISPLAY', '')
MODEL_C_DISPLAY = os.environ.get('MODEL_C_DISPLAY', '')

# Headers for API calls
HEADERS = {
    "Authorization": f"Bearer {TOGETHER_API_KEY}",
    "Content-Type": "application/json"
}

SYSTEM_PROMPT = os.environ.get('SYSTEM_PROMPT', """You are an expert conversationalist who responds to the best of your ability. The assistant is Palmyra, created by Writer.""")

MODELS = {
    "Model A": MODEL_A_NAME,
    "Model B": MODEL_B_NAME,
    "Model C": MODEL_C_NAME
}

def stream_together_model(model_name, user_prompt, add_thinking_delay=False):
    if add_thinking_delay:
        yield "Thinking.."
        time.sleep(1)
        yield ""

    body = {
        "model": model_name,
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": user_prompt}
        ],
        "stream": True
    }
    try:
        with requests.post(TOGETHER_API_URL, headers=HEADERS, json=body, stream=True) as response:
            response.raise_for_status()
            for line in response.iter_lines():
                if line:
                    try:
                        data = json.loads(line.decode('utf-8').replace("data: ", ""))
                        content = data.get("choices", [{}])[0].get("delta", {}).get("content", "")
                        if content:
                            yield content
                    except:
                        continue
    except Exception as e:
        yield f"[Error: {str(e)}]"

def stream_model_c(user_prompt):
    url = "http://192.222.54.94:8000/v1/chat/completions"
    headers = {"Content-Type": "application/json"}
    body = {
        "model": "palmyra-x5-v2",
        "messages": [
            {"role": "user", "content": user_prompt}
        ],
        "temperature": 0.07
    }

    try:
        response = requests.post(url, headers=headers, json=body)
        response.raise_for_status()
        data = response.json()
        content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
        yield content
    except Exception as e:
        yield f"[Error: {str(e)}]"

custom_css = """... (unchanged CSS, keep same) ..."""

with gr.Blocks(css=custom_css, theme=gr.themes.Base()) as demo:
    gr.HTML("""
        <div class="container">
            <h1>Palmyra-x5</h1>
        </div>
    """)

    with gr.Row():
        chatbot_a = gr.Chatbot(label=MODEL_A_DISPLAY, height=500, bubble_full_width=False)
        chatbot_b = gr.Chatbot(label=MODEL_B_DISPLAY, height=500, bubble_full_width=False)
        chatbot_c = gr.Chatbot(label=MODEL_C_DISPLAY, height=500, bubble_full_width=False)

    with gr.Row():
        user_input = gr.Textbox(placeholder="Type your message...", show_label=False, scale=8)
        thinking_toggle = gr.Checkbox(label="Show Thinking Process", value=True, scale=2)
        submit_btn = gr.Button("Send", scale=1, variant="primary")

    gr.Examples(
        examples=[
            "What does Tencent do?",
            "Explain quantum computing",
            "Write a haiku about AI",
            "Compare Python vs JavaScript",
            "Tips for better sleep"
        ],
        inputs=user_input,
        label="Try these examples:"
    )

    def stream_all_models(message, enable_thinking, hist_a, hist_b, hist_c):
        if not message.strip():
            return hist_a, hist_b, hist_c, ""

        hist_a = hist_a + [[message, ""]]
        hist_b = hist_b + [[message, ""]]
        hist_c = hist_c + [[message, ""]]
        yield hist_a, hist_b, hist_c, ""

        q1, q2, q3 = queue.Queue(), queue.Queue(), queue.Queue()

        def fetch_stream(q, model, add_delay=False):
            try:
                for chunk in stream_together_model(model, message, add_delay):
                    q.put(chunk)
            finally:
                q.put(None)

        def fetch_stream_c(q, message):
            try:
                for chunk in stream_model_c(message):
                    q.put(chunk)
            finally:
                q.put(None)

        threading.Thread(target=fetch_stream, args=(q1, MODELS["Model A"], True)).start()
        threading.Thread(target=fetch_stream, args=(q2, MODELS["Model B"], True)).start()
        threading.Thread(target=fetch_stream, args=(q3, MODELS["Model C"], True)).start()

        done_a = done_b = done_c = False

        while not (done_a and done_b and done_c):
            updated = False

            if not done_a:
                try:
                    chunk = q1.get(timeout=0.05)
                    if chunk is None:
                        done_a = True
                    else:
                        if chunk == "":
                            hist_a[-1][1] = ""
                        elif chunk.startswith("\ud83e\udd14"):
                            hist_a[-1][1] = chunk
                        else:
                            hist_a[-1][1] += chunk
                        updated = True
                except:
                    pass

            if not done_b:
                try:
                    chunk = q2.get(timeout=0.05)
                    if chunk is None:
                        done_b = True
                    else:
                        if chunk == "":
                            hist_b[-1][1] = ""
                        elif chunk.startswith("\ud83e\udd14"):
                            hist_b[-1][1] = chunk
                        else:
                            hist_b[-1][1] += chunk
                        updated = True
                except:
                    pass

            if not done_c:
                try:
                    chunk = q3.get(timeout=0.05)
                    if chunk is None:
                        done_c = True
                    else:
                        if chunk == "":
                            hist_c[-1][1] = ""
                        elif chunk.startswith("\ud83e\udd14"):
                            hist_c[-1][1] = chunk
                        else:
                            hist_c[-1][1] += chunk
                        updated = True
                except:
                    pass

            if updated:
                yield hist_a, hist_b, hist_c, ""

    submit_btn.click(
        stream_all_models,
        [user_input, thinking_toggle, chatbot_a, chatbot_b, chatbot_c],
        [chatbot_a, chatbot_b, chatbot_c, user_input]
    )

    user_input.submit(
        stream_all_models,
        [user_input, thinking_toggle, chatbot_a, chatbot_b, chatbot_c],
        [chatbot_a, chatbot_b, chatbot_c, user_input]
    )

if __name__ == "__main__":
    demo.launch()