File size: 5,495 Bytes
3319147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pandas as pd
import plotly.graph_objects as go
import time
import random
import os
import asyncio
from dotenv import load_dotenv
from typing import List, Dict
import itertools

# --- Core Backend Logic (Adapted from your FastAPI code) ---
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain.prompts import ChatPromptTemplate
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_openai import ChatOpenAI
from openai import OpenAI
from unidecode import unidecode
from langchain.tools import tool
import re

# --- 1. Environment and API Setup ---
load_dotenv()

# Ensure API keys are set
if not os.getenv("OPENAI_API_KEY") or not os.getenv("TAVILY_API_KEY"):
    raise ValueError("OPENAI_API_KEY and TAVILY_API_KEY must be set in the .env file")

if not os.getenv("OPENAI_API_KEY") or not os.getenv("DEEPSEEK_API_KEY"):
    raise ValueError("At least one API key (OPENAI_API_" \
    "KEY or DEEPSEEK_API_KEY) must be set in the .env file")

# Initialize OpenAI client for the custom tool
openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

openrouter_api_key = os.getenv("OPENROUTERS_API_KEY")

# Initilization from openrouters
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key= openrouter_api_key # Replace with your OpenRouter API key
)


# --- You can also add this helper function for clarity ---
def sanitize_text(text: str) -> str:
    """

    Cleans text by converting special Unicode characters (like smart quotes)

    into their basic ASCII equivalents.

    e.g., "WinZO’s" -> "WinZO's"

    """
    if not isinstance(text, str):
        return ""
    return unidecode(text)


# --- 2. Product Description (Hardcoded) ---
OUR_PRODUCT_DESCRIPTION = """

Our company, Start.io, offers a mobile monetization platform for publishers. 

Our primary product is a Supply-Side Platform (SSP) designed to help **mobile web publishers** 

maximize their advertising revenue and ad yield.



We achieve this by connecting them to premium global advertising demand through modern technologies, including:

- Full support for Header Bidding (Prebid.js and Amazon Transparent Ad Marketplace - TAM).

- Upcoming integration with Google's Open Bidding.



Our expertise is backed by 14 years of success in the in-app monetization market (with 500k+ app integrations), 

which we are now bringing to the mobile web space. Our ideal customer is any company that runs a popular mobile 

website and wants to increase their ad revenue. """


# --- 3. Custom LangChain Tool with gpt-4o-search-preview ---
@tool
def custom_web_researcher(query: str) -> str:
    """

    Use this tool for in-depth, real-time web research on a company.

    It can synthesize information from multiple sources to answer complex questions

    about a company's recent activities, products, values, or market position.

    This tool leverages a specialized web-browsing model to get the most relevant results.

    """
    print(f"--- Calling Custom Web Researcher with query: {query} ---")
    system_prompt = "You are a world-class web researcher. Your goal is to find the most relevant, up-to-date " \
                    "information about a company based on the user's query. Synthesize the findings into a concise " \
                    "summary. Include citations of your sources using markdown format like [Source 1](url) at the end " \
                    "of your answer. "
    try:
        completion = client.chat.completions.create(
            model=os.getenv("CUSTOM_WEB_SEARCH_MODEL_OPENROUTER"),
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": query}
            ]
        )

        # completion = openai_client.chat.completions.create(
        #     model=os.getenv("CUSTOM_WEB_SEARCH_MODEL"),
        #     messages=[
        #         {"role": "system", "content": system_prompt},
        #         {"role": "user", "content": query}
        #     ]
        # )
        response_content = completion.choices[0].message.content
        print(f"--- Custom Web Researcher Response: {response_content[:200]}... ---")
        return response_content
    except Exception as e:
        print(f"Error in custom_web_researcher: {e}")
        return "Failed to retrieve information from the custom web researcher."

# --- Helper functions ---
def get_company_name_from_email(email: str) -> str:
    if not isinstance(email, str) or '@' not in email: return ""
    try:
        domain_part = email.split('@')[1]
        company_name = domain_part.split('.')[0]
        return company_name.replace('-', ' ').title()
    except IndexError: return ""

def get_name_from_email(email: str) -> str:
    if not isinstance(email, str) or '@' not in email: return ""
    generic_prefixes = ['info', 'contact', 'sales', 'support', 'admin', 'hello']
    local_part = email.split('@')[0]
    if local_part.lower() in generic_prefixes: return ""
    name_part = re.sub(r'[\d]', '', local_part).replace('.', ' ').replace('_', ' ').replace('-', ' ')
    first_name = name_part.split(' ')[0]
    if not first_name or first_name.lower() in generic_prefixes: return ""
    return first_name.capitalize()

def sanitize_text(text: str) -> str:
    if not isinstance(text, str): return ""
    return unidecode(text)