T-K-O-H commited on
Commit
c928d10
·
1 Parent(s): 0b4a72e

Update code to use environment variables and improve error handling

Browse files
Files changed (6) hide show
  1. Dockerfile +5 -4
  2. agent_graph.py +1 -1
  3. app.py +70 -32
  4. chainlit.md +55 -0
  5. requirements.txt +7 -6
  6. test_agent.py +14 -44
Dockerfile CHANGED
@@ -10,7 +10,7 @@ RUN apt-get update && apt-get install -y \
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  # Create a non-root user
13
- RUN useradd -m -u 1000 app_user
14
 
15
  # Copy requirements first for better caching
16
  COPY requirements.txt /code/requirements.txt
@@ -21,16 +21,17 @@ COPY . /code/
21
 
22
  # Create necessary directories and set permissions
23
  RUN mkdir -p /code/.files && \
24
- chown -R app_user:app_user /code && \
25
  chmod -R 755 /code
26
 
27
  # Set environment variables
28
  ENV HOST=0.0.0.0
29
  ENV PORT=7860
30
  ENV PYTHONPATH=/code
 
31
 
32
  # Switch to non-root user
33
- USER app_user
34
 
35
  # Command to run the application
36
- CMD python app.py
 
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  # Create a non-root user
13
+ RUN useradd -m -u 1000 chainlit_user
14
 
15
  # Copy requirements first for better caching
16
  COPY requirements.txt /code/requirements.txt
 
21
 
22
  # Create necessary directories and set permissions
23
  RUN mkdir -p /code/.files && \
24
+ chown -R chainlit_user:chainlit_user /code && \
25
  chmod -R 755 /code
26
 
27
  # Set environment variables
28
  ENV HOST=0.0.0.0
29
  ENV PORT=7860
30
  ENV PYTHONPATH=/code
31
+ ENV OPENAI_API_KEY=${OPENAI_API_KEY}
32
 
33
  # Switch to non-root user
34
+ USER chainlit_user
35
 
36
  # Command to run the application
37
+ CMD chainlit run app.py --host $HOST --port $PORT
agent_graph.py CHANGED
@@ -18,7 +18,7 @@ if not openai_api_key:
18
 
19
  # Initialize the LLM
20
  llm = ChatOpenAI(
21
- model="gpt-4",
22
  temperature=0,
23
  openai_api_key=openai_api_key
24
  )
 
18
 
19
  # Initialize the LLM
20
  llm = ChatOpenAI(
21
+ model="gpt-3.5-turbo",
22
  temperature=0,
23
  openai_api_key=openai_api_key
24
  )
app.py CHANGED
@@ -1,39 +1,77 @@
1
- import gradio as gr
2
- from test_agent import process_query
3
- import logging
4
  import os
5
- from dotenv import load_dotenv
 
 
 
6
 
7
- # Load environment variables
8
  load_dotenv()
9
 
10
- # Set up logging
11
- logging.basicConfig(level=logging.INFO)
12
- logger = logging.getLogger(__name__)
13
 
