import json import os from openai import OpenAI from dotenv import load_dotenv import hashlib import requests from supabase import Client load_dotenv() GRADIO_CUSTOM_CSS = """ .contain { display: flex; flex: 1; flex-direction: column; } .gradio-container { background-color: #F8F9F9; height: 100vh !important; margin: 0 !important;} .gradio-container .main { padding: 0 !important; } .main { display: flex; flex: 1; } #component-0 { height: 100%; } #chatbot { flex-grow: 1; overflow: auto;} """ get_user_info = """ function(message, chat_history, user_info) { return [message, chat_history, window.gradioUserInfo]; } """ def retrieve_or_create_thread(user_uuid: str, company_uuid: str, supabase_client: Client, openai_client: OpenAI): key = f"{user_uuid}:{company_uuid}" # Query the database for the thread data = supabase_client.table('thread_ids').select( 'thread_id').eq('key', key).execute() if data.data: # Thread exists, retrieve it thread_id = data.data[0]['thread_id'] print(f"Retrieving thread {thread_id}") thread = openai_client.beta.threads.retrieve(thread_id) return thread else: # No thread found, create a new thread print("No thread found, creating new thread") thread = openai_client.beta.threads.create() # Insert the new thread into the database supabase_client.table('thread_ids').insert( {'key': key, 'thread_id': thread.id}).execute() return thread def delete_thread(user_uuid: str, company_uuid: str, supabase_client: Client, openai_client: OpenAI): key = f"{user_uuid}:{company_uuid}" data = supabase_client.table('thread_ids').select( 'thread_id').eq('key', key).execute() if data.data: thread_id = data.data[0]['thread_id'] openai_client.beta.threads.delete(thread_id) supabase_client.table('thread_ids').delete().eq('key', key).execute() print(f"Deleted thread {thread_id}") else: print("No thread found to delete") def check_secret_key(secret_key: str, supabase_client: Client) -> bool: secret_key_hash = hashlib.sha256(secret_key.encode()).hexdigest() data = supabase_client.table('secrets').select( 'value').eq('key', 'hf_secret').execute() if data.data: stored_hash = data.data[0]['value'] if stored_hash == secret_key_hash: print('Secret key matches. Continuing...') return True else: raise ValueError( "The secret key provided does not match the stored secret key. Aborting.") else: raise ValueError( "The secret key provided does not match the stored secret key. Aborting.") def process_tool_call(tool_call): try: print( f"Processing tool call {tool_call.function.name}({tool_call.function.arguments})") func_to_call = globals().get(tool_call.function.name) if not func_to_call: raise ValueError( f"Function {tool_call.function.name} is not defined") args_dict = json.loads(tool_call.function.arguments) result = func_to_call(**args_dict) return { "tool_call_id": tool_call.id, "output": json.dumps(result) } except Exception as exc: # Serialize the exception information into a simple dictionary # that can be pickled and sent back to the main process. return { "tool_call_id": tool_call.id, "output": f"Error processing tool call {tool_call.id}: {str(exc)}", "error": { "message": str(exc), } } def call_function_with_args(func_object): # Extract the function by its name func_to_call = globals().get(func_object.name) # If the function does not exist, handle the error appropriately if not func_to_call: raise ValueError(f"Function {func_object.name} is not defined") # Convert the arguments from JSON to a dictionary args_dict = json.loads(func_object.arguments) # Call the function with the unpacked arguments return func_to_call(**args_dict) def make_liveplan_request(method, endpoint, auth_token, csrf_token, payload=None) -> str: """ Makes a request to the LivePlan API. """ base_url = os.getenv('LIVEPLAN_URL') url = f"{base_url}/seam/resource/restv1{endpoint}" headers = { "Content-Type": "application/json", "X-Csrf-Token": csrf_token, "accept": "application/json", } cookies = { "auth": auth_token, "csrf-token": csrf_token, } if method.upper() == 'GET': response = requests.get(url, headers=headers, cookies=cookies) elif method.upper() == 'POST': response = requests.post(url, headers=headers, cookies=cookies, json=payload) else: raise ValueError("Unsupported method") if response.status_code >= 400: raise ValueError( f"Request failed with status code {response.status_code} and message {response.text}") return response.text