-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathprompt_function.py
More file actions
141 lines (112 loc) · 4.83 KB
/
prompt_function.py
File metadata and controls
141 lines (112 loc) · 4.83 KB
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
import uno
import unohelper
import json
import urllib.request
import os
from org.extension.localwriter.PromptFunction import XPromptFunction
from llm import build_api_request, make_ssl_context
class PromptFunction(unohelper.Base, XPromptFunction):
def __init__(self, ctx):
self.ctx = ctx
def getProgrammaticFunctionName(self, aDisplayName):
if aDisplayName == "PROMPT":
return "prompt"
return ""
def getDisplayFunctionName(self, aProgrammaticName):
if aProgrammaticName == "prompt":
return "PROMPT"
return ""
def getFunctionDescription(self, aProgrammaticName):
if aProgrammaticName == "prompt":
return "Generates text using an LLM."
return ""
def getArgumentDescription(self, aProgrammaticName, nArgument):
if aProgrammaticName == "prompt":
if nArgument == 0:
return "The prompt to send to the LLM."
return ""
def getArgumentName(self, aProgrammaticName, nArgument):
if aProgrammaticName == "prompt":
if nArgument == 0:
return "message"
return ""
def hasFunctionWizard(self, aProgrammaticName):
return True
def getArgumentCount(self, aProgrammaticName):
if aProgrammaticName == "prompt":
return 1
return 0
def getArgumentIsOptional(self, aProgrammaticName, nArgument):
return False
def getProgrammaticCategoryName(self, aProgrammaticName):
return "Add-In"
def getDisplayCategoryName(self, aProgrammaticName):
return "Add-In"
def getLocale(self):
return uno.createUnoStruct("com.sun.star.lang.Locale", "en", "US", "")
def setLocale(self, locale):
pass
def load(self, xSomething):
pass
def unload(self):
pass
def prompt(self, message):
try:
endpoint = str(self.get_config("endpoint", "http://localhost:11434"))
api_key = str(self.get_config("api_key", ""))
api_type = str(self.get_config("api_type", "completions")).lower()
model = str(self.get_config("model", ""))
is_owui = self.get_config("is_openwebui", False)
openai_compat = self.get_config("openai_compatibility", False)
system_prompt = str(self.get_config("extend_selection_system_prompt", ""))
max_tokens = self.get_config("extend_selection_max_tokens", 70)
request = build_api_request(
message, endpoint, api_key, api_type, model,
is_owui, openai_compat, system_prompt, int(max_tokens))
# Override stream to False — Calc needs the full response at once
body = json.loads(request.data.decode('utf-8'))
body['stream'] = False
request.data = json.dumps(body).encode('utf-8')
disable_ssl = self.get_config("disable_ssl_verification", False)
ssl_ctx = make_ssl_context(disable_ssl)
with urllib.request.urlopen(request, context=ssl_ctx) as response:
response_json = json.loads(response.read().decode('utf-8'))
if api_type == "chat":
return response_json["choices"][0]["message"]["content"]
else:
return response_json["choices"][0]["text"]
except urllib.error.HTTPError as e:
error_body = e.read().decode('utf-8')
return f"HTTP Error {e.code}: {error_body}"
except urllib.error.URLError as e:
return f"Connection error: {e.reason}"
except Exception as e:
return f"Error: {e}"
def get_config(self, key, default):
name_file = "localwriter.json"
path_settings = self.ctx.getServiceManager().createInstanceWithContext(
'com.sun.star.util.PathSettings', self.ctx)
user_config_path = getattr(path_settings, "UserConfig")
if user_config_path.startswith('file://'):
user_config_path = str(uno.fileUrlToSystemPath(user_config_path))
config_file_path = os.path.join(user_config_path, name_file)
if not os.path.exists(config_file_path):
return default
try:
with open(config_file_path, 'r') as file:
config_data = json.load(file)
except (IOError, json.JSONDecodeError):
return default
return config_data.get(key, default)
def getImplementationName(self):
return "org.extension.localwriter.PromptFunction"
def supportsService(self, name):
return name in self.getSupportedServiceNames()
def getSupportedServiceNames(self):
return ("com.sun.star.sheet.AddIn",)
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
PromptFunction,
"org.extension.localwriter.PromptFunction",
("com.sun.star.sheet.AddIn",),
)