zypchn commited on
Commit
e9275ec
·
verified ·
1 Parent(s): 54f8754

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +70 -39
src/streamlit_app.py CHANGED
@@ -7,48 +7,78 @@ 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
12
-
13
- # --- 1. Setup Tools & LLM (Cached to prevent reloading on every click) ---
14
- @st.cache_resource
15
- def initialize_agent():
16
- advisor = PokemonAdvisorTools()
17
- tool_methods = [
18
- advisor.get_card_info,
19
- advisor.find_grading_opportunities,
20
- advisor.assess_risk_volatility,
21
- advisor.get_roi_metrics,
22
- advisor.get_recent_price_spikes,
23
- advisor.analyze_set_performance,
24
- advisor.find_cards_by_artist,
25
- advisor.get_market_movers
26
- ]
27
- tools = [FunctionTool.from_defaults(fn=func) for func in tool_methods]
28
- llm = OpenAI(model="gpt-4o-mini")
29
-
30
- system_prompt = """### ROLE
31
- You are the **Poke-Alpha 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.
38
- 4. **Profit Hunting:** If a user asks "What should I buy?", use `find_grading_opportunities` or `get_market_movers`."""
39
-
40
- agent = ReActAgent(
41
- tools=tools,
42
- llm=llm,
43
- verbose=True,
44
- system_prompt=system_prompt,
45
- timeout=120
46
- )
47
- # Context should be initialized once
48
- ctx = Context(agent)
49
- return agent, ctx
50
-
51
- agent, global_ctx = initialize_agent()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  # --- 2. Page Configuration ---
54
  st.set_page_config(page_title="cAsh Robo-Advisor", page_icon="🤖", layout="wide")
@@ -105,4 +135,5 @@ if prompt := st.chat_input("Ask your Pokemon Quants advisor..."):
105
  with st.chat_message("user"):
106
  st.markdown(prompt)
107
 
108
- asyncio.run(process_chat(prompt))
 
 
7
  from llama_index.core.workflow import Context
8
  from llama_index.core.tools import FunctionTool
9
 
10
+ # --- 1. Setup Tools & LLM ---
11
+ # Instantiate the class to load data
12
+ advisor = PokemonAdvisorTools()
13
+
14
+ # Create the list of tool methods to wrap
15
+ tool_methods = [
16
+ advisor.get_card_info,
17
+ advisor.find_grading_opportunities,
18
+ advisor.assess_risk_volatility,
19
+ advisor.get_roi_metrics,
20
+ advisor.get_recent_price_spikes,
21
+ advisor.analyze_set_performance,
22
+ advisor.find_cards_by_artist,
23
+ advisor.get_market_movers
24
+ ]
25
+
26
+ # Wrap tools into LlamaIndex FunctionTools
27
+ tools = [FunctionTool.from_defaults(fn=func) for func in tool_methods]
28
+
29
+ # Initialize the LLM (Ensure OPENAI_API_KEY is set in your env)
30
+ llm = OpenAI(model="gpt-4o-mini", temperature=0.6)
31
+
32
+ # --- 2. System Prompt ---
33
+ system_prompt = """
34
+ ### ROLE
35
+ You are the **cAsh, Pokemon Investment Advisor**, an expert algorithmic trading assistant for the Pokemon TCG market.
36
+ You rely **strictly** on data. You do not guess. You do not hallucinate prices. Always answer in English.
37
 
38
  ### TOOL USAGE PROTOCOL
39
  1. **Verify First:** If a user asks about a card, ALWAYS use `get_card_info` first to ensure it exists.
40
  2. **Safety Check:** BEFORE recommending ANY card, you MUST call `assess_risk_volatility` (default to 6 months).
41
+ 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.
42
+ 4. **Profit Hunting:** If a user asks "What should I buy?", use `find_grading_opportunities` or `get_market_movers`.
43
+
44
+ ### TONE
45
+ Professional, objective, and user-friendly.
46
+ """
47
+ # --- 3. Initialize Agent & Global Memory ---
48
+ # We use timeout=120 because deep reasoning sequences can take time
49
+ agent = ReActAgent(
50
+ tools=tools,
51
+ llm=llm,
52
+ verbose=True,
53
+ system_prompt=system_prompt,
54
+ timeout=120
55
+ )
56
+
57
+ # Global Context acts as the "Server Memory" for this session
58
+ global_ctx = Context(agent)
59
+
60
+ # --- 4. Define the Chat Function (Async) ---
61
+ async def ask_advisor(user_message, history):
62
+ st.session_state.messages.append({"role": "user", "content": user_message})
63
+ """
64
+ Async function to handle the chat.
65
+ It uses 'global_ctx' to maintain memory of previous turns/corrections.
66
+ """
67
+ if not user_message:
68
+ return "Please enter a message."
69
+
70
+ try:
71
+ # Execute the agent workflow
72
+ # The 'ctx' argument passes the memory of previous interactions
73
+ response = await agent.run(user_msg=user_message, ctx=global_ctx)
74
+ final_text = str(response)
75
+ response_placeholder.markdown(final_text)
76
+ st.session_state.messages.append({"role": "assistant", "content": final_text})
77
+ # Return the final text response
78
+ return str(response)
79
+
80
+ except Exception as e:
81
+ return f"⚠️ **Agent Error:** {str(e)}\n\n*Check the console logs for detailed tool output.*"
82
 
83
  # --- 2. Page Configuration ---
84
  st.set_page_config(page_title="cAsh Robo-Advisor", page_icon="🤖", layout="wide")
 
135
  with st.chat_message("user"):
136
  st.markdown(prompt)
137
 
138
+ # asyncio.run(process_chat(prompt))
139
+ await ask_advisor(prompt)