T-K-O-H commited on
Commit
c9027fd
·
1 Parent(s): ae52b28

Update code to use environment variables and improve error handling

Browse files
Files changed (3) hide show
  1. app.py +34 -0
  2. requirements.txt +5 -7
  3. test_agent.py +44 -14
app.py CHANGED
@@ -3,6 +3,9 @@ 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()
@@ -16,6 +19,10 @@ if not openai_api_key:
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
@@ -75,3 +82,30 @@ async def end_chat():
75
  session_id = cl.user_session.get("id")
76
  if session_id in chat_histories:
77
  del chat_histories[session_id]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  from agent_graph import agent_node
4
  from dotenv import load_dotenv # Import dotenv
5
  from typing import List, Dict
6
+ import gradio as gr
7
+ from test_agent import process_query
8
+ import logging
9
 
10
  # Load environment variables from .env file
11
  load_dotenv()
 
19
  # Store chat history
20
  chat_histories: Dict[str, List[Dict[str, str]]] = {}
21
 
22
+ # Set up logging
23
+ logging.basicConfig(level=logging.INFO)
24
+ logger = logging.getLogger(__name__)
25
+
26
  @cl.on_chat_start
27
  async def start_chat():
28
  # Initialize empty chat history for this session
 
82
  session_id = cl.user_session.get("id")
83
  if session_id in chat_histories:
84
  del chat_histories[session_id]
85
+
86
+ def respond(message, history):
87
+ """Process the user's message and return the response."""
88
+ try:
89
+ logger.info(f"Received message: {message}")
90
+ response = process_query(message)
91
+ logger.info(f"Sending response: {response}")
92
+ return response
93
+ except Exception as e:
94
+ error_msg = f"Error processing message: {str(e)}"
95
+ logger.error(error_msg)
96
+ return error_msg
97
+
98
+ # Create the Gradio interface
99
+ demo = gr.ChatInterface(
100
+ fn=respond,
101
+ title="AI Stock Agent",
102
+ description="Ask me about stock prices and buying power calculations!",
103
+ examples=[
104
+ "What is the current price of AAPL?",
105
+ "How many shares of MSFT can I buy with $5000?",
106
+ ],
107
+ )
108
+
109
+ # Launch the interface
110
+ if __name__ == "__main__":
111
+ demo.launch()
requirements.txt CHANGED
@@ -1,7 +1,5 @@
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
 
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
 
 
test_agent.py CHANGED
@@ -3,16 +3,26 @@ 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
 
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,13 +39,33 @@ 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)
 
 
 
 
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
  ]
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)