Multi-Modal Chatbot

This example demonstrates how to create a chatbot application using FastMLX with a Gradio interface.

 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
import argparse
import gradio as gr
import requests
import json

import asyncio

async def process_sse_stream(url, headers, data):
    response = requests.post(url, headers=headers, json=data, stream=True)
    if response.status_code != 200:
        raise gr.Error(f"Error: Received status code {response.status_code}")
    full_content = ""
    for line in response.iter_lines():
        if line:
            line = line.decode('utf-8')
            if line.startswith('data: '):
                event_data = line[6:]  # Remove 'data: ' prefix
                if event_data == '[DONE]':
                    break
                try:
                    chunk_data = json.loads(event_data)
                    content = chunk_data['choices'][0]['delta']['content']
                    yield str(content)
                except (json.JSONDecodeError, KeyError):
                    continue

async def chat(message, history, temperature, max_tokens):

    url = "http://localhost:8000/v1/chat/completions"
    headers = {"Content-Type": "application/json"}
    data = {
        "model": "mlx-community/Qwen2.5-1.5B-Instruct-4bit",
        "messages": [{"role": "user", "content": message['text']}],
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stream": True
    }

    if len(message['files']) > 0:
        data["model"] = "mlx-community/nanoLLaVA-1.5-8bit"
        data["image"] = message['files'][-1]["path"]

    response = requests.post(url, headers=headers, json=data, stream=True)
    if response.status_code != 200:
        raise gr.Error(f"Error: Received status code {response.status_code}")

    full_content = ""
    for line in response.iter_lines():
        if line:
            line = line.decode('utf-8')
            if line.startswith('data: '):
                event_data = line[6:]  # Remove 'data: ' prefix
                if event_data == '[DONE]':
                    break
                try:
                    chunk_data = json.loads(event_data)
                    content = chunk_data['choices'][0]['delta']['content']
                    full_content += content
                    yield full_content
                except (json.JSONDecodeError, KeyError):
                    continue

demo = gr.ChatInterface(
    fn=chat,
    title="FastMLX Chat UI",
    additional_inputs_accordion=gr.Accordion(
        label="⚙️ Parameters", open=False, render=False
    ),
    additional_inputs=[
        gr.Slider(
            minimum=0, maximum=1, step=0.1, value=0.1, label="Temperature", render=False
        ),
        gr.Slider(
            minimum=128,
            maximum=4096,
            step=1,
            value=200,
            label="Max new tokens",
            render=False
        ),
    ],
    multimodal=True,
)

demo.launch(inbrowser=True)