Spaces:
Sleeping
Sleeping
Update src/main.py
Browse files- src/main.py +209 -209
src/main.py
CHANGED
|
@@ -1,209 +1,209 @@
|
|
| 1 |
-
import ast
|
| 2 |
-
import json
|
| 3 |
-
import streamlit as st
|
| 4 |
-
import pandas as pd
|
| 5 |
-
from langchain.agents.agent_types import AgentType
|
| 6 |
-
from langchain_experimental.agents import create_csv_agent
|
| 7 |
-
from langchain_groq import ChatGroq
|
| 8 |
-
from langchain.memory import ChatMessageHistory
|
| 9 |
-
from groq import Groq
|
| 10 |
-
|
| 11 |
-
# Initialize Groq client and model
|
| 12 |
-
client = Groq(api_key='gsk')
|
| 13 |
-
MODEL = 'llama3-70b-8192'
|
| 14 |
-
|
| 15 |
-
# Initialize chat history
|
| 16 |
-
history = ChatMessageHistory()
|
| 17 |
-
history.add_user_message("hi!")
|
| 18 |
-
history.add_ai_message("whats up?")
|
| 19 |
-
|
| 20 |
-
# Initialize language model
|
| 21 |
-
llm = ChatGroq(
|
| 22 |
-
temperature=0,
|
| 23 |
-
groq_api_key='gsk...',
|
| 24 |
-
model_name='llama3-70b-8192'
|
| 25 |
-
)
|
| 26 |
-
|
| 27 |
-
# Create CSV agent
|
| 28 |
-
agent = create_csv_agent(
|
| 29 |
-
llm,
|
| 30 |
-
r"Financial_data.csv",
|
| 31 |
-
verbose=True,
|
| 32 |
-
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
|
| 33 |
-
max_iterations=5,
|
| 34 |
-
handle_parsing_errors=True
|
| 35 |
-
)
|
| 36 |
-
|
| 37 |
-
# Functions to handle conversations
|
| 38 |
-
def convo_agent(question, chat_history):
|
| 39 |
-
response = 'I was built to answer questions related to financials MSFT, TSLA and AAPL. Let me know if you have any questions on these.'
|
| 40 |
-
return {'answer': response}
|
| 41 |
-
|
| 42 |
-
def csv_agent(question, chat_history):
|
| 43 |
-
prompt = (
|
| 44 |
-
"""
|
| 45 |
-
Let's decode the way to respond to the queries. The responses depend on the type of information requested in the query.
|
| 46 |
-
|
| 47 |
-
Return just the data, don't take effort of creating plots, prints and all.
|
| 48 |
-
No explanation needed. Return just the dict
|
| 49 |
-
Always include units in response .
|
| 50 |
-
|
| 51 |
-
1. If the query requires a table, format your answer like this:
|
| 52 |
-
{"table": {"columns": ["column1", "column2", ...], "data": [[value1, value2, ...], [value1, value2, ...], ...]}}
|
| 53 |
-
|
| 54 |
-
2. For a bar chart, respond like this:
|
| 55 |
-
{"bar": {"columns": ["A", "B", "C", ...], "data": [25, 24, 10, ...]}}
|
| 56 |
-
|
| 57 |
-
3. If a line chart is more appropriate, your reply should look like this:
|
| 58 |
-
{"line": {"columns": ["A", "B", "C", ...], "data": [25, 24, 10, ...]}}
|
| 59 |
-
|
| 60 |
-
Note: We only accommodate two types of charts: "bar" and "line".
|
| 61 |
-
|
| 62 |
-
4. For a plain question that doesn't need a chart or table, your response should be:
|
| 63 |
-
{"answer": "Your answer goes here"}
|
| 64 |
-
|
| 65 |
-
For example:
|
| 66 |
-
{"answer": "The Product with the highest Orders is '15143Exfo'"}
|
| 67 |
-
|
| 68 |
-
5. If the answer is not known or available, respond with:
|
| 69 |
-
{"answer": "I do not know."}
|
| 70 |
-
|
| 71 |
-
Return all output as a string. Remember to encase all strings in the "columns" list and data list in double quotes.
|
| 72 |
-
For example: {"columns": ["Products", "Orders"], "data": [["51993Masc", 191], ["49631Foun", 152]]}
|
| 73 |
-
|
| 74 |
-
Return all the numerical values in int format only.
|
| 75 |
-
Now, let's tackle the query step by step. Here's the query for you to work on:"""
|
| 76 |
-
+
|
| 77 |
-
question
|
| 78 |
-
)
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
response = agent.run(prompt)
|
| 83 |
-
return ast.literal_eval(response)
|
| 84 |
-
|
| 85 |
-
# Define tools and function mapping
|
| 86 |
-
tool_convo_agent = {
|
| 87 |
-
"type": "function",
|
| 88 |
-
"function": {
|
| 89 |
-
"name": "convo_agent",
|
| 90 |
-
"description": "Answers questions like chit chat or simple friendly messages",
|
| 91 |
-
"parameters": {
|
| 92 |
-
"type": "object",
|
| 93 |
-
"properties": {
|
| 94 |
-
"question": {"type": "string", "description": "The user question"}
|
| 95 |
-
},
|
| 96 |
-
"required": ["question"],
|
| 97 |
-
},
|
| 98 |
-
},
|
| 99 |
-
}
|
| 100 |
-
|
| 101 |
-
tool_fin_agent = {
|
| 102 |
-
"type": "function",
|
| 103 |
-
"function": {
|
| 104 |
-
"name": "csv_agent",
|
| 105 |
-
"description": "Answers questions related to financial metrics of us Apple, Microsoft and Tesla.",
|
| 106 |
-
"parameters": {
|
| 107 |
-
"type": "object",
|
| 108 |
-
"properties": {
|
| 109 |
-
"question": {"type": "string", "description": "The user question"}
|
| 110 |
-
},
|
| 111 |
-
"required": ["question"],
|
| 112 |
-
},
|
| 113 |
-
},
|
| 114 |
-
}
|
| 115 |
-
|
| 116 |
-
tools = [tool_convo_agent, tool_fin_agent]
|
| 117 |
-
|
| 118 |
-
function_map = {
|
| 119 |
-
"csv_agent": csv_agent,
|
| 120 |
-
"convo_agent": convo_agent
|
| 121 |
-
}
|
| 122 |
-
|
| 123 |
-
# Conversation handling
|
| 124 |
-
def run_conversation(chat_history, user_prompt, tools):
|
| 125 |
-
final_prompt = {'chat_history':{chat_history}, 'question':{user_prompt}}
|
| 126 |
-
messages = [
|
| 127 |
-
{"role": "system", "content": "You are an efficient agent that determines which function to use in order to answer user question."},
|
| 128 |
-
{"role": "user", "content": str(final_prompt)},
|
| 129 |
-
]
|
| 130 |
-
|
| 131 |
-
response = client.chat.completions.create(
|
| 132 |
-
model=MODEL,
|
| 133 |
-
messages=messages,
|
| 134 |
-
tools=tools,
|
| 135 |
-
tool_choice="auto",
|
| 136 |
-
max_tokens=4096
|
| 137 |
-
)
|
| 138 |
-
|
| 139 |
-
response_message = response.choices[0].message
|
| 140 |
-
tool_calls = response_message.tool_calls
|
| 141 |
-
return tool_calls
|
| 142 |
-
|
| 143 |
-
def get_response(question):
|
| 144 |
-
try:
|
| 145 |
-
history.add_user_message(question)
|
| 146 |
-
chat_history = str(history.messages)
|
| 147 |
-
agents = run_conversation(chat_history, question, tools)
|
| 148 |
-
func_to_call = agents[0].function.name
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
if func_to_call in function_map:
|
| 152 |
-
question_to_run = ast.literal_eval(agents[0].function.arguments)['question']
|
| 153 |
-
result = function_map[func_to_call](question_to_run, chat_history)
|
| 154 |
-
else:
|
| 155 |
-
result = {"error": "Something went Wrong"}
|
| 156 |
-
|
| 157 |
-
if 'error' in result:
|
| 158 |
-
return "Something went wrong"
|
| 159 |
-
print(result)
|
| 160 |
-
history.add_ai_message(str(result))
|
| 161 |
-
return result
|
| 162 |
-
|
| 163 |
-
except Exception as e:
|
| 164 |
-
return f"Something went wrong: {e}"
|
| 165 |
-
|
| 166 |
-
# Response writing for Streamlit
|
| 167 |
-
def write_answer(response_dict):
|
| 168 |
-
if not isinstance(response_dict, dict):
|
| 169 |
-
return "Invalid response format received."
|
| 170 |
-
|
| 171 |
-
if "answer" in response_dict:
|
| 172 |
-
return response_dict
|
| 173 |
-
|
| 174 |
-
if "bar" in response_dict:
|
| 175 |
-
data = response_dict["bar"]
|
| 176 |
-
try:
|
| 177 |
-
df_data = {col: [x[i] if isinstance(x, list) else x for x in data['data']] for i, col in enumerate(data['columns'])}
|
| 178 |
-
df = pd.DataFrame(df_data)
|
| 179 |
-
df.set_index("Year", inplace=True)
|
| 180 |
-
st.bar_chart(df)
|
| 181 |
-
return {'bar': ''}
|
| 182 |
-
except ValueError:
|
| 183 |
-
st.error(f"Couldn't create DataFrame from data: {data}")
|
| 184 |
-
|
| 185 |
-
if "line" in response_dict:
|
| 186 |
-
data = response_dict["line"]
|
| 187 |
-
try:
|
| 188 |
-
df_data = {col: [x[i] for x in data['data']] for i, col in enumerate(data['columns'])}
|
| 189 |
-
df = pd.DataFrame(df_data)
|
| 190 |
-
df.set_index("Year", inplace=True)
|
| 191 |
-
st.line_chart(df)
|
| 192 |
-
return {'line': ''}
|
| 193 |
-
except ValueError:
|
| 194 |
-
st.error(f"Couldn't create DataFrame from data: {data}")
|
| 195 |
-
|
| 196 |
-
if "table" in response_dict:
|
| 197 |
-
data = response_dict["table"]
|
| 198 |
-
try:
|
| 199 |
-
clean_data = [
|
| 200 |
-
[int(x.replace(',', '')) if isinstance(x, str) and x.replace(',', '').isdigit() else x for x in row]
|
| 201 |
-
for row in data["data"]
|
| 202 |
-
]
|
| 203 |
-
df = pd.DataFrame(clean_data, columns=data["columns"])
|
| 204 |
-
st.table(df)
|
| 205 |
-
return {'table': ''}
|
| 206 |
-
except ValueError as e:
|
| 207 |
-
st.error(f"Couldn't create DataFrame from data: {data}. Error: {e}")
|
| 208 |
-
|
| 209 |
-
return "No valid response type found."
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import json
|
| 3 |
+
import streamlit as st
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from langchain.agents.agent_types import AgentType
|
| 6 |
+
from langchain_experimental.agents import create_csv_agent
|
| 7 |
+
from langchain_groq import ChatGroq
|
| 8 |
+
from langchain.memory import ChatMessageHistory
|
| 9 |
+
from groq import Groq
|
| 10 |
+
|
| 11 |
+
# Initialize Groq client and model
|
| 12 |
+
client = Groq(api_key='gsk')
|
| 13 |
+
MODEL = 'llama3-70b-8192'
|
| 14 |
+
|
| 15 |
+
# Initialize chat history
|
| 16 |
+
history = ChatMessageHistory()
|
| 17 |
+
history.add_user_message("hi!")
|
| 18 |
+
history.add_ai_message("whats up?")
|
| 19 |
+
|
| 20 |
+
# Initialize language model
|
| 21 |
+
llm = ChatGroq(
|
| 22 |
+
temperature=0,
|
| 23 |
+
groq_api_key='gsk...',
|
| 24 |
+
model_name='llama3-70b-8192'
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# Create CSV agent
|
| 28 |
+
agent = create_csv_agent(
|
| 29 |
+
llm,
|
| 30 |
+
r"data\Financial_data.csv",
|
| 31 |
+
verbose=True,
|
| 32 |
+
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
|
| 33 |
+
max_iterations=5,
|
| 34 |
+
handle_parsing_errors=True
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
# Functions to handle conversations
|
| 38 |
+
def convo_agent(question, chat_history):
|
| 39 |
+
response = 'I was built to answer questions related to financials MSFT, TSLA and AAPL. Let me know if you have any questions on these.'
|
| 40 |
+
return {'answer': response}
|
| 41 |
+
|
| 42 |
+
def csv_agent(question, chat_history):
|
| 43 |
+
prompt = (
|
| 44 |
+
"""
|
| 45 |
+
Let's decode the way to respond to the queries. The responses depend on the type of information requested in the query.
|
| 46 |
+
|
| 47 |
+
Return just the data, don't take effort of creating plots, prints and all.
|
| 48 |
+
No explanation needed. Return just the dict
|
| 49 |
+
Always include units in response .
|
| 50 |
+
|
| 51 |
+
1. If the query requires a table, format your answer like this:
|
| 52 |
+
{"table": {"columns": ["column1", "column2", ...], "data": [[value1, value2, ...], [value1, value2, ...], ...]}}
|
| 53 |
+
|
| 54 |
+
2. For a bar chart, respond like this:
|
| 55 |
+
{"bar": {"columns": ["A", "B", "C", ...], "data": [25, 24, 10, ...]}}
|
| 56 |
+
|
| 57 |
+
3. If a line chart is more appropriate, your reply should look like this:
|
| 58 |
+
{"line": {"columns": ["A", "B", "C", ...], "data": [25, 24, 10, ...]}}
|
| 59 |
+
|
| 60 |
+
Note: We only accommodate two types of charts: "bar" and "line".
|
| 61 |
+
|
| 62 |
+
4. For a plain question that doesn't need a chart or table, your response should be:
|
| 63 |
+
{"answer": "Your answer goes here"}
|
| 64 |
+
|
| 65 |
+
For example:
|
| 66 |
+
{"answer": "The Product with the highest Orders is '15143Exfo'"}
|
| 67 |
+
|
| 68 |
+
5. If the answer is not known or available, respond with:
|
| 69 |
+
{"answer": "I do not know."}
|
| 70 |
+
|
| 71 |
+
Return all output as a string. Remember to encase all strings in the "columns" list and data list in double quotes.
|
| 72 |
+
For example: {"columns": ["Products", "Orders"], "data": [["51993Masc", 191], ["49631Foun", 152]]}
|
| 73 |
+
|
| 74 |
+
Return all the numerical values in int format only.
|
| 75 |
+
Now, let's tackle the query step by step. Here's the query for you to work on:"""
|
| 76 |
+
+
|
| 77 |
+
question
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
response = agent.run(prompt)
|
| 83 |
+
return ast.literal_eval(response)
|
| 84 |
+
|
| 85 |
+
# Define tools and function mapping
|
| 86 |
+
tool_convo_agent = {
|
| 87 |
+
"type": "function",
|
| 88 |
+
"function": {
|
| 89 |
+
"name": "convo_agent",
|
| 90 |
+
"description": "Answers questions like chit chat or simple friendly messages",
|
| 91 |
+
"parameters": {
|
| 92 |
+
"type": "object",
|
| 93 |
+
"properties": {
|
| 94 |
+
"question": {"type": "string", "description": "The user question"}
|
| 95 |
+
},
|
| 96 |
+
"required": ["question"],
|
| 97 |
+
},
|
| 98 |
+
},
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
tool_fin_agent = {
|
| 102 |
+
"type": "function",
|
| 103 |
+
"function": {
|
| 104 |
+
"name": "csv_agent",
|
| 105 |
+
"description": "Answers questions related to financial metrics of us Apple, Microsoft and Tesla.",
|
| 106 |
+
"parameters": {
|
| 107 |
+
"type": "object",
|
| 108 |
+
"properties": {
|
| 109 |
+
"question": {"type": "string", "description": "The user question"}
|
| 110 |
+
},
|
| 111 |
+
"required": ["question"],
|
| 112 |
+
},
|
| 113 |
+
},
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
tools = [tool_convo_agent, tool_fin_agent]
|
| 117 |
+
|
| 118 |
+
function_map = {
|
| 119 |
+
"csv_agent": csv_agent,
|
| 120 |
+
"convo_agent": convo_agent
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
# Conversation handling
|
| 124 |
+
def run_conversation(chat_history, user_prompt, tools):
|
| 125 |
+
final_prompt = {'chat_history':{chat_history}, 'question':{user_prompt}}
|
| 126 |
+
messages = [
|
| 127 |
+
{"role": "system", "content": "You are an efficient agent that determines which function to use in order to answer user question."},
|
| 128 |
+
{"role": "user", "content": str(final_prompt)},
|
| 129 |
+
]
|
| 130 |
+
|
| 131 |
+
response = client.chat.completions.create(
|
| 132 |
+
model=MODEL,
|
| 133 |
+
messages=messages,
|
| 134 |
+
tools=tools,
|
| 135 |
+
tool_choice="auto",
|
| 136 |
+
max_tokens=4096
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
response_message = response.choices[0].message
|
| 140 |
+
tool_calls = response_message.tool_calls
|
| 141 |
+
return tool_calls
|
| 142 |
+
|
| 143 |
+
def get_response(question):
|
| 144 |
+
try:
|
| 145 |
+
history.add_user_message(question)
|
| 146 |
+
chat_history = str(history.messages)
|
| 147 |
+
agents = run_conversation(chat_history, question, tools)
|
| 148 |
+
func_to_call = agents[0].function.name
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if func_to_call in function_map:
|
| 152 |
+
question_to_run = ast.literal_eval(agents[0].function.arguments)['question']
|
| 153 |
+
result = function_map[func_to_call](question_to_run, chat_history)
|
| 154 |
+
else:
|
| 155 |
+
result = {"error": "Something went Wrong"}
|
| 156 |
+
|
| 157 |
+
if 'error' in result:
|
| 158 |
+
return "Something went wrong"
|
| 159 |
+
print(result)
|
| 160 |
+
history.add_ai_message(str(result))
|
| 161 |
+
return result
|
| 162 |
+
|
| 163 |
+
except Exception as e:
|
| 164 |
+
return f"Something went wrong: {e}"
|
| 165 |
+
|
| 166 |
+
# Response writing for Streamlit
|
| 167 |
+
def write_answer(response_dict):
|
| 168 |
+
if not isinstance(response_dict, dict):
|
| 169 |
+
return "Invalid response format received."
|
| 170 |
+
|
| 171 |
+
if "answer" in response_dict:
|
| 172 |
+
return response_dict
|
| 173 |
+
|
| 174 |
+
if "bar" in response_dict:
|
| 175 |
+
data = response_dict["bar"]
|
| 176 |
+
try:
|
| 177 |
+
df_data = {col: [x[i] if isinstance(x, list) else x for x in data['data']] for i, col in enumerate(data['columns'])}
|
| 178 |
+
df = pd.DataFrame(df_data)
|
| 179 |
+
df.set_index("Year", inplace=True)
|
| 180 |
+
st.bar_chart(df)
|
| 181 |
+
return {'bar': ''}
|
| 182 |
+
except ValueError:
|
| 183 |
+
st.error(f"Couldn't create DataFrame from data: {data}")
|
| 184 |
+
|
| 185 |
+
if "line" in response_dict:
|
| 186 |
+
data = response_dict["line"]
|
| 187 |
+
try:
|
| 188 |
+
df_data = {col: [x[i] for x in data['data']] for i, col in enumerate(data['columns'])}
|
| 189 |
+
df = pd.DataFrame(df_data)
|
| 190 |
+
df.set_index("Year", inplace=True)
|
| 191 |
+
st.line_chart(df)
|
| 192 |
+
return {'line': ''}
|
| 193 |
+
except ValueError:
|
| 194 |
+
st.error(f"Couldn't create DataFrame from data: {data}")
|
| 195 |
+
|
| 196 |
+
if "table" in response_dict:
|
| 197 |
+
data = response_dict["table"]
|
| 198 |
+
try:
|
| 199 |
+
clean_data = [
|
| 200 |
+
[int(x.replace(',', '')) if isinstance(x, str) and x.replace(',', '').isdigit() else x for x in row]
|
| 201 |
+
for row in data["data"]
|
| 202 |
+
]
|
| 203 |
+
df = pd.DataFrame(clean_data, columns=data["columns"])
|
| 204 |
+
st.table(df)
|
| 205 |
+
return {'table': ''}
|
| 206 |
+
except ValueError as e:
|
| 207 |
+
st.error(f"Couldn't create DataFrame from data: {data}. Error: {e}")
|
| 208 |
+
|
| 209 |
+
return "No valid response type found."
|