import json import os from datetime import datetime from typing import Dict, List import requests import streamlit as st from gtts import gTTS from openai import OpenAI api_key = os.environ["API_KEY"] def invoke_search_api( api_key: str, query: str, location: str = "New York, New York, United States", num: int = 10, ) -> Dict[str, any]: """ Invoke the Vitanexus SearchBot API to retrieve search results based on a query and location. Args: api_key (str): The API key for authenticating the request. query (str): The search query string. location (str, optional): The location context for the search. Default is "New York, New York, United States". num (int, optional): The number of search results to retrieve. Default is 10. Returns: Dict[str, any]: A dictionary containing the JSON response from the API. If an error occurs, returns a dictionary with error details. """ # Construct the API endpoint URL with the provided API key url = f"https://vitanexus-searchbot-v2.azurewebsites.net/api/http_trigger?code={api_key}" # Create the JSON payload for the POST request payload = {"query": query, "location": location, "num": num} try: # Send a POST request to the API endpoint with the JSON payload response = requests.post(url, json=payload) # Raise an exception for any HTTP error responses response.raise_for_status() # Return the parsed JSON response if the request is successful return response.json() except requests.exceptions.RequestException as e: # Handle any request exceptions and return an error message print(f"An error occurred: {e}") return {"status": "error", "message": str(e)} # Credit: Time def current_year() -> int: """ Returns the current year as an integer. This function fetches the current date and time, then extracts and returns the year from the current date. Returns: int: The current year. """ # Get the current date and time now: datetime = datetime.now() # Extract and return the current year return now.year # Save audio def save_to_audio(text: str) -> None: """ Converts the given text to an audio file. This function uses Google Text-to-Speech (gTTS) to convert the provided text into speech and saves it as an MP3 file named 'output.mp3'. Parameters: text (str): The text to be converted to speech. """ # Create a gTTS object with the specified text and language ('en' for English) tts = gTTS(text=text, lang="en") # 'en' for English, change as needed # Save the generated speech to an audio file named "output.mp3" tts.save("output.mp3") class ChatBot: """ A simple chatbot class that interacts with the OpenAI API to generate responses based on user prompts and maintains a conversation history. """ def __init__(self): """ Initialize the ChatBot instance by creating an OpenAI client and setting up an initial conversation history with the role of 'system' as a helpful assistant. """ self.client = OpenAI(api_key=os.environ["OPENAI_API_KEY"]) self.history = [{"role": "system", "content": "You are a helpful assistant."}] def generate_response(self, prompt: str) -> str: """ Generate a response from the chatbot based on the user's prompt. Args: prompt (str): The input message from the user. Returns: str: The chatbot's response to the provided prompt. """ # Add the user's prompt to the history with the role of 'user'. self.history.append({"role": "user", "content": prompt}) # Request a completion from the OpenAI API using the conversation history. completion = self.client.chat.completions.create( model="gpt-3.5-turbo", # NOTE: feel free to change it to gpt-4, or gpt-4o messages=self.history, ) # Extract the assistant's response from the completion result. response = completion.choices[0].message.content # Add the assistant's response to the history with the role of 'assistant'. self.history.append({"role": "assistant", "content": response}) # Return the generated response. return response def get_history(self) -> list: """ Retrieve the conversation history between the user and the chatbot. Returns: list: A list of messages representing the conversation history. """ return self.history