-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGitAccess.py
More file actions
328 lines (290 loc) · 10.9 KB
/
GitAccess.py
File metadata and controls
328 lines (290 loc) · 10.9 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""
title: GitAccess
author: ErrorRExorY/CptExorY
author_url: https://pascal-frerks.de
git_url: https://github.com/WhyWaitServices/open-webui-gitaccess.git
description: This Tool allows the LLM to connect to one GitHub Repo to fetch its contents to ask it about it and use it to have your model always have the current state of the project
required_open_webui_version: 0.6.0
version: 0.1.0
licence: MIT
"""
from typing import Any, Optional, Callable, Awaitable
from pydantic import BaseModel, Field, ValidationError
import os
import requests
from datetime import datetime
class Filter:
def __init__(self):
pass
def inlet(self, body: dict) -> dict:
body["sanitized"] = "".join(e for e in body.get("input", "") if e.isalnum())
return body
def outlet(self, body: dict) -> dict:
for message in body.get("messages", []):
if message.get("role") == "assistant":
message["content"] = f"**{message['content']}**"
return body
class RepositoryPipe:
class Valves(BaseModel):
MODEL_ID: str = Field(default="github_repo")
def __init__(self):
self.valves = self.Valves()
def pipe(self, body: dict) -> str:
repo_url = body.get("repo_url", "")
return f"Fetched content from {repo_url}"
class Action:
def __init__(self):
pass
def create_action_button(self):
return {
"type": "button",
"title": "Analyze Repo",
"action": "analyze_repository",
}
async def emit_citation(__event_emitter__, content, title, url):
await __event_emitter__(
{
"type": "citation",
"data": {
"document": [content],
"metadata": [
{"date_accessed": datetime.now().isoformat(), "source": title}
],
"source": {"name": title, "url": url},
},
}
)
class Tools:
class Valves(BaseModel):
access_token: str = Field(
default=os.getenv("GITHUB_ACCESS_TOKEN", ""),
description="GitHub Personal Access Token (needs repo access)",
json_schema_extra={"secret": True},
)
repo_url: str = Field(
default=os.getenv("GITHUB_REPO_URL", ""),
description="Default GitHub repository to access (in the format 'username/repo')",
)
class UserValves(BaseModel):
max_files: int = Field(
default=20,
description="Maximum number of files per directory (optional to limit)",
)
truncate_content: bool = Field(
default=True,
description="Truncate large files for better readability",
)
max_content_length: int = Field(
default=5000,
description="Maximum character length for file contents when truncation is enabled",
)
def __init__(self):
try:
self.valves = self.Valves()
except ValidationError as e:
raise ValueError(f"Configuration error in Valves: {e}")
self.user_valves = self.UserValves()
self.filter = Filter()
self.pipe = RepositoryPipe()
self.action = Action()
self.citation = False
async def _fetch_directory_contents(
self,
api_url: str,
headers: dict,
__event_emitter__: Optional[Callable[[Any], Awaitable[None]]] = None,
) -> Any:
if __event_emitter__:
await __event_emitter__(
{
"type": "status",
"data": {
"description": f"Fetching contents from {api_url}...",
"done": False,
"hidden": False,
},
}
)
response = requests.get(api_url, headers=headers)
if response.status_code != 200:
return f"Error fetching from {api_url}: {response.status_code} - {response.text}"
items = response.json()
result = []
file_count = 0
for item in items:
if file_count >= self.user_valves.max_files:
break
if item["type"] == "dir":
if __event_emitter__:
await __event_emitter__(
{
"type": "status",
"data": {
"description": f"Entering directory: {item['name']}...",
"done": False,
},
}
)
sub_contents = await self._fetch_directory_contents(
item["url"], headers, __event_emitter__
)
result.append(
{
"name": item["name"],
"type": "dir",
"path": item["path"],
"contents": sub_contents,
}
)
elif item["type"] == "file":
file_dict = {
"name": item["name"],
"type": "file",
"path": item["path"],
}
if __event_emitter__:
await __event_emitter__(
{
"type": "status",
"data": {
"description": f"Fetching file: {item['name']}...",
"done": False,
},
}
)
if item.get("download_url"):
file_response = requests.get(item["download_url"])
if file_response.status_code == 200:
content = file_response.text
if (
self.user_valves.truncate_content
and len(content) > self.user_valves.max_content_length
):
content = (
content[: self.user_valves.max_content_length] + "..."
)
file_dict["content"] = content
else:
file_dict["content_error"] = (
f"Error fetching file content: {file_response.status_code}"
)
result.append(file_dict)
file_count += 1
else:
result.append(
{
"name": item.get("name"),
"type": item.get("type"),
"path": item.get("path"),
"detail": item,
}
)
if __event_emitter__:
await __event_emitter__(
{
"type": "status",
"data": {
"description": f"Finished fetching from {api_url}.",
"done": True,
"hidden": False,
},
}
)
return result
async def fetch_repo_content(
self, __event_emitter__: Optional[Callable[[Any], Awaitable[None]]] = None
):
if not self.valves.access_token or not self.valves.repo_url:
msg = "Access token or repo URL is not properly configured."
if __event_emitter__:
await __event_emitter__(
{"type": "error", "data": {"description": msg, "done": True}}
)
return msg
headers = {
"Authorization": f"token {self.valves.access_token}",
"Accept": "application/vnd.github.v3+json",
}
if "/" not in self.valves.repo_url or len(self.valves.repo_url.split("/")) != 2:
msg = "The repo_url is not in the expected 'username/repo' format."
if __event_emitter__:
await __event_emitter__(
{"type": "error", "data": {"description": msg, "done": True}}
)
return msg
repo_api_url = f"https://api.github.com/repos/{self.valves.repo_url}/contents"
if __event_emitter__:
await __event_emitter__(
{
"type": "status",
"data": {
"description": "Fetching repository contents...",
"done": False,
},
}
)
contents = await self._fetch_directory_contents(
repo_api_url, headers, __event_emitter__
)
if __event_emitter__:
await __event_emitter__(
{
"type": "status",
"data": {
"description": "Repository contents fetched successfully.",
"done": True,
"hidden": False,
},
}
)
messages_wrapper = {"messages": contents}
self.filter.outlet(messages_wrapper)
if contents:
repo_name = self.valves.repo_url.split("/")[1]
for item in contents:
if item.get("type") == "file":
file_name = item.get("name", "Unknown")
file_url = item.get("url", "Unknown")
await emit_citation(
__event_emitter__,
[item.get("content", "")],
f"Repo: {repo_name}, File: {file_name}",
file_url,
)
return messages_wrapper.get("messages")
async def analyze_repository(
self,
user: dict = {},
__event_emitter__: Optional[Callable[[Any], Awaitable[None]]] = None,
):
try:
if __event_emitter__:
await __event_emitter__(
{
"type": "status",
"data": {
"description": "Starting repository analysis...",
"done": False,
},
}
)
content = await self.fetch_repo_content(__event_emitter__)
if __event_emitter__:
await __event_emitter__(
{
"type": "status",
"data": {
"description": "Analysis completed successfully.",
"done": True,
"hidden": False,
},
}
)
return f"Repository contents:\n{content}"
except Exception as e:
error_msg = f"An error occurred: {e}"
if __event_emitter__:
await __event_emitter__(
{"type": "error", "data": {"description": error_msg, "done": True}}
)
return error_msg