ragibhasan commited on
Commit
8b67916
Β·
verified Β·
1 Parent(s): 6115ea7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +155 -0
app.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from typing import Generator
4
+ from groq import Groq
5
+ from dotenv import load_dotenv
6
+ import yaml
7
+
8
+ # Load environment variables from .env file
9
+ load_dotenv()
10
+
11
+ def generate_chat_responses(chat_completion) -> Generator[str, None, None]:
12
+ """Yield chat response content from the Groq API response."""
13
+ for chunk in chat_completion:
14
+ if chunk.choices[0].delta.content:
15
+ yield chunk.choices[0].delta.content
16
+
17
+ def load_config():
18
+ """Load and validate the configuration from config.yaml"""
19
+ try:
20
+ with open("config.yaml", "r") as f:
21
+ config = yaml.safe_load(f)
22
+
23
+ if "models" not in config:
24
+ st.error("The 'models' section is missing from the config file.")
25
+ st.stop()
26
+
27
+ if "default_max_tokens" not in config:
28
+ st.warning("'default_max_tokens' is not specified in the config. Using 1024 as default.")
29
+ config["default_max_tokens"] = 1024
30
+
31
+ if "prompt_templates" not in config:
32
+ st.warning("No prompt templates found in the config.")
33
+ config["prompt_templates"] = {}
34
+
35
+ return config
36
+ except FileNotFoundError:
37
+ st.error("config.yaml file not found. Please ensure it exists in the same directory as this script.")
38
+ st.stop()
39
+ except yaml.YAMLError as e:
40
+ st.error(f"Error reading config.yaml: {e}")
41
+ st.stop()
42
+
43
+ # Set up the Streamlit page
44
+ st.set_page_config(page_icon="πŸ’¬", layout="wide", page_title="Llama 3.1 Chat App")
45
+
46
+ # Load configuration
47
+ config = load_config()
48
+
49
+ # Load Groq API key from environment variable
50
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
51
+ if not GROQ_API_KEY:
52
+ st.error("GROQ_API_KEY environment variable not found. Please set it in the .env file.")
53
+ st.stop()
54
+
55
+ client = Groq(api_key=GROQ_API_KEY)
56
+
57
+ # Initialize chat history
58
+ if "messages" not in st.session_state:
59
+ st.session_state.messages = []
60
+
61
+ # Define model details
62
+ model_option = "llama-3.1-70b-versatile"
63
+ if model_option not in config["models"]:
64
+ st.error(f"The model '{model_option}' is not defined in the config file.")
65
+ st.stop()
66
+
67
+ model_info = config["models"][model_option]
68
+
69
+ # Display model information
70
+ st.sidebar.header("Model Information")
71
+ st.sidebar.markdown(f"**Name:** {model_info.get('name', 'N/A')}")
72
+ st.sidebar.markdown(f"**Developer:** {model_info.get('developer', 'N/A')}")
73
+ st.sidebar.markdown(f"**Description:** {model_info.get('description', 'N/A')}")
74
+
75
+ max_tokens_range = model_info.get("tokens", 1024) # Default to 1024 if not specified
76
+
77
+ # Adjust max_tokens slider
78
+ max_tokens = st.sidebar.slider(
79
+ "Max Tokens:",
80
+ min_value=512,
81
+ max_value=max_tokens_range,
82
+ value=min(config["default_max_tokens"], max_tokens_range),
83
+ step=512,
84
+ help=f"Adjust the maximum number of tokens (words) for the model's response. Max for selected model: {max_tokens_range}"
85
+ )
86
+
87
+ # Display chat messages from history on app rerun
88
+ for message in st.session_state.messages:
89
+ avatar = 'πŸ€–' if message["role"] == "assistant" else 'πŸ‘¨β€πŸ’»'
90
+ with st.chat_message(message["role"], avatar=avatar):
91
+ st.markdown(message["content"])
92
+
93
+ if prompt := st.chat_input("Enter your prompt here..."):
94
+ st.session_state.messages.append({"role": "user", "content": prompt})
95
+
96
+ with st.chat_message("user", avatar='πŸ‘¨β€πŸ’»'):
97
+ st.markdown(prompt)
98
+
99
+ # Fetch response from Groq API
100
+ try:
101
+ chat_completion = client.chat.completions.create(
102
+ model=model_option,
103
+ messages=[
104
+ {
105
+ "role": m["role"],
106
+ "content": m["content"]
107
+ }
108
+ for m in st.session_state.messages
109
+ ],
110
+ max_tokens=max_tokens,
111
+ stream=True
112
+ )
113
+
114
+ # Use the generator function with st.write_stream
115
+ with st.chat_message("assistant", avatar="πŸ€–"):
116
+ chat_responses_generator = generate_chat_responses(chat_completion)
117
+ full_response = st.write_stream(chat_responses_generator)
118
+ except Exception as e:
119
+ st.error(f"Error: {e}", icon="🚨")
120
+ else:
121
+ # Append the full response to session_state.messages
122
+ if isinstance(full_response, str):
123
+ st.session_state.messages.append(
124
+ {"role": "assistant", "content": full_response})
125
+ else:
126
+ # Handle the case where full_response is not a string
127
+ combined_response = "\n".join(str(item) for item in full_response)
128
+ st.session_state.messages.append(
129
+ {"role": "assistant", "content": combined_response})
130
+
131
+ # Add a clear chat button
132
+ if st.sidebar.button("Clear Chat"):
133
+ st.session_state.messages = []
134
+
135
+ # Add a download chat history button
136
+ if st.sidebar.button("Download Chat History"):
137
+ chat_history = "\n".join([f"{m['role'].capitalize()}: {m['content']}" for m in st.session_state.messages])
138
+ st.download_button(
139
+ label="Download Chat History",
140
+ data=chat_history,
141
+ file_name="chat_history.txt",
142
+ mime="text/plain",
143
+ )
144
+
145
+ # Add a prompt templates section
146
+ st.sidebar.header("Prompt Templates")
147
+ template_options = list(config["prompt_templates"].keys())
148
+ if template_options:
149
+ selected_template = st.sidebar.selectbox("Choose a prompt template", options=template_options)
150
+ if st.sidebar.button("Load Template"):
151
+ prompt_template = config["prompt_templates"][selected_template]
152
+ st.session_state.messages.append({"role": "user", "content": prompt_template})
153
+ st.experimental_rerun()
154
+ else:
155
+ st.sidebar.info("No prompt templates available.")