File size: 8,799 Bytes
579038a
4c7ba35
579038a
 
3239ea8
c7722c9
4c7ba35
579038a
 
4c7ba35
 
579038a
40cf0a9
 
 
 
 
 
 
 
 
 
 
 
eb2ec81
579038a
 
 
 
 
 
5362085
 
579038a
 
5362085
579038a
 
5362085
579038a
 
5362085
579038a
 
8ebd080
579038a
4c7ba35
 
 
 
579038a
 
 
5362085
 
2d842c0
 
 
 
 
 
 
579038a
 
 
4c7ba35
 
 
 
579038a
 
4751587
c7722c9
 
 
 
 
4751587
c7722c9
4751587
5362085
4751587
c7722c9
4751587
c7722c9
 
 
3239ea8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579038a
 
 
 
 
 
 
 
 
 
 
 
 
 
3239ea8
 
 
 
 
 
 
c7722c9
579038a
c7722c9
579038a
c7722c9
579038a
c7722c9
bc32962
c7722c9
bc32962
c7722c9
bc32962
c7722c9
579038a
c7722c9
579038a
 
 
 
4751587
c7722c9
 
8ebd080
579038a
5362085
 
 
 
579038a
c7722c9
 
579038a
c7722c9
579038a
 
 
 
 
 
 
 
 
 
 
 
 
8ebd080
 
5362085
 
579038a
 
 
 
 
 
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
import os
import gradio as gr
import openai
from langdetect import detect
from fpdf import FPDF  # To generate PDF
import json

# Set up OpenAI API with your custom endpoint
openai.api_key = os.getenv("API_KEY")
openai.api_base = "https://api.groq.com/openai/v1"

# Import datasets from the Python files in your project
from company_profile import company_profile
from workforce import workforce
from financials import financials
from investors import investors
from products_services import products_services
from market_trends import market_trends
from partnerships_collaborations import partnerships_collaborations
from legal_compliance import legal_compliance
from customer_insights import customer_insights
from news_updates import news_updates
from social_media import social_media
from tech_stack import tech_stack

# Command handler for specific queries
def command_handler(user_input):
    if user_input.lower().startswith("define "):
        term = user_input[7:].strip()
        definitions = {
            "market analysis": (
                "Market analysis evaluates a business's position by studying competitors, trends, and customer behavior. "
                "It helps in crafting strategies for growth. 📊"
            ),
            "financials": (
                "Financial analysis examines profit margins, revenues, and expenses to determine fiscal health and sustainability. 💵"
            ),
            "investors": (
                "Investors provide capital in exchange for equity or debt, enabling business growth and scaling. 🏦"
            )
        }
        return definitions.get(term.lower(), "Definition not available. Let’s dive into your query!")
    return None

# Function to get the response from OpenAI with professionalism and energy
def get_groq_response(message, user_language):
    try:
        response = openai.ChatCompletion.create(
            model="llama-3.1-70b-versatile",
            messages=[
                {
                    "role": "system",
                    "content": (
                        f"You are a professional and concise Private Market Analyst AI. Your task is to explain market trends, "
                        f"company insights, and investment strategies in a clear, impactful, and concise manner. "
                        f"Keep the responses brief yet informative, focusing on the key points. Always maintain professionalism. "                      
                        f"1. **Accuracy**: Provide reliable, data-backed insights based on market trends, company profiles, and financial data.\n"
                        f"2. **Real-Time Updates**: Continuously track and update insights from the latest company developments, financial reports, and market movements.\n"
                        f"3. **Customizable**: Offer tailored responses based on user preferences such as specific industries, risk levels, and deal types.\n"
                        f"4. **Confidentiality**: Ensure that all information and insights provided remain secure and confidential, respecting user privacy.\n"
                        f"5. **Explainability**: Provide clear, understandable, and actionable explanations for every AI-generated insight, ensuring users can easily follow the rationale behind the analysis.\n\n"
                        f"Your primary goal is to assist users by providing accurate, personalized, and actionable insights related to private markets. Always maintain professionalism and conciseness. Ensure that responses are easy to interpret, and avoid jargon whenever possible.\n\n"
                    )
                },
                {"role": "user", "content": message}
            ]
        )
        return response.choices[0].message["content"]
    except Exception as e:
        return f"Oops, looks like something went wrong! Error: {str(e)}"

