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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import requests
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
import json
|
| 5 |
+
import time
|
| 6 |
+
from typing import Dict, List
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
class FinanceAgent:
|
| 10 |
+
def __init__(self):
|
| 11 |
+
# Initialize the summarization pipeline
|
| 12 |
+
try:
|
| 13 |
+
self.summarizer = pipeline(
|
| 14 |
+
"summarization",
|
| 15 |
+
model="facebook/bart-large-cnn",
|
| 16 |
+
max_length=512,
|
| 17 |
+
min_length=100
|
| 18 |
+
)
|
| 19 |
+
except Exception as e:
|
| 20 |
+
print(f"Error loading summarization model: {e}")
|
| 21 |
+
self.summarizer = None
|
| 22 |
+
|
| 23 |
+
def search_web(self, query: str, num_results: int = 5) -> List[Dict]:
|
| 24 |
+
"""
|
| 25 |
+
Search the web using DuckDuckGo API (free alternative)
|
| 26 |
+
"""
|
| 27 |
+
try:
|
| 28 |
+
# Using DuckDuckGo Instant Answer API
|
| 29 |
+
url = "https://api.duckduckgo.com/"
|
| 30 |
+
params = {
|
| 31 |
+
'q': f"{query} finance financial",
|
| 32 |
+
'format': 'json',
|
| 33 |
+
'no_html': '1',
|
| 34 |
+
'skip_disambig': '1'
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
response = requests.get(url, params=params, timeout=10)
|
| 38 |
+
data = response.json()
|
| 39 |
+
|
| 40 |
+
results = []
|
| 41 |
+
|
| 42 |
+
# Extract abstract if available
|
| 43 |
+
if data.get('Abstract'):
|
| 44 |
+
results.append({
|
| 45 |
+
'title': data.get('Heading', 'Financial Information'),
|
| 46 |
+
'content': data.get('Abstract', ''),
|
| 47 |
+
'url': data.get('AbstractURL', '')
|
| 48 |
+
})
|
| 49 |
+
|
| 50 |
+
# Extract related topics
|
| 51 |
+
for topic in data.get('RelatedTopics', [])[:num_results-1]:
|
| 52 |
+
if isinstance(topic, dict) and topic.get('Text'):
|
| 53 |
+
results.append({
|
| 54 |
+
'title': topic.get('Text', '')[:100] + '...',
|
| 55 |
+
'content': topic.get('Text', ''),
|
| 56 |
+
'url': topic.get('FirstURL', '')
|
| 57 |
+
})
|
| 58 |
+
|
| 59 |
+
return results
|
| 60 |
+
|
| 61 |
+
except Exception as e:
|
| 62 |
+
print(f"Search error: {e}")
|
| 63 |
+
return [{'title': 'Search Error', 'content': f'Unable to search: {str(e)}', 'url': ''}]
|
| 64 |
+
|
| 65 |
+
def get_financial_context(self, topic: str) -> str:
|
| 66 |
+
"""
|
| 67 |
+
Get basic financial context for common topics
|
| 68 |
+
"""
|
| 69 |
+
financial_contexts = {
|
| 70 |
+
'stock': 'Stocks represent ownership shares in publicly traded companies. Stock prices fluctuate based on company performance, market conditions, and investor sentiment.',
|
| 71 |
+
'bond': 'Bonds are debt securities where investors lend money to entities for a defined period at a fixed interest rate.',
|
| 72 |
+
'cryptocurrency': 'Cryptocurrencies are digital assets that use cryptography for security and operate on decentralized networks.',
|
| 73 |
+
'inflation': 'Inflation is the rate at which the general level of prices for goods and services rises, eroding purchasing power.',
|
| 74 |
+
'recession': 'A recession is a significant decline in economic activity across the economy lasting more than a few months.',
|
| 75 |
+
'fed': 'The Federal Reserve is the central banking system of the United States, responsible for monetary policy.',
|
| 76 |
+
'gdp': 'Gross Domestic Product (GDP) is the total monetary value of all goods and services produced within a country.',
|
| 77 |
+
'market': 'Financial markets are platforms where buyers and sellers trade financial securities, commodities, and other assets.'
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
topic_lower = topic.lower()
|
| 81 |
+
for key, context in financial_contexts.items():
|
| 82 |
+
if key in topic_lower:
|
| 83 |
+
return context
|
| 84 |
+
|
| 85 |
+
return "This is a financial topic that may involve various economic, market, or investment-related concepts."
|
| 86 |
+
|
| 87 |
+
def summarize_content(self, content: str, max_length: int = 300) -> str:
|
| 88 |
+
"""
|
| 89 |
+
Summarize content using the transformer model
|
| 90 |
+
"""
|
| 91 |
+
if not self.summarizer or not content.strip():
|
| 92 |
+
return "Unable to generate summary."
|
| 93 |
+
|
| 94 |
+
try:
|
| 95 |
+
# Truncate content if too long
|
| 96 |
+
if len(content) > 1000:
|
| 97 |
+
content = content[:1000] + "..."
|
| 98 |
+
|
| 99 |
+
summary = self.summarizer(content, max_length=max_length, min_length=50, do_sample=False)
|
| 100 |
+
return summary[0]['summary_text']
|
| 101 |
+
except Exception as e:
|
| 102 |
+
print(f"Summarization error: {e}")
|
| 103 |
+
return f"Summary unavailable: {str(e)}"
|
| 104 |
+
|
| 105 |
+
def process_finance_query(self, prompt: str) -> str:
|
| 106 |
+
"""
|
| 107 |
+
Main function to process finance queries
|
| 108 |
+
"""
|
| 109 |
+
if not prompt.strip():
|
| 110 |
+
return "Please enter a financial topic or question."
|
| 111 |
+
|
| 112 |
+
# Add progress indicator
|
| 113 |
+
progress_msg = f"π Searching for information about: {prompt}\n\n"
|
| 114 |
+
|
| 115 |
+
# Search for relevant information
|
| 116 |
+
search_results = self.search_web(prompt)
|
| 117 |
+
|
| 118 |
+
if not search_results:
|
| 119 |
+
return progress_msg + "β No search results found. Please try a different query."
|
| 120 |
+
|
| 121 |
+
# Combine search results
|
| 122 |
+
combined_content = ""
|
| 123 |
+
sources = []
|
| 124 |
+
|
| 125 |
+
for i, result in enumerate(search_results[:3], 1): # Limit to top 3 results
|
| 126 |
+
if result.get('content'):
|
| 127 |
+
combined_content += f"\n{result['content']}\n"
|
| 128 |
+
if result.get('url'):
|
| 129 |
+
sources.append(f"{i}. {result['url']}")
|
| 130 |
+
|
| 131 |
+
# Get financial context
|
| 132 |
+
context = self.get_financial_context(prompt)
|
| 133 |
+
|
| 134 |
+
# Create comprehensive content for summarization
|
| 135 |
+
full_content = f"{context}\n\nCurrent Information:\n{combined_content}"
|
| 136 |
+
|
| 137 |
+
# Generate summary
|
| 138 |
+
summary = self.summarize_content(full_content)
|
| 139 |
+
|
| 140 |
+
# Format final response
|
| 141 |
+
response = f"""## π Financial Summary: {prompt.title()}
|
| 142 |
+
|
| 143 |
+
### π― Key Points:
|
| 144 |
+
{summary}
|
| 145 |
+
|
| 146 |
+
### π Context:
|
| 147 |
+
{context}
|
| 148 |
+
|
| 149 |
+
### π Sources:
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
if sources:
|
| 153 |
+
for source in sources:
|
| 154 |
+
response += f"\n{source}"
|
| 155 |
+
else:
|
| 156 |
+
response += "\nInformation compiled from web search results."
|
| 157 |
+
|
| 158 |
+
response += f"\n\nβ° *Generated on: {time.strftime('%Y-%m-%d %H:%M:%S')}*"
|
| 159 |
+
|
| 160 |
+
return response
|
| 161 |
+
|
| 162 |
+
# Initialize the agent
|
| 163 |
+
agent = FinanceAgent()
|
| 164 |
+
|
| 165 |
+
def finance_chat_interface(message, history):
|
| 166 |
+
"""
|
| 167 |
+
Gradio chat interface function
|
| 168 |
+
"""
|
| 169 |
+
try:
|
| 170 |
+
response = agent.process_finance_query(message)
|
| 171 |
+
return response
|
| 172 |
+
except Exception as e:
|
| 173 |
+
return f"β Error processing your request: {str(e)}\n\nPlease try again with a different query."
|
| 174 |
+
|
| 175 |
+
# Create Gradio interface
|
| 176 |
+
def create_interface():
|
| 177 |
+
with gr.Blocks(title="Financial AI Agent", theme=gr.themes.Soft()) as demo:
|
| 178 |
+
gr.Markdown("""
|
| 179 |
+
# π¦ Financial AI Agent
|
| 180 |
+
|
| 181 |
+
Ask me about any financial topic and I'll search the web for current information and provide you with a comprehensive summary.
|
| 182 |
+
|
| 183 |
+
**Examples:**
|
| 184 |
+
- "What is the current state of cryptocurrency market?"
|
| 185 |
+
- "Explain inflation and its impact on the economy"
|
| 186 |
+
- "Tell me about recent stock market trends"
|
| 187 |
+
- "What are bonds and how do they work?"
|
| 188 |
+
""")
|
| 189 |
+
|
| 190 |
+
chatbot = gr.Chatbot(
|
| 191 |
+
height=500,
|
| 192 |
+
placeholder="Financial AI Agent is ready to help with your finance questions!"
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
msg = gr.Textbox(
|
| 196 |
+
label="Ask a financial question",
|
| 197 |
+
placeholder="e.g., What is inflation and how does it affect the stock market?",
|
| 198 |
+
lines=2
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
clear = gr.Button("Clear Chat")
|
| 202 |
+
|
| 203 |
+
def user(user_message, history):
|
| 204 |
+
return "", history + [[user_message, None]]
|
| 205 |
+
|
| 206 |
+
def bot(history):
|
| 207 |
+
if history and history[-1][1] is None:
|
| 208 |
+
user_message = history[-1][0]
|
| 209 |
+
bot_message = finance_chat_interface(user_message, history[:-1])
|
| 210 |
+
history[-1][1] = bot_message
|
| 211 |
+
return history
|
| 212 |
+
|
| 213 |
+
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
|
| 214 |
+
bot, chatbot, chatbot
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 218 |
+
|
| 219 |
+
gr.Markdown("""
|
| 220 |
+
### π Notes:
|
| 221 |
+
- This agent searches the web for current financial information
|
| 222 |
+
- Summaries are generated using AI and should be verified with official sources
|
| 223 |
+
- For investment decisions, always consult with qualified financial advisors
|
| 224 |
+
""")
|
| 225 |
+
|
| 226 |
+
return demo
|
| 227 |
+
|
| 228 |
+
if __name__ == "__main__":
|
| 229 |
+
demo = create_interface()
|
| 230 |
+
demo.launch(share=True)
|