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})