forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
430 lines (365 loc) · 15.4 KB
/
Copy pathmain.py
File metadata and controls
430 lines (365 loc) · 15.4 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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
"""
Stack Overflow Integration App for Omi.
Provides chat tools for searching Stack Overflow and reading question answers
through the public Stack Exchange API.
"""
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from html import unescape
import re
from typing import Any, Optional
import httpx
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
STACK_API_BASE_URL = "https://api.stackexchange.com/2.3"
REQUEST_TIMEOUT_SECONDS = 10
MAX_LIMIT = 10
DEFAULT_SITE = "stackoverflow"
USER_AGENT = "omi-stack-overflow-app/1.0 (https://omi.me)"
SITE_HOSTS = {
"stackoverflow": "stackoverflow.com",
"serverfault": "serverfault.com",
"superuser": "superuser.com",
"askubuntu": "askubuntu.com",
"mathoverflow": "mathoverflow.net",
"stackapps": "stackapps.com",
}
_stack_client: Optional[httpx.AsyncClient] = None
def _new_stack_client() -> httpx.AsyncClient:
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
return httpx.AsyncClient(timeout=REQUEST_TIMEOUT_SECONDS, headers=headers)
async def _get_stack_client() -> httpx.AsyncClient:
global _stack_client
if _stack_client is None or _stack_client.is_closed:
_stack_client = _new_stack_client()
return _stack_client
@asynccontextmanager
async def lifespan(_: FastAPI):
global _stack_client
_stack_client = _new_stack_client()
try:
yield
finally:
if _stack_client is not None:
await _stack_client.aclose()
app = FastAPI(
title="Omi Stack Overflow Integration",
description="Search Stack Overflow and read answers from Omi chat tools",
version="1.0.0",
lifespan=lifespan,
)
class ChatToolResponse(BaseModel):
"""Response model for Omi chat tool endpoints."""
result: Optional[str] = None
error: Optional[str] = None
def _safe_limit(limit: Any, default: int = 5) -> int:
if limit is None or limit == "":
return default
try:
limit = int(limit)
except (TypeError, ValueError):
return default
return max(1, min(limit, MAX_LIMIT))
def _safe_site(site: Optional[str]) -> str:
value = (site or DEFAULT_SITE).strip().lower()
if not re.fullmatch(r"[a-z0-9.-]{2,40}", value):
return DEFAULT_SITE
return value
def _safe_tags(tags: Any) -> Optional[str]:
if not tags:
return None
if isinstance(tags, list):
values = tags
else:
values = re.split(r"[,;]", str(tags))
cleaned = []
for tag in values:
tag = str(tag).strip().lower()
if re.fullmatch(r"[a-z0-9.+#-]{1,35}", tag):
cleaned.append(tag)
return ";".join(cleaned[:5]) if cleaned else None
def _coerce_bool(value: Any) -> Optional[bool]:
if isinstance(value, bool):
return value
if value is None or value == "":
return None
if str(value).strip().lower() in {"1", "true", "yes", "y"}:
return True
if str(value).strip().lower() in {"0", "false", "no", "n"}:
return False
return None
def _clean_text(value: Optional[str]) -> str:
if not value:
return ""
text = unescape(value)
text = re.sub(r"<pre[^>]*>|</pre>", "\n", text, flags=re.IGNORECASE)
text = re.sub(r"<code[^>]*>|</code>", "`", text, flags=re.IGNORECASE)
text = re.sub(r"</?(p|blockquote|ul|ol|li|h[1-6])[^>]*>", "\n", text, flags=re.IGNORECASE)
text = re.sub(r"<br\s*/?>", "\n", text, flags=re.IGNORECASE)
text = re.sub(r"<[^>]+>", "", text)
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def _format_date(timestamp: Optional[int]) -> str:
if not timestamp:
return "unknown date"
return datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime("%Y-%m-%d")
async def _request_json(path: str, params: Optional[dict[str, Any]] = None) -> dict[str, Any]:
client = await _get_stack_client()
response = await client.get(f"{STACK_API_BASE_URL}{path}", params=params)
response.raise_for_status()
data = response.json()
if data.get("error_id"):
raise ValueError(data.get("error_message") or "Stack Exchange API returned an error")
if data.get("backoff"):
raise ValueError(f"Stack Exchange requested a {data['backoff']} second backoff. Retry shortly.")
return data
def _question_url(site: str, question_id: Any) -> str:
if site.endswith(".stackoverflow"):
host = f"{site}.com"
elif site.endswith(".serverfault"):
host = f"{site}.com"
elif site.endswith(".superuser"):
host = f"{site}.com"
else:
host = SITE_HOSTS.get(site, f"{site}.stackexchange.com")
return f"https://{host}/questions/{question_id}"
def _format_question(item: dict[str, Any], index: int, site: str) -> str:
title = _clean_text(item.get("title")) or "Untitled question"
question_id = item.get("question_id")
score = item.get("score", 0)
answers = item.get("answer_count", 0)
views = item.get("view_count", 0)
accepted = "accepted" if item.get("is_answered") else "not accepted"
tags = ", ".join(item.get("tags", [])) or "no tags"
link = item.get("link") or _question_url(site, question_id)
return (
f"{index}. {title}\n"
f" {score} score | {answers} answers | {views} views | {accepted}\n"
f" Tags: {tags}\n"
f" {link}"
)
def _format_answer(item: dict[str, Any], index: int) -> str:
owner = item.get("owner", {}).get("display_name") or "unknown"
score = item.get("score", 0)
accepted = " | accepted" if item.get("is_accepted") else ""
body = _clean_text(item.get("body"))
if len(body) > 1600:
body = body[:1600].rstrip() + "..."
return f"{index}. {owner} | {score} score{accepted}\n{body}"
@app.get("/")
async def root():
return HTMLResponse(
"""
<html>
<head><title>Stack Overflow x Omi</title></head>
<body style="font-family: sans-serif; max-width: 640px; margin: 48px auto; line-height: 1.5;">
<h1>Stack Overflow x Omi</h1>
<p>Search developer questions, inspect question details, and read top answers from Omi.</p>
<p>No sign-in or API key is required.</p>
</body>
</html>
"""
)
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/.well-known/omi-tools.json")
async def get_omi_tools_manifest():
return {
"tools": [
{
"name": "search_questions",
"description": "Search Stack Overflow or another Stack Exchange site for developer questions. Use this when the user asks how to solve a programming problem or wants related Q&A threads.",
"endpoint": "/tools/search_questions",
"method": "POST",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Free-form search query, such as an error message, API name, or programming problem.",
},
"tags": {
"type": "string",
"description": "Optional comma- or semicolon-separated tags, such as python, react, fastapi.",
},
"site": {
"type": "string",
"description": "Stack Exchange API site slug. Defaults to stackoverflow.",
},
"accepted": {
"type": "boolean",
"description": "Optional filter for questions with accepted answers.",
},
"limit": {
"type": "integer",
"description": "Maximum questions to return. Defaults to 5, maximum 10.",
},
},
"required": ["query"],
},
"auth_required": False,
"status_message": "Searching Stack Overflow...",
},
{
"name": "get_question",
"description": "Get details for a specific Stack Overflow question ID, including title, score, tags, and body excerpt.",
"endpoint": "/tools/get_question",
"method": "POST",
"parameters": {
"type": "object",
"properties": {
"question_id": {
"type": "integer",
"description": "Stack Overflow question ID.",
},
"site": {
"type": "string",
"description": "Stack Exchange API site slug. Defaults to stackoverflow.",
},
},
"required": ["question_id"],
},
"auth_required": False,
"status_message": "Fetching Stack Overflow question...",
},
{
"name": "get_top_answers",
"description": "Get the highest-voted answers for a specific Stack Overflow question ID.",
"endpoint": "/tools/get_top_answers",
"method": "POST",
"parameters": {
"type": "object",
"properties": {
"question_id": {
"type": "integer",
"description": "Stack Overflow question ID.",
},
"site": {
"type": "string",
"description": "Stack Exchange API site slug. Defaults to stackoverflow.",
},
"limit": {
"type": "integer",
"description": "Maximum answers to return. Defaults to 3, maximum 10.",
},
},
"required": ["question_id"],
},
"auth_required": False,
"status_message": "Fetching Stack Overflow answers...",
},
]
}
@app.post("/tools/search_questions", tags=["chat_tools"], response_model=ChatToolResponse)
async def search_questions(payload: dict[str, Any]):
query = (payload.get("query") or "").strip()
if not query:
return ChatToolResponse(error="Missing required field: query")
site = _safe_site(payload.get("site"))
limit = _safe_limit(payload.get("limit"))
params: dict[str, Any] = {
"site": site,
"q": query,
"pagesize": limit,
"order": "desc",
"sort": "relevance",
}
tags = _safe_tags(payload.get("tags"))
if tags:
params["tagged"] = tags
accepted = _coerce_bool(payload.get("accepted"))
if accepted is not None:
params["accepted"] = "true" if accepted else "false"
try:
data = await _request_json("/search/advanced", params)
items = data.get("items", [])[:limit]
if not items:
return ChatToolResponse(result=f"No Stack Exchange questions found for '{query}'.")
lines = [f"Stack Exchange results for '{query}' on {site}:"]
lines.extend(_format_question(item, index, site) for index, item in enumerate(items, start=1))
return ChatToolResponse(result="\n\n".join(lines))
except ValueError as exc:
return ChatToolResponse(error=f"Stack Exchange search failed: {exc}")
except httpx.HTTPStatusError as exc:
return ChatToolResponse(error=f"Stack Exchange search failed with status {exc.response.status_code}.")
except httpx.HTTPError as exc:
return ChatToolResponse(error=f"Stack Exchange search failed: {exc}")
@app.post("/tools/get_question", tags=["chat_tools"], response_model=ChatToolResponse)
async def get_question(payload: dict[str, Any]):
question_id = payload.get("question_id")
if question_id is None:
return ChatToolResponse(error="Missing required field: question_id")
try:
question_id = int(question_id)
except (TypeError, ValueError):
return ChatToolResponse(error="question_id must be an integer")
site = _safe_site(payload.get("site"))
try:
data = await _request_json(
f"/questions/{question_id}",
{"site": site, "filter": "withbody", "pagesize": 1},
)
items = data.get("items", [])
if not items:
return ChatToolResponse(error=f"No question found for ID {question_id} on {site}.")
item = items[0]
title = _clean_text(item.get("title")) or "Untitled question"
body = _clean_text(item.get("body"))
if len(body) > 1800:
body = body[:1800].rstrip() + "..."
tags = ", ".join(item.get("tags", [])) or "no tags"
link = item.get("link") or _question_url(site, question_id)
lines = [
title,
f"Question ID: {question_id}",
f"Created: {_format_date(item.get('creation_date'))}",
f"Score: {item.get('score', 0)} | Answers: {item.get('answer_count', 0)} | Views: {item.get('view_count', 0)}",
f"Tags: {tags}",
link,
]
if body:
lines.extend(["", "Question body:", body])
return ChatToolResponse(result="\n".join(lines))
except ValueError as exc:
return ChatToolResponse(error=f"Stack Exchange question request failed: {exc}")
except httpx.HTTPStatusError as exc:
return ChatToolResponse(error=f"Stack Exchange question request failed with status {exc.response.status_code}.")
except httpx.HTTPError as exc:
return ChatToolResponse(error=f"Stack Exchange question request failed: {exc}")
@app.post("/tools/get_top_answers", tags=["chat_tools"], response_model=ChatToolResponse)
async def get_top_answers(payload: dict[str, Any]):
question_id = payload.get("question_id")
if question_id is None:
return ChatToolResponse(error="Missing required field: question_id")
try:
question_id = int(question_id)
except (TypeError, ValueError):
return ChatToolResponse(error="question_id must be an integer")
site = _safe_site(payload.get("site"))
limit = _safe_limit(payload.get("limit"), default=3)
try:
data = await _request_json(
f"/questions/{question_id}/answers",
{
"site": site,
"filter": "withbody",
"pagesize": limit,
"order": "desc",
"sort": "votes",
},
)
items = data.get("items", [])[:limit]
if not items:
return ChatToolResponse(result=f"No answers found for question ID {question_id} on {site}.")
lines = [f"Top answers for question {question_id} on {site}:", _question_url(site, question_id)]
lines.extend(_format_answer(item, index) for index, item in enumerate(items, start=1))
return ChatToolResponse(result="\n\n".join(lines))
except ValueError as exc:
return ChatToolResponse(error=f"Stack Exchange answers request failed: {exc}")
except httpx.HTTPStatusError as exc:
return ChatToolResponse(error=f"Stack Exchange answers request failed with status {exc.response.status_code}.")
except httpx.HTTPError as exc:
return ChatToolResponse(error=f"Stack Exchange answers request failed: {exc}")