File size: 5,178 Bytes
ad1cd7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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