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()