Download utils.py from shkkonda/AutoSDR: direct link, hf CLI and curl.
- Browser
- Download file 5.5 kB
-
https://huggingface.co/spaces/shkkonda/AutoSDR/resolve/main/utils.py
- Command line
-
hf download hf://spaces/shkkonda/AutoSDR/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/shkkonda/AutoSDR/resolve/main/utils.py
5.5 kB
| 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 --- | |
| 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) |