zypchn commited on
Commit
32e23ca
·
verified ·
1 Parent(s): 417c323

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +30 -27
src/streamlit_app.py CHANGED
@@ -1,11 +1,10 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import os
4
- import asyncio
5
  from llama_index.llms.openai import OpenAI
6
  from llama_index.core.agent import ReActAgent
7
- from llama_index.core.workflow import Context
8
  from llama_index.core.tools import FunctionTool
 
9
 
10
  # --- Import tools class ---
11
  from tools import PokemonAdvisorTools
@@ -26,54 +25,58 @@ def initialize_agent():
26
  advisor.get_data_shape
27
  ]
28
  tools = [FunctionTool.from_defaults(fn=func) for func in tool_methods]
29
- llm = OpenAI(model="gpt-4o-mini")
30
 
31
  system_prompt = """### ROLE
32
  You are the **cAsh, Pokemon Investment Advisor**, an expert algorithmic trading assistant for the Pokémon TCG market.
33
  You rely **strictly** on data. You do not guess. You do not hallucinate prices.
 
34
  ### TOOL USAGE PROTOCOL
35
  1. **Verify First:** If a user asks about a card, ALWAYS use `get_card_info` first to ensure it exists.
36
  2. **Safety Check:** BEFORE recommending ANY card, you MUST call `assess_risk_volatility` (default to 6 months).
37
  3. **Refining Search:** If the user corrects you (e.g., "Not that card"), use `get_card_info` again with the corrected name or use `analyze_set_performance` to broaden the scope.
38
  4. **Profit Hunting:** If a user asks "What should I buy?", use `find_grading_opportunities` or `get_market_movers`.
 
39
  ### TONE
40
  Professional, objective, concise, and user-friendly.
41
  """
42
 
43
- agent = ReActAgent(
44
  tools=tools,
45
  llm=llm,
46
- verbose=True,
47
- system_prompt=system_prompt,
48
- timeout=120
49
  )
50
- # Context should be initialized once
51
- ctx = Context(agent)
52
- return agent, ctx
 
 
53
 
54
- agent, global_ctx = initialize_agent()
55
- print("agent has initialized")
56
 
57
  # --- 2. Page Configuration ---
58
  st.set_page_config(page_title="cAsh Robo-Advisor", page_icon="🤖", layout="wide")
59
 
60
  # --- 3. Chat Logic Function ---
61
- async def process_chat(user_message):
62
- """Handles the async call to the agent and updates session state."""
63
  st.session_state.messages.append({"role": "user", "content": user_message})
64
 
65
  # Placeholder for the assistant's response while it thinks
66
  with st.chat_message("assistant"):
67
  response_placeholder = st.empty()
68
- try:
69
- # Execute the agent workflow
70
- response = await agent.run(user_msg=user_message, ctx=global_ctx)
71
- final_text = str(response)
72
- response_placeholder.markdown(final_text)
73
- st.session_state.messages.append({"role": "assistant", "content": final_text})
74
- except Exception as e:
75
- error_msg = f"⚠️ **Agent Error:** {str(e)}"
76
- response_placeholder.markdown(error_msg)
 
 
77
 
78
  # --- 4. Sidebar & UI Styling ---
79
  st.title("🤖 cAsh Robo-Advisor")
@@ -87,6 +90,7 @@ if "messages" not in st.session_state:
87
  st.sidebar.header("Example Queries")
88
  examples = [
89
  "What are the top 3 grading opportunities right now?",
 
90
  "What cards are trending down?",
91
  "Show me profitable cards by Tomokazu Komiya."
92
  ]
