Spaces:
Runtime error
Runtime error
added url button to steam
Browse files- Home.py +81 -34
- module/__custom__.py +9 -0
Home.py
CHANGED
|
@@ -1,10 +1,13 @@
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
import os
|
| 3 |
import random
|
| 4 |
import time
|
| 5 |
from module.__custom__ import *
|
| 6 |
from streamlit_extras.switch_page_button import switch_page
|
| 7 |
|
|
|
|
|
|
|
| 8 |
|
| 9 |
# Openai API Key
|
| 10 |
import openai
|
|
@@ -26,6 +29,7 @@ def read_api_key_from_secrets(file_path='secrets.json'):
|
|
| 26 |
|
| 27 |
# Example usage
|
| 28 |
try:
|
|
|
|
| 29 |
openai.api_key = os.environ['key']
|
| 30 |
os.environ['OPENAI_API_KEY'] = os.environ['key']
|
| 31 |
print(f"OpenAI API Key Found")
|
|
@@ -55,13 +59,12 @@ db_plot = Chroma(
|
|
| 55 |
embedding_function=embedding
|
| 56 |
)
|
| 57 |
|
| 58 |
-
|
| 59 |
with st.sidebar: is_plot = st.toggle('Enable Plot')
|
| 60 |
db_selected = db_cos
|
| 61 |
if is_plot: db_selected = db_plot
|
| 62 |
|
| 63 |
|
| 64 |
-
|
| 65 |
from langchain.agents.agent_toolkits.conversational_retrieval.tool import (
|
| 66 |
create_retriever_tool,
|
| 67 |
)
|
|
@@ -71,8 +74,30 @@ retriever_tool = create_retriever_tool(
|
|
| 71 |
"document-retriever",
|
| 72 |
"Query a retriever to get information about the video game dataset.",
|
| 73 |
)
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
|
|
|
| 76 |
from langchain.utils.openai_functions import convert_pydantic_to_openai_function
|
| 77 |
from pydantic import BaseModel, Field
|
| 78 |
|
|
@@ -91,8 +116,8 @@ class Response(BaseModel):
|
|
| 91 |
description="A list of the names of the games found for the user. Only include the game name if it was given as a result to the user's query."
|
| 92 |
)
|
| 93 |
|
| 94 |
-
import json
|
| 95 |
|
|
|
|
| 96 |
from langchain.schema.agent import AgentActionMessageLog, AgentFinish
|
| 97 |
def parse(output):
|
| 98 |
# If no function was invoked, return to user
|
|
@@ -149,16 +174,19 @@ agent = (
|
|
| 149 |
agent_executor = AgentExecutor(tools=[retriever_tool], agent=agent, verbose=True)
|
| 150 |
|
| 151 |
post_prompt = """
|
| 152 |
-
Respond with a respectable and friendy tone.
|
| 153 |
-
|
| 154 |
-
Do not give me any information that is not included in the document.
|
| 155 |
-
If you
|
| 156 |
-
If you need more context from the user, ask them to provide more context in the next query. Do not include games that contain the queried game in the title.
|
| 157 |
-
If a user asks for a type of game, use that type to find a game that mentions the type.
|
| 158 |
-
If a user asks for a specific number of games, and you cannot provide that, answer with what games you found and explain why you could not find others.
|
| 159 |
"""
|
|
|
|
|
|
|
| 160 |
|
| 161 |
-
st.header("🕹️ GameInsightify
|
|
|
|
|
|
|
| 162 |
|
| 163 |
# Description for users
|
| 164 |
st.markdown("""
|
|
@@ -175,7 +203,7 @@ if 'gamenames' not in st.session_state:
|
|
| 175 |
# Slider on range and button to clear chat history
|
| 176 |
col1, col2= st.columns([8,2])
|
| 177 |
with col1:
|
| 178 |
-
|
| 179 |
with col2:
|
| 180 |
if st.button("Clear chat"):
|
| 181 |
st.session_state.messages = []
|
|
@@ -200,28 +228,39 @@ if prompt := st.chat_input("Need a game recommendation?"):
|
|
| 200 |
|
| 201 |
with st.chat_message("assistant"): # Display assistant response in chat message container
|
| 202 |
message_placeholder = st.empty()
|
|
|
|
|
|
|
| 203 |
|
| 204 |
# docs = db.max_marginal_relevance_search(prompt,k=query_num, fetch_k=10) # Sending query to db
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
) # retrieve response from chatgpt
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
|
|
|
|
|
|
| 212 |
|
| 213 |
-
|
| 214 |
-
top_games = []
|
| 215 |
-
assistant_response = ""
|
| 216 |
-
# for idx, doc in enumerate(docs['name']):
|
| 217 |
-
# gamename = doc
|
| 218 |
-
# top_games.append(gamename)
|
| 219 |
-
# assistant_response += f"{idx+1}. {gamename}\n"
|
| 220 |
print(docs)
|
| 221 |
-
|
| 222 |
-
assistant_response += docs["answer"]
|
| 223 |
-
except:
|
| 224 |
-
assistant_response += docs["output"]
|
| 225 |
# separating response into chunk of words
|
| 226 |
chunks = []
|
| 227 |
for line in assistant_response.splitlines():
|
|
@@ -238,14 +277,22 @@ if prompt := st.chat_input("Need a game recommendation?"):
|
|
| 238 |
|
| 239 |
# Add assistant response to chat history
|
| 240 |
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
| 241 |
-
if is_plot: st.session_state.gamenames.append(
|
| 242 |
-
|
| 243 |
-
col1, col2, col3= st.columns([4,
|
| 244 |
with col2:
|
| 245 |
if is_plot and db_selected==db_plot:
|
| 246 |
if st.button("Plot Games"): # button in center column
|
| 247 |
switch_page('Overall')
|
| 248 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
# Styling on Tabs
|
| 251 |
css = '''
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import pandas as pd
|
| 3 |
import os
|
| 4 |
import random
|
| 5 |
import time
|
| 6 |
from module.__custom__ import *
|
| 7 |
from streamlit_extras.switch_page_button import switch_page
|
| 8 |
|
| 9 |
+
df = pd.read_csv('./data/cosine.csv')
|
| 10 |
+
|
| 11 |
|
| 12 |
# Openai API Key
|
| 13 |
import openai
|
|
|
|
| 29 |
|
| 30 |
# Example usage
|
| 31 |
try:
|
| 32 |
+
|
| 33 |
openai.api_key = os.environ['key']
|
| 34 |
os.environ['OPENAI_API_KEY'] = os.environ['key']
|
| 35 |
print(f"OpenAI API Key Found")
|
|
|
|
| 59 |
embedding_function=embedding
|
| 60 |
)
|
| 61 |
|
|
|
|
| 62 |
with st.sidebar: is_plot = st.toggle('Enable Plot')
|
| 63 |
db_selected = db_cos
|
| 64 |
if is_plot: db_selected = db_plot
|
| 65 |
|
| 66 |
|
| 67 |
+
##### Conversational Retrieval #####
|
| 68 |
from langchain.agents.agent_toolkits.conversational_retrieval.tool import (
|
| 69 |
create_retriever_tool,
|
| 70 |
)
|
|
|
|
| 74 |
"document-retriever",
|
| 75 |
"Query a retriever to get information about the video game dataset.",
|
| 76 |
)
|
| 77 |
+
##################################
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
##### Retriever - Self Query #####
|
| 81 |
+
metadata_field_info = [
|
| 82 |
+
AttributeInfo(
|
| 83 |
+
name="name",
|
| 84 |
+
description="The name of the video game on steam",
|
| 85 |
+
type="string",
|
| 86 |
+
)
|
| 87 |
+
]
|
| 88 |
+
document_content_description = "Brief summary of a video game on Steam"
|
| 89 |
+
|
| 90 |
+
retriever_plot = SelfQueryRetriever.from_llm(
|
| 91 |
+
llm,
|
| 92 |
+
db_selected,
|
| 93 |
+
document_content_description,
|
| 94 |
+
metadata_field_info,
|
| 95 |
+
enable_limit=True,
|
| 96 |
+
)
|
| 97 |
+
##################################
|
| 98 |
+
|
| 99 |
|
| 100 |
+
from typing import List
|
| 101 |
from langchain.utils.openai_functions import convert_pydantic_to_openai_function
|
| 102 |
from pydantic import BaseModel, Field
|
| 103 |
|
|
|
|
| 116 |
description="A list of the names of the games found for the user. Only include the game name if it was given as a result to the user's query."
|
| 117 |
)
|
| 118 |
|
|
|
|
| 119 |
|
| 120 |
+
import json
|
| 121 |
from langchain.schema.agent import AgentActionMessageLog, AgentFinish
|
| 122 |
def parse(output):
|
| 123 |
# If no function was invoked, return to user
|
|
|
|
| 174 |
agent_executor = AgentExecutor(tools=[retriever_tool], agent=agent, verbose=True)
|
| 175 |
|
| 176 |
post_prompt = """
|
| 177 |
+
1. Respond with a respectable and friendy tone.
|
| 178 |
+
2. You should give the best possible answer based on user's query.
|
| 179 |
+
3. Do not give me any information that is not included in the document.
|
| 180 |
+
4. If you are able to, provide the links to the steam site for the games answer.
|
| 181 |
+
5. If you need more context from the user, ask them to provide more context in the next query. Do not include games that contain the queried game in the title.
|
| 182 |
+
6. If a user asks for a type of game, use that type to find a game that mentions the type.
|
|
|
|
| 183 |
"""
|
| 184 |
+
# If you do not have an answer, your response should be kind and apologetic, as to why you do not have an answer.
|
| 185 |
+
# If a user asks for a specific number of games, and you cannot provide that, answer with what games you found and explain why you could not find others.
|
| 186 |
|
| 187 |
+
st.header("🕹️ GameInsightify")
|
| 188 |
+
st.title("Your Personal :green[Game Recommender]")
|
| 189 |
+
st.image('./data/img/demoGIF.gif')
|
| 190 |
|
| 191 |
# Description for users
|
| 192 |
st.markdown("""
|
|
|
|
| 203 |
# Slider on range and button to clear chat history
|
| 204 |
col1, col2= st.columns([8,2])
|
| 205 |
with col1:
|
| 206 |
+
pass
|
| 207 |
with col2:
|
| 208 |
if st.button("Clear chat"):
|
| 209 |
st.session_state.messages = []
|
|
|
|
| 228 |
|
| 229 |
with st.chat_message("assistant"): # Display assistant response in chat message container
|
| 230 |
message_placeholder = st.empty()
|
| 231 |
+
assistant_response = ""
|
| 232 |
+
full_response = ""
|
| 233 |
|
| 234 |
# docs = db.max_marginal_relevance_search(prompt,k=query_num, fetch_k=10) # Sending query to db
|
| 235 |
+
if is_plot:
|
| 236 |
+
docs = retriever_plot.invoke(prompt)
|
| 237 |
+
full_response = random.choice( # 1st sentence of response
|
| 238 |
+
["I recommend the following games:\n",
|
| 239 |
+
f"Hi, human! These are the {len(docs)} best games:\n",
|
| 240 |
+
f"I bet you will love these {len(docs)} games:\n",]
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
# formatting response from db
|
| 244 |
+
top_games = []
|
| 245 |
+
for idx, doc in enumerate(docs):
|
| 246 |
+
gamename = doc.metadata['name']
|
| 247 |
+
top_games.append(gamename)
|
| 248 |
+
assistant_response += f"{idx+1}. {gamename}\n"
|
| 249 |
+
|
| 250 |
+
else:
|
| 251 |
+
docs = agent_executor.invoke(
|
| 252 |
+
{"input": f"{prompt} {post_prompt}"},
|
| 253 |
+
return_only_outputs=True,
|
| 254 |
) # retrieve response from chatgpt
|
| 255 |
+
try:
|
| 256 |
+
assistant_response += docs["answer"]
|
| 257 |
+
except:
|
| 258 |
+
assistant_response += docs["output"]
|
| 259 |
+
top_games = docs['name']
|
| 260 |
|
| 261 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
print(docs)
|
| 263 |
+
|
|
|
|
|
|
|
|
|
|
| 264 |
# separating response into chunk of words
|
| 265 |
chunks = []
|
| 266 |
for line in assistant_response.splitlines():
|
|
|
|
| 277 |
|
| 278 |
# Add assistant response to chat history
|
| 279 |
st.session_state.messages.append({"role": "assistant", "content": full_response})
|
| 280 |
+
if is_plot: st.session_state.gamenames.append(top_games)
|
| 281 |
+
|
| 282 |
+
col1, col2, col3= st.columns([4,3,4])
|
| 283 |
with col2:
|
| 284 |
if is_plot and db_selected==db_plot:
|
| 285 |
if st.button("Plot Games"): # button in center column
|
| 286 |
switch_page('Overall')
|
| 287 |
+
else:
|
| 288 |
+
try:
|
| 289 |
+
appid = df[df['Name']==top_games[0]]['AppID'].iloc[0]
|
| 290 |
+
url = f'https://store.steampowered.com/app/{appid}'
|
| 291 |
+
st.link_button("Check on Steam", url)
|
| 292 |
+
except: pass
|
| 293 |
+
with st.sidebar:
|
| 294 |
+
try: home_dfbox(top_games)
|
| 295 |
+
except: pass
|
| 296 |
|
| 297 |
# Styling on Tabs
|
| 298 |
css = '''
|
module/__custom__.py
CHANGED
|
@@ -121,6 +121,15 @@ def rec_dfbox():
|
|
| 121 |
df_names = pd.DataFrame(rec_games, columns=['gamename'])
|
| 122 |
st.write(title)
|
| 123 |
st.dataframe(df_names[0:len(rec_games)])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
# plot 1 Section
|
| 126 |
"""Plot contains the top ranked games
|
|
|
|
| 121 |
df_names = pd.DataFrame(rec_games, columns=['gamename'])
|
| 122 |
st.write(title)
|
| 123 |
st.dataframe(df_names[0:len(rec_games)])
|
| 124 |
+
# Overloaded with argument of names
|
| 125 |
+
def home_dfbox(rec_games):
|
| 126 |
+
title = f"1.1 :blue[Recommended] by :green[GameInsightify]"
|
| 127 |
+
if len(rec_games) > 0:
|
| 128 |
+
with st.sidebar:
|
| 129 |
+
df_names = pd.DataFrame(rec_games, columns=['gamename'])
|
| 130 |
+
st.write(title)
|
| 131 |
+
st.dataframe(df_names[0:len(rec_games)])
|
| 132 |
+
|
| 133 |
|
| 134 |
# plot 1 Section
|
| 135 |
"""Plot contains the top ranked games
|