Spaces:
Sleeping
Sleeping
File size: 7,171 Bytes
35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 c69bcce 35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 62ceac1 35aecd6 62ceac1 35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 a0720d6 35aecd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | import os
import json
from duckduckgo_search import DDGS
from groq import Groq
import gradio as gr
from typing import List, Tuple
# Initialize clients
ddgs = DDGS()
GROQ_API_KEY = "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" # Replace with your API key
groq_client = Groq(api_key=GROQ_API_KEY)
# Chatbot system prompt with your schema
CHATBOT_SYSTEM_PROMPT = """
You are a financial education chatbot that responds in strict JSON format using this schema:
{
"response": {
"answer": "string (direct 4-5 sentence answer)",
"explanation": "string (detailed 3-5 paragraph explanation)",
"related_topics": ["string"]
},
"actionable_steps": {
"steps": ["string (numbered steps)"]
},
"warnings_disclaimers": {
"financial_risk_warning": "string",
"legal_disclaimer": "string"
},
"sources_references": ["string (URLs)"],
"suggested_followups": ["string (questions)"]
}
Rules:
1. ALWAYS maintain valid JSON
2. For financial queries:
- Provide both concise answers and detailed explanations
- Include practical steps
- Add relevant warnings
3. For non-financial queries:
- Politely redirect to financial topics
- Suggest related financial questions
4. Never return non-JSON content
"""
# Enhanced financial search
def financial_chatbot_search(query):
try:
results = ddgs.text(
keywords=f"{query} site:investopedia.com OR site:sec.gov OR site:consumerfinance.gov",
region="wt-wt",
safesearch="moderate",
max_results=5
)
# Extract and format sources
sources = []
for r in results:
source = {
"title": r['title'],
"url": r['href'],
"snippet": r['body'][:200] + "..." if len(r['body']) > 200 else r['body']
}
sources.append(f"{source['title']} - {source['url']}")
return sources
except Exception as e:
return ["Error: Unable to retrieve sources"]
# Response generator using your schema
def generate_chatbot_response(user_query):
# Get relevant sources
sources = financial_chatbot_search(user_query)
try:
response = groq_client.chat.completions.create(
messages=[
{"role": "system", "content": CHATBOT_SYSTEM_PROMPT},
{"role": "user", "content": user_query},
{"role": "assistant", "content": f"Relevant sources: {str(sources)}"}
],
model="llama3-70b-8192",
response_format={"type": "json_object"},
temperature=0.4,
max_tokens=2048
)
# Parse and pretty-print JSON
json_response = json.loads(response.choices[0].message.content)
return json.dumps(json_response, indent=2)
except Exception as e:
return json.dumps({
"error": "Response generation failed",
"details": str(e)
}, indent=2)
def format_response(json_response: str) -> str:
"""Formats the JSON response into a readable string for the chat interface."""
try:
response_data = json.loads(json_response)
# Build the formatted response
formatted = []
# Main answer
if 'response' in response_data:
resp = response_data['response']
formatted.append(f"**Answer:** {resp.get('answer', '')}")
formatted.append(f"\n**Explanation:**\n{resp.get('explanation', '')}")
if 'related_topics' in resp and resp['related_topics']:
formatted.append(f"\n**Related Topics:**\n- " + "\n- ".join(resp['related_topics']))
# Actionable steps
if 'actionable_steps' in response_data and response_data['actionable_steps'].get('steps'):
formatted.append("\n**Actionable Steps:**")
for i, step in enumerate(response_data['actionable_steps']['steps'], 1):
formatted.append(f"{i}. {step}")
# Warnings
if 'warnings_disclaimers' in response_data:
warnings = response_data['warnings_disclaimers']
if warnings.get('financial_risk_warning'):
formatted.append(f"\n **Warning:** {warnings['financial_risk_warning']}")
if warnings.get('legal_disclaimer'):
formatted.append(f"\n **Disclaimer:** {warnings['legal_disclaimer']}")
# Sources
if 'sources_references' in response_data and response_data['sources_references']:
formatted.append("\n**Sources & References:**")
for source in response_data['sources_references']:
formatted.append(f"- {source}")
# Follow-ups
if 'suggested_followups' in response_data and response_data['suggested_followups']:
formatted.append("\n**Suggested Follow-up Questions:**")
for i, question in enumerate(response_data['suggested_followups'], 1):
formatted.append(f"{i}. {question}")
return "\n".join(formatted)
except json.JSONDecodeError:
return json_response
def chatbot_response(message: str, history: List[Tuple[str, str]]) -> Tuple[List[Tuple[str, str]], str]:
"""Handles the chat interaction, maintains history, and generates responses."""
# Generate response using your existing function
json_response = generate_chatbot_response(message)
# Format the JSON response for display
formatted_response = format_response(json_response)
# Update the history with both user message and bot response
updated_history = history + [(message, formatted_response)]
# Return the updated history and clear the input
return updated_history, ""
def clear_chat() -> List[Tuple[str, str]]:
"""Clears the chat history."""
return []
# Create the Gradio interface
with gr.Blocks(title="Financial Education Chatbot") as demo:
gr.Markdown("""
# Financial Education Chatbot
Get expert financial advice with sources and actionable steps. Ask me about investing, retirement, taxes, or any money-related topic!
""")
# Chat interface
chatbot = gr.Chatbot(
height=600,
bubble_full_width=False,
avatar_images=(
"https://cdn-icons-png.flaticon.com/512/4712/4712035.png", # User avatar
"https://cdn-icons-png.flaticon.com/512/4712/4712139.png" # Bot avatar
)
)
with gr.Row():
msg = gr.Textbox(
label="Type your financial question",
placeholder="How does compound interest work?",
scale=7,
container=False
)
submit_btn = gr.Button("Submit", variant="primary", scale=1)
clear_btn = gr.Button("Clear Chat", variant="secondary", scale=1)
# Chatbot functionality
msg.submit(
fn=chatbot_response,
inputs=[msg, chatbot],
outputs=[chatbot, msg]
)
submit_btn.click(
fn=chatbot_response,
inputs=[msg, chatbot],
outputs=[chatbot, msg]
)
clear_btn.click(
fn=clear_chat,
inputs=None,
outputs=[chatbot]
)
# Launch the interface
if __name__ == "__main__":
demo.launch() |