@@ -94,7 +98,8 @@ examples = [
94
  # Sidebar helper: clicking an example sends it immediately
95
  for ex in examples:
96
  if st.sidebar.button(ex):
97
- asyncio.run(process_chat(ex))
 
98
 
99
  # --- 5. Main Chat Interface ---
100
  # Display existing messages
@@ -104,8 +109,6 @@ for message in st.session_state.messages:
104
 
105
  # User Input
106
  if prompt := st.chat_input("Ask your Pokemon Quants advisor..."):
107
- # Clear the "user" UI immediately then run logic
108
  with st.chat_message("user"):
109
  st.markdown(prompt)
110
-
111
- asyncio.run(process_chat(prompt))
 
1
  import streamlit as st
2
  import pandas as pd
3
  import os
 
4
  from llama_index.llms.openai import OpenAI
5
  from llama_index.core.agent import ReActAgent
 
6
  from llama_index.core.tools import FunctionTool
7
+ from llama_index.core.llms import ChatMessage
8
 
9
  # --- Import tools class ---
10
  from tools import PokemonAdvisorTools
 
25
  advisor.get_data_shape
26
  ]
27
  tools = [FunctionTool.from_defaults(fn=func) for func in tool_methods]
28
+ llm = OpenAI(model="gpt-4o-mini", temperature=0.1)
29
 
30
  system_prompt = """### ROLE
31
  You are the **cAsh, Pokemon Investment Advisor**, an expert algorithmic trading assistant for the Pokémon TCG market.
32
  You rely **strictly** on data. You do not guess. You do not hallucinate prices.
33
+
34
  ### TOOL USAGE PROTOCOL
35
  1. **Verify First:** If a user asks about a card, ALWAYS use `get_card_info` first to ensure it exists.
36
  2. **Safety Check:** BEFORE recommending ANY card, you MUST call `assess_risk_volatility` (default to 6 months).
37
  3. **Refining Search:** If the user corrects you (e.g., "Not that card"), use `get_card_info` again with the corrected name or use `analyze_set_performance` to broaden the scope.
38
  4. **Profit Hunting:** If a user asks "What should I buy?", use `find_grading_opportunities` or `get_market_movers`.
39
+
40
  ### TONE
41
  Professional, objective, concise, and user-friendly.
42
  """
43
 
44
+ agent = ReActAgent.from_tools(
45
  tools=tools,
46
  llm=llm,
47
+ verbose=True,
48
+ max_iterations=10
 
49
  )
50
+
51
+ # Set system prompt via chat history
52
+ agent.chat_history = [ChatMessage(role="system", content=system_prompt)]
53
+
54
+ return agent
55
 
56
+ agent = initialize_agent()
 
57
 
58
  # --- 2. Page Configuration ---
59
  st.set_page_config(page_title="cAsh Robo-Advisor", page_icon="🤖", layout="wide")
60
 
61
  # --- 3. Chat Logic Function ---
62
+ def process_chat(user_message):
63
+ """Handles the synchronous call to the agent and updates session state."""
64
  st.session_state.messages.append({"role": "user", "content": user_message})
65
 
66
  # Placeholder for the assistant's response while it thinks
67
  with st.chat_message("assistant"):
68
  response_placeholder = st.empty()
69
+ with st.spinner("Thinking..."):
70
+ try:
71
+ # Execute the agent chat
72
+ response = agent.chat(user_message)
73
+ final_text = str(response)
74
+ response_placeholder.markdown(final_text)
75
+ st.session_state.messages.append({"role": "assistant", "content": final_text})
76
+ except Exception as e:
77
+ error_msg = f"⚠️ **Agent Error:** {str(e)}"
78
+ response_placeholder.markdown(error_msg)
79
+ st.error(f"Full error: {repr(e)}")
80
 
81
  # --- 4. Sidebar & UI Styling ---
82
  st.title("🤖 cAsh Robo-Advisor")
 
90
  st.sidebar.header("Example Queries")
91
  examples = [
92
  "What are the top 3 grading opportunities right now?",
93
+ "Is investing in Charizard VMAX risky?",
94
  "What cards are trending down?",
95
  "Show me profitable cards by Tomokazu Komiya."
96
  ]
 
98
  # Sidebar helper: clicking an example sends it immediately
99
  for ex in examples:
100
  if st.sidebar.button(ex):
101
+ process_chat(ex)
102
+ st.rerun()
103
 
104
  # --- 5. Main Chat Interface ---
105
  # Display existing messages
 
109
 
110
  # User Input
111
  if prompt := st.chat_input("Ask your Pokemon Quants advisor..."):
 
112
  with st.chat_message("user"):
113
  st.markdown(prompt)
114
+ process_chat(prompt)