14
- def respond(message, history):
15
- """Process the user's message and return the response."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  try:
17
- logger.info(f"Received message: {message}")
18
- response = process_query(message)
19
- logger.info(f"Sending response: {response}")
20
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  except Exception as e:
22
- error_msg = f"Error processing message: {str(e)}"
23
- logger.error(error_msg)
24
- return error_msg
25
-
26
- # Create the Gradio interface
27
- demo = gr.ChatInterface(
28
- fn=respond,
29
- title="AI Stock Agent",
30
- description="Ask me about stock prices and buying power calculations!",
31
- examples=[
32
- "What is the current price of AAPL?",
33
- "How many shares of MSFT can I buy with $5000?",
34
- ],
35
- )
36
-
37
- # Launch the interface
38
- if __name__ == "__main__":
39
- demo.launch()
 
 
 
 
1
  import os
2
+ import chainlit as cl
3
+ from agent_graph import agent_node
4
+ from dotenv import load_dotenv # Import dotenv
5
+ from typing import List, Dict
6
 
7
+ # Load environment variables from .env file
8
  load_dotenv()
9
 
10
+ # Ensure your OpenAI API key is set up in environment variables
11
+ openai_api_key = os.getenv("OPENAI_API_KEY")
 
12
 
13
+ if not openai_api_key:
14
+ raise ValueError("OpenAI API key is missing in the .env file")
15
+
16
+ # Store chat history
17
+ chat_histories: Dict[str, List[Dict[str, str]]] = {}
18
+
19
+ @cl.on_chat_start
20
+ async def start_chat():
21
+ # Initialize empty chat history for this session
22
+ chat_histories[cl.user_session.get("id")] = []
23
+
24
+ welcome_message = """👋 Welcome to the Stock Price Calculator!
25
+
26
+ I can help you with:
27
+ • Getting real-time stock prices
28
+ • Calculating how many shares you can buy
29
+
30
+ Try these examples:
31
+ • Type 'AAPL' to get Apple's stock price
32
+ • Ask 'How many MSFT shares can I buy with $10000?'
33
+
34
+ What would you like to know?"""
35
+
36
+ await cl.Message(content=welcome_message).send()
37
+
38
+ @cl.on_message
39
+ async def handle_message(message: cl.Message):
40
  try:
41
+ # Get chat history for this session
42
+ session_id = cl.user_session.get("id")
43
+ history = chat_histories.get(session_id, [])
44
+
45
+ # Add current message to history
46
+ history.append({"role": "user", "content": message.content})
47
+
48
+ # Create state dictionary with history
49
+ state = {
50
+ "input": message.content,
51
+ "chat_history": history
52
+ }
53
+
54
+ # Process the message with agent_node
55
+ response = agent_node(state)
56
+
57
+ # Send the response back to the user
58
+ if isinstance(response, dict) and "output" in response:
59
+ # Add response to history
60
+ history.append({"role": "assistant", "content": response["output"]})
61
+ await cl.Message(content=response["output"]).send()
62
+ else:
63
+ await cl.Message(content="Received an invalid response format from the agent.").send()
64
+
65
+ # Update history in storage
66
+ chat_histories[session_id] = history
67
+
68
  except Exception as e:
69
+ print(f"Error occurred: {e}")
70
+ await cl.Message(content="Sorry, something went wrong while processing your request.").send()
71
+
72
+ @cl.on_chat_end
73
+ async def end_chat():
74
+ # Clean up chat history when session ends
75
+ session_id = cl.user_session.get("id")
76
+ if session_id in chat_histories:
77
+ del chat_histories[session_id]
 
 
 
 
 
 
 
 
 
chainlit.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Stock Price & Share Calculator 📈
2
+
3
+ Welcome! This app helps you:
4
+ 1. Check real-time stock prices
5
+ 2. Calculate how many shares you can buy with a specific amount
6
+
7
+ ## Quick Start Guide 🚀
8
+
9
+ ### 1️⃣ Get Stock Prices
10
+ Just type a ticker symbol or company name:
11
+ ```
12
+ AAPL
13
+ ```
14
+ or
15
+ ```
16
+ What's the price of Apple?
17
+ ```
18
+
19
+ ### 2️⃣ Calculate Shares
20
+ Ask how many shares you can afford:
21
+ ```
22
+ How many AAPL shares can I buy with $10000?
23
+ ```
24
+
25
+ ## Popular Stocks You Can Try 💎
26
+
27
+ ### Tech Companies
28
+ - `AAPL` - Apple
29
+ - `MSFT` - Microsoft
30
+ - `GOOGL` - Google
31
+ - `AMZN` - Amazon
32
+ - `META` - Meta/Facebook
33
+ - `TSLA` - Tesla
34
+ - `NVDA` - NVIDIA
35
+
36
+ ### Financial
37
+ - `JPM` - JPMorgan
38
+ - `BAC` - Bank of America
39
+ - `GS` - Goldman Sachs
40
+
41
+ ### Retail
42
+ - `WMT` - Walmart
43
+ - `COST` - Costco
44
+ - `SBUX` - Starbucks
45
+
46
+ ## Tips 💡
47
+ - You can use either the ticker (e.g., `AAPL`) or company name (e.g., "Apple")
48
+ - Include a dollar amount to calculate shares (e.g., "AAPL $5000")
49
+ - All prices are real-time from the market
50
+
51
+ Try it now! Type a ticker symbol or ask about any company listed above.
52
+
53
+ ## Welcome screen
54
+
55
+ To modify the welcome screen, edit the `chainlit.md` file at the root of your project. If you do not want a welcome screen, just leave this file empty.
requirements.txt CHANGED
@@ -1,6 +1,7 @@
1
- langchain==0.0.267
2
- openai==0.28.0
3
- python-dotenv==1.0.0
4
- yfinance==0.2.18
5
- gradio==3.50.2
6
- requests==2.31.0
 
 
1
+ chainlit
2
+ langchain-openai>=0.0.3
3
+ langchain-core>=0.1.4
4
+ openai>=1.7.0
5
+ python-dotenv>=1.0.0
6
+ yfinance>=0.2.36
7
+ typing-extensions>=4.9.0
test_agent.py CHANGED
@@ -3,26 +3,16 @@ from langchain.agents import initialize_agent, Tool, AgentType
3
  from tools import get_price, buying_power_tool
4
  from dotenv import load_dotenv
5
  import os
6
- import logging
7
-
8
- # Set up logging
9
- logging.basicConfig(level=logging.INFO)
10
- logger = logging.getLogger(__name__)
11
 
12
  # Load environment variables from .env file
13
  load_dotenv()
14
 
15
  # Initialize the language model with API key from environment variables
16
- try:
17
- llm = ChatOpenAI(
18
- temperature=0,
19
- model_name="gpt-3.5-turbo",
20
- openai_api_key=os.getenv("OPENAI_API_KEY")
21
- )
22
- logger.info("Successfully initialized ChatOpenAI")
23
- except Exception as e:
24
- logger.error(f"Failed to initialize ChatOpenAI: {str(e)}")
25
- raise
26
 
27
  # Define tools
28
  tools = [
@@ -39,33 +29,13 @@ tools = [
39
  ]
40
 
41
  # Initialize the agent
42
- try:
43
- agent = initialize_agent(
44
- tools,
45
- llm,
46
- agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
47
- verbose=True
48
- )
49
- logger.info("Successfully initialized agent")
50
- except Exception as e:
51
- logger.error(f"Failed to initialize agent: {str(e)}")
52
- raise
53
-
54
- def process_query(query):
55
- """Process a user query and return the response."""
56
- try:
57
- logger.info(f"Processing query: {query}")
58
- response = agent.run(query)
59
- logger.info(f"Response: {response}")
60
- return response
61
- except Exception as e:
62
- error_msg = f"Error processing query: {str(e)}"
63
- logger.error(error_msg)
64
- return error_msg
65
 
66
- # Run a test if this is the main module
67
- if __name__ == "__main__":
68
- test_query = "How much is AAPL?"
69
- logger.info(f"Running test with query: {test_query}")
70
- response = process_query(test_query)
71
- print(response)
 
3
  from tools import get_price, buying_power_tool
4
  from dotenv import load_dotenv
5
  import os
 
 
 
 
 
6
 
7
  # Load environment variables from .env file
8
  load_dotenv()
9
 
10
  # Initialize the language model with API key from environment variables
11
+ llm = ChatOpenAI(
12
+ temperature=0,
13
+ model_name="gpt-3.5-turbo",
14
+ openai_api_key=os.getenv("OPENAI_API_KEY")
15
+ )
 
 
 
 
 
16
 
17
  # Define tools
18
  tools = [
 
29
  ]
30
 
31
  # Initialize the agent
32
+ agent = initialize_agent(
33
+ tools,
34
+ llm,
35
+ agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
36
+ verbose=True
37
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ # Run a test
40
+ response = agent.run("How much is AAPL?")
41
+ print(response)