# Function to format the response data in a readable and highlighted form
def format_response(data):
    if not data:
        return "No data available for this query."

    if isinstance(data, dict):
        formatted_response = "### Insights:\n\n"
        for key, value in data.items():
            formatted_response += f"**{key.capitalize()}**: {value}\n\n"
    elif isinstance(data, list):
        formatted_response = "### Insights:\n\n" + "\n".join(f"{idx+1}. {item}" for idx, item in enumerate(data))
    else:
        formatted_response = f"### Key Insights:\n\n{data}"

    return formatted_response.strip()

# Function to generate PDF based on investment data
def generate_pdf(company_name, investment_data):
    pdf = FPDF()
    pdf.set_auto_page_break(auto=True, margin=15)
    pdf.add_page()

    # Title
    pdf.set_font("Arial", 'B', 16)
    pdf.cell(200, 10, f"Investment Report for {company_name}", ln=True, align="C")

    # Adding investment data
    pdf.set_font("Arial", size=12)
    pdf.ln(10)
    pdf.multi_cell(0, 10, f"Investment Data:\n\n{investment_data}")

    # Save PDF to file
    pdf_output = f"{company_name}_investment_report.pdf"
    pdf.output(pdf_output)

    return pdf_output

# Function to handle the interaction and queries
def market_analysis_agent(user_input, history=[]):
    try:
        # Detect the language of the user's input
        detected_language = detect(user_input)
        user_language = "Hindi" if detected_language == "hi" else "English"
        
        # Handle special commands like "Define [term]"
        command_response = command_handler(user_input)
        if command_response:
            history.append((user_input, command_response))
            return history, history
        
        # Handle private market queries with datasets
        if "create a pdf" in user_input.lower() and "investment" in user_input.lower():
            company_name = "Razorpay"  # Example; in real scenario, extract from user input
            investment_data = "Investment data for Razorpay will go here."  # Replace with actual data retrieval logic
            pdf_output = generate_pdf(company_name, investment_data)
            return history, gr.File(pdf_output)  # Returning the generated PDF file

        elif "company" in user_input.lower():
            response = company_profile
        elif "financials" in user_input.lower():
            response = financials
        elif "investors" in user_input.lower():
            response = investors
        elif "products" in user_input.lower():
            response = products_services
        elif "news" in user_input.lower() or "updates" in user_input.lower():
            response = news_updates
        elif "legal" in user_input.lower() or "compliance" in user_input.lower():
            response = legal_compliance
        elif "social media" in user_input.lower() or "instagram" in user_input.lower() or "linkedin" in user_input.lower() or "twitter" in user_input.lower():
            response = social_media
        elif "workforce" in user_input.lower():
            response = workforce
        else:
            # Get dynamic AI response if query doesn't match predefined terms
            response = get_groq_response(user_input, user_language)

        # Format the response for easy readability and highlighting
        formatted_response = format_response(response)

        # Add some professional and engaging replies for the user
        cool_replies = [
            "Insightful! Let's keep going! 🔍",
            "Good question! More insights ahead. 📈",
            "You're on the right track. Let’s keep this going. 🧠",
            "Great focus! Let’s explore further. 💡"
        ]
        formatted_response += f"\n{cool_replies[hash(user_input) % len(cool_replies)]}"

        # Add to chat history
        history.append((user_input, formatted_response))
        return history, history

    except Exception as e:
        return [(user_input, f"Oops, something went wrong: {str(e)}")], history

# Gradio Interface setup
chat_interface = gr.Interface(
    fn=market_analysis_agent,  # Function for handling user interaction
    inputs=["text", "state"],  # Inputs: user message and chat history
    outputs=["chatbot", "state"],  # Outputs: chatbot messages and updated history
    live=False,  # Disable live responses; show after submit
    title="Private Market AI Agent",  # Title of the app
    description=(
        "Welcome to your professional Private Market Analyst AI! 📊\n\n"
        "Ask me anything about market trends, company profiles, financial analysis, investors, and more! "
        "I’ll provide you with concise insights that are informative and to the point, helping you make well-informed decisions. "
        "Let's break down market complexities with clarity. 🔍"
    )
)

# Launch the Gradio interface
if __name__ == "__main__":
    chat_interface.launch()