File size: 1,950 Bytes
29b5d42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py

import streamlit as st
from openai import OpenAI
import os

# Set page configuration
st.set_page_config(
    page_title="Chat with Groq",
    page_icon="⚡️",
    layout="centered"
)

# Initialize the Groq client
# The API key is securely fetched from Hugging Face's secrets
client = OpenAI(
    api_key=os.environ.get("GROQ_API_KEY"),
    base_url="https://api.groq.com/openai/v1",
)

# App title and caption
st.title("⚡️ Chat with Groq")
st.caption("Powered by Streamlit, Hugging Face, and the lightning-fast Groq API")

# Initialize chat history in session state
if "messages" not in st.session_state:
    st.session_state.messages = []

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

# Handle user input
if prompt := st.chat_input("What's on your mind?"):
    # Add user message to history and display it
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    # Generate and display assistant's response
    with st.chat_message("assistant"):
        message_placeholder = st.empty()
        
        try:
            # Create the API call
            response = client.chat.completions.create(
                model="llama-3.1-8b-instant",  # Use a current, supported model
                messages=[
                    {"role": m["role"], "content": m["content"]}
                    for m in st.session_state.messages
                ],
            )
            
            full_response = response.choices[0].message.content
            message_placeholder.markdown(full_response)
            
            # Add assistant's response to history
            st.session_state.messages.append({"role": "assistant", "content": full_response})
            
        except Exception as e:
            st.error(f"An error occurred: {e}")