defgee's picture
Update app.py
10e2d2e verified
Raw
History Blame Contribute Delete
8.25 kB
from seasonality import seasonal_trades
from news_scraper import fetch_news_summary
from sentiment_analyzer import fetch_market_sentiment
from economic_calendar import econ_cal
from ta import fetch_technical_analysis
import openai
import os
from openai import OpenAIError
from IPython.display import Markdown, display
import gradio as gr
api_key= os.getenv("OPENAI_API_KEY")
openai.api_key = api_key
def seasonality():
summary =seasonal_trades()
return summary
def news():
url = "https://www.forexlive.com"
news_summary = fetch_news_summary(url)
return news_summary
def sentiment():
url = "https://www.forexlive.com"
news_sentiment = fetch_market_sentiment(url)
return news_sentiment
def economic_calendar():
calendar=econ_cal()
return calendar
def technical():
url = "https://www.forexlive.com/technical-analysis"
technical_analysis = fetch_technical_analysis(url)
return technical_analysis
system_message='''you are called PipNode Trading Assistant and you help traders analyze the financial market. be truthful with your answers. especially re
related to asset prices.you also never perform technical analysis. you only analyze sentiments,seasonality,economic calendar and market news
You are a professional and knowledgeable trading assistant on Pipnode.com, a platform specializing in seasonal trading insights and historical market data. Your primary goal is to assist traders of all experience levels by providing accurate and helpful responses. Here's how you should operate:
Only talk about pipnode when have been asked specific.
Adopt a friendly tone
Offer clear, concise, and actionable advice related to seasonal patterns, trading strategies, and market insights.
Explain how seasonal trends in financial markets work and guide users on leveraging Pipnode's tools.
Provide examples of historical market trends or scenarios when needed.
Answer questions about trading fundamentals, platform features, and how to integrate seasonal insights into broader trading strategies.
Avoid giving direct financial or investment advice, but instead focus on educating and guiding users to make informed decisions.
Maintain a friendly, professional, and approachable tone while using straightforward language that traders, beginners, and experts alike can understand.
As the AI for Pipnode, always encourage users to explore the platform's seasonal trading tools and unique features, emphasizing how it can enhance their trading decisions.
'''
cyclical_function = {
"name": "get_cyclical_data",
"description": "Fetches historically strong and weak seasonal periods. Example: if the user asks about any upcoming seasonal trades.or they ask;can you analyze eurusd for me?",
"parameters": {
"type": "object",
"properties": {}, # No properties defined
"required": [],
"additionalProperties": False
}
}
news_function = {
"name": "get_news_feed",
"description": " get the lastest forex news articles for example when clients asks 'give me forex news' or' can you give me some trading news?or 'what is the market looking like today? '",
"parameters": {
"type": "object",
"properties": {
"asset_class": {
"type": "string",
"description": "",
},
},
"required": [],
"additionalProperties": False
}
}
sentiment_function = {
"name": "get_sentiment",
"description": "user wants to know the overall or prevailing market sentiment,mood or risk tone",
"parameters": {
"type": "object",
"properties": {
"asset_class": {
"type": "string",
"description": "",
},
},
"required": [],
"additionalProperties": False
}
}
calendar_function = {
"name": "get_calendar",
"description": "user wants to know the upcoming economic events,the next NFP report, or interest rat decision",
"parameters": {
"type": "object",
"properties": {
"asset_class": {
"type": "string",
"description": "",
},
},
"required": [],
"additionalProperties": False
}
}
technical_function = {
"name": "get_technical",
"description": "user wants to know to get technical analysis for today. they may ask questions like 'can you give me technical analysis for gold?' or 'what is a strong support level for usdcad?'.be honest with your responses. if you dont have any information on the particular asset,just say so.",
"parameters": {
"type": "object",
"properties": {
"asset_class": {
"type": "string",
"description": "",
},
},
"required": [],
"additionalProperties": False
}
}
#this has to work
tools = [
{"type": "function", "function": cyclical_function},
{"type": "function", "function": news_function},
{"type": "function", "function": sentiment_function},
{"type": "function", "function": calendar_function}
#{"type": "function", "function": technical_function}
]
import openai
import traceback # Add this at the top with other imports if not already present
def chat(message, history):
try:
messages = [{"role": "system", "content": system_message}] + history + [{"role": "user", "content": message}]
try:
# First API call to OpenAI
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools
)
except OpenAIError as api_err:
print("OpenAI Initial API Call Error:", traceback.format_exc())
return f"Error processing your request: {str(api_err)}"
# Check if tool is called
if response.choices[0].finish_reason == "tool_calls":
tool_calls = response.choices[0].message.tool_calls
messages.append(response.choices[0].message) # Append AI's tool request
for tool_call in tool_calls:
tool_name = tool_call.function.name
try:
# Map tool calls to their handlers
if tool_name == "get_cyclical_data":
tool_response_content = seasonality()
elif tool_name == "get_news_feed":
tool_response_content = news()
elif tool_name == "get_sentiment":
tool_response_content = sentiment()
elif tool_name == "get_calendar":
tool_response_content = economic_calendar()
else:
tool_response_content = f"Unknown tool request: {tool_name}"
except Exception as tool_err:
tool_response_content = f"Error executing tool '{tool_name}': {str(tool_err)}"
print("Tool Execution Error:", traceback.format_exc())
# Append tool's response
tool_response = {
"role": "tool",
"content": tool_response_content,
"tool_call_id": tool_call.id
}
messages.append(tool_response)
try:
# Final API call after tool execution
final = openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
return final.choices[0].message.content
except OpenAIError as final_err:
print("OpenAI Final Response Error:", traceback.format_exc())
return f"Error generating final response: {str(final_err)}"
# If no tool call, return normal message
return response.choices[0].message.content
except Exception as unexpected_err:
print("Unexpected Error:", traceback.format_exc())
return f"An unexpected error occurred: {str(unexpected_err)}"
# Launch Gradio Interface
gr.ChatInterface(fn=chat, type="messages").launch(share=True)