File size: 4,139 Bytes
c6b7e90
1a86107
 
c6b7e90
e35ef75
 
 
2dadf18
 
 
 
 
1a86107
e35ef75
 
 
 
 
1a86107
727cfb3
1a86107
 
 
2dadf18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a86107
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e35ef75
92b4b79
e35ef75
727cfb3
 
b387a86
727cfb3
 
 
e35ef75
 
 
 
c6b7e90
e35ef75
 
 
 
c6b7e90
e35ef75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
727cfb3
e35ef75
 
 
 
 
 
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
import streamlit as st
import requests
import json
import os
import base64
from io import BytesIO

# TODO:
# Tool Use
# - Search
# - Data visualization

# Define function to encode image to base64
def encode_image(uploaded_file):
    bytes_data = uploaded_file.getvalue()
    base64_image = base64.b64encode(bytes_data).decode('utf-8')
    return f"data:image/{uploaded_file.type.split('/')[-1]};base64,{base64_image}"

# Define function to generate response from Groq API
def generate_response(messages, model, current_image=None):
    api_key = os.environ.get("GROQ_API_KEY")
    url = "https://api.groq.com/openai/v1/chat/completions"
    # Prepare messages for API
    api_messages = []
    image_added = False
    for i, msg in enumerate(messages):
        if msg["role"] == "user" and current_image and not image_added:
            # Only add the image to the first user message in this turn
            if isinstance(msg["content"], str):
                api_messages.append({
                    "role": "user",
                    "content": [
                        {"type": "text", "text": msg["content"]},
                        {"type": "image_url", "image_url": {"url": current_image}}
                    ]
                })
                image_added = True
            else:
                api_messages.append(msg)
        else:
            api_messages.append(msg)
    payload = json.dumps({
        "model": model,
        "messages": api_messages,
        "temperature": 0.1,
        "top_p": 1,
        "stream": True,
        "stop": None
    })
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    with requests.post(url, headers=headers, data=payload, stream=True) as response:
        for line in response.iter_lines():
            if line:
                if line.startswith(b'data: '):
                    data = line[len(b'data: '):]
                    if data == b'[DONE]':
                        break
                    try:
                        chunk = json.loads(data)
                        content = chunk.get('choices', [{}])[0].get('delta', {}).get('content')
                        if content:
                            yield content
                    except Exception:
                        continue

# Initialize session state for chat history if it doesn't exist
if 'messages' not in st.session_state:
    st.session_state.messages = []

st.title("Fast Inference Chat")

model = st.selectbox(
    "Select a model",
    ["meta-llama/llama-4-scout-17b-16e-instruct", "meta-llama/llama-4-maverick-17b-128e-instruct"],     
    index=0,
)

# Display chat history
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

# File uploader for images
uploaded_file = st.file_uploader("Upload an image (optional)", type=['png', 'jpg', 'jpeg'])

# Get user input
user_input = st.chat_input('Message to Assistant...', key='prompt_input')

if user_input:
    # Add user message to chat history (text only)
    st.session_state.messages.append({"role": "user", "content": user_input})
    
    # Display user message with image if present
    with st.chat_message("user"):
        st.markdown(user_input)
        if uploaded_file:
            st.image(uploaded_file)
    
    # Generate and display assistant response
    with st.chat_message("assistant"):
        response_placeholder = st.empty()
        full_response = ""
        
        # Prepare image for API call if present
        current_image = encode_image(uploaded_file) if uploaded_file else None
        
        # Stream the response
        with st.spinner("Generating response..."):
            for content in generate_response(st.session_state.messages, model, current_image):
                full_response += content
                response_placeholder.markdown(full_response + "▌")
            response_placeholder.markdown(full_response)
    
    # Add assistant response to chat history (text only)
    st.session_state.messages.append({"role": "assistant", "content": full_response})