appsocom 0.6.3__tar.gz → 0.7.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {appsocom-0.6.3 → appsocom-0.7.0}/PKG-INFO +33 -2
- appsocom-0.7.0/README.md +74 -0
- {appsocom-0.6.3 → appsocom-0.7.0}/appsocom/__init__.py +181 -5
- {appsocom-0.6.3 → appsocom-0.7.0}/appsocom.egg-info/PKG-INFO +33 -2
- {appsocom-0.6.3 → appsocom-0.7.0}/pyproject.toml +1 -1
- {appsocom-0.6.3 → appsocom-0.7.0}/tests/test_sfukit.py +130 -2
- appsocom-0.6.3/README.md +0 -43
- {appsocom-0.6.3 → appsocom-0.7.0}/LICENSE +0 -0
- {appsocom-0.6.3 → appsocom-0.7.0}/appsocom.egg-info/SOURCES.txt +0 -0
- {appsocom-0.6.3 → appsocom-0.7.0}/appsocom.egg-info/dependency_links.txt +0 -0
- {appsocom-0.6.3 → appsocom-0.7.0}/appsocom.egg-info/top_level.txt +0 -0
- {appsocom-0.6.3 → appsocom-0.7.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: appsocom
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification
|
|
5
5
|
Author: Appsotech Limited
|
|
6
6
|
License-Expression: MIT
|
|
@@ -55,7 +55,38 @@ def hook():
|
|
|
55
55
|
return "", 204
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
## AI assistant
|
|
59
|
+
|
|
60
|
+
Tell the assistant about your app once, mint a token for each signed-in person, and answer its tool calls at your `toolsUrl`:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from appsocom import AssistantToolError, assistant_tools
|
|
64
|
+
|
|
65
|
+
kit.set_assistant_config({
|
|
66
|
+
"name": "Ada",
|
|
67
|
+
"toolsUrl": "https://app.example/assistant-tools",
|
|
68
|
+
"tools": [{"name": "list_students", "description": "Students in a class", "parameters": {"type": "object", "properties": {"cls": {"type": "string"}}}}],
|
|
69
|
+
"appMap": [{"label": "Fees", "path": "/fees", "aliases": ["bursary"]}],
|
|
70
|
+
})
|
|
71
|
+
tok = kit.create_assistant_token(user.id, name=user.name, role=user.role, metadata={"school": user.school_id})
|
|
72
|
+
# give tok["token"] to the browser (@appsocom/react <AssistantPanel>)
|
|
73
|
+
|
|
74
|
+
def list_students(args, call): # runs as the person who asked
|
|
75
|
+
if call["role"] != "teacher":
|
|
76
|
+
raise AssistantToolError("Only teachers can list students.") # the model sees this message
|
|
77
|
+
return db.students(call["metadata"]["school"], args["cls"])
|
|
78
|
+
|
|
79
|
+
tools = assistant_tools(os.environ["APPSOCOM_WEBHOOK_SECRET"], {"list_students": list_students})
|
|
80
|
+
|
|
81
|
+
@app.post("/assistant-tools")
|
|
82
|
+
def assistant_tools_route():
|
|
83
|
+
status, body = tools.handle(request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
84
|
+
return body, status, {"Content-Type": "application/json"}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
|
|
88
|
+
|
|
89
|
+
All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
|
|
59
90
|
|
|
60
91
|
Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
|
|
61
92
|
|
appsocom-0.7.0/README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# appsocom (Python)
|
|
2
|
+
|
|
3
|
+
Python server SDK for [Appsocom Live](https://live.appsocom.com): mint join tokens, manage rooms and participants, moderate and verify webhooks. Python 3.9+, standard library only.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install appsocom
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import os
|
|
11
|
+
from appsocom import SfuKit, SfuKitError, verify_webhook
|
|
12
|
+
|
|
13
|
+
kit = SfuKit("https://api.appsocom.dev", os.environ["APPSOCOM_API_KEY"]) # project API key from the console
|
|
14
|
+
|
|
15
|
+
tok = kit.create_token("class-1", "u_7", name="Ada", role="student", metadata={"seat": 3})
|
|
16
|
+
tok["token"], tok["expiresAt"]
|
|
17
|
+
|
|
18
|
+
kit.set_role("class-1", "u_9", "student") # promote an observer
|
|
19
|
+
kit.mute("class-1", "*", ["mic"], lock=True) # mute everyone, keep them muted
|
|
20
|
+
kit.set_room_metadata("class-1", {"topic": "Fractions"})
|
|
21
|
+
kit.set_track_permissions("class-1", "u_7", {"allowAll": False, "allow": [{"userId": "u_1"}]})
|
|
22
|
+
kit.remove_participant("class-1", "u_8", ban=True)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Errors raise `SfuKitError` with `.status` and `.body`.
|
|
26
|
+
|
|
27
|
+
Webhooks (Flask):
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
@app.post("/appsocom-webhooks")
|
|
31
|
+
def hook():
|
|
32
|
+
event = verify_webhook(os.environ["APPSOCOM_WEBHOOK_SECRET"], request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
33
|
+
if event is None:
|
|
34
|
+
return "", 401
|
|
35
|
+
print(event["event"], event["roomId"])
|
|
36
|
+
return "", 204
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## AI assistant
|
|
40
|
+
|
|
41
|
+
Tell the assistant about your app once, mint a token for each signed-in person, and answer its tool calls at your `toolsUrl`:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from appsocom import AssistantToolError, assistant_tools
|
|
45
|
+
|
|
46
|
+
kit.set_assistant_config({
|
|
47
|
+
"name": "Ada",
|
|
48
|
+
"toolsUrl": "https://app.example/assistant-tools",
|
|
49
|
+
"tools": [{"name": "list_students", "description": "Students in a class", "parameters": {"type": "object", "properties": {"cls": {"type": "string"}}}}],
|
|
50
|
+
"appMap": [{"label": "Fees", "path": "/fees", "aliases": ["bursary"]}],
|
|
51
|
+
})
|
|
52
|
+
tok = kit.create_assistant_token(user.id, name=user.name, role=user.role, metadata={"school": user.school_id})
|
|
53
|
+
# give tok["token"] to the browser (@appsocom/react <AssistantPanel>)
|
|
54
|
+
|
|
55
|
+
def list_students(args, call): # runs as the person who asked
|
|
56
|
+
if call["role"] != "teacher":
|
|
57
|
+
raise AssistantToolError("Only teachers can list students.") # the model sees this message
|
|
58
|
+
return db.students(call["metadata"]["school"], args["cls"])
|
|
59
|
+
|
|
60
|
+
tools = assistant_tools(os.environ["APPSOCOM_WEBHOOK_SECRET"], {"list_students": list_students})
|
|
61
|
+
|
|
62
|
+
@app.post("/assistant-tools")
|
|
63
|
+
def assistant_tools_route():
|
|
64
|
+
status, body = tools.handle(request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
65
|
+
return body, status, {"Content-Type": "application/json"}
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
`handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
|
|
69
|
+
|
|
70
|
+
All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
|
|
71
|
+
|
|
72
|
+
Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
|
|
73
|
+
|
|
74
|
+
Docs: [docs.appsocom.dev](https://docs.appsocom.dev) · License: MIT
|
|
@@ -16,13 +16,27 @@ import time
|
|
|
16
16
|
import urllib.error
|
|
17
17
|
import urllib.parse
|
|
18
18
|
import urllib.request
|
|
19
|
-
from typing import Any, Dict, List, Optional, Sequence, Union
|
|
20
|
-
|
|
21
|
-
__all__ = [
|
|
22
|
-
|
|
19
|
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"SfuKit",
|
|
23
|
+
"SfuKitError",
|
|
24
|
+
"sign_token",
|
|
25
|
+
"verify_webhook",
|
|
26
|
+
"sign_webhook",
|
|
27
|
+
"SIGNATURE_HEADER",
|
|
28
|
+
"AssistantToolError",
|
|
29
|
+
"AssistantTools",
|
|
30
|
+
"assistant_tools",
|
|
31
|
+
"verify_assistant_tool_call",
|
|
32
|
+
]
|
|
33
|
+
__version__ = "0.7.0"
|
|
23
34
|
|
|
24
35
|
SIGNATURE_HEADER = "X-SfuKit-Signature"
|
|
25
36
|
_ID = re.compile(r"^[A-Za-z0-9._:@-]{1,128}$")
|
|
37
|
+
# The kit's own patterns for the parts of a recording download path.
|
|
38
|
+
_RECORDING_ID = re.compile(r"^[A-Za-z0-9-]{1,64}$")
|
|
39
|
+
_RECORDING_FILE = re.compile(r"^[A-Za-z0-9._@-]{1,128}$")
|
|
26
40
|
_ROLE = re.compile(r"^[A-Za-z0-9._-]{1,32}$")
|
|
27
41
|
_ROLE_DEFAULTS = {
|
|
28
42
|
"teacher": {"mic": True, "camera": True, "screen": True, "moderate": True},
|
|
@@ -42,7 +56,8 @@ class SfuKitError(Exception):
|
|
|
42
56
|
|
|
43
57
|
|
|
44
58
|
def _id(value: str) -> str:
|
|
45
|
-
|
|
59
|
+
# "." and ".." would be resolved as dot segments, sending the request to a different route.
|
|
60
|
+
if not isinstance(value, str) or not _ID.match(value) or value in (".", ".."):
|
|
46
61
|
raise SfuKitError(400, f'invalid id "{value}" (letters, numbers, . _ : @ -, max 128)')
|
|
47
62
|
return urllib.parse.quote(value, safe="")
|
|
48
63
|
|
|
@@ -227,6 +242,10 @@ class SfuKit:
|
|
|
227
242
|
return self.request("GET", f"/rooms/{_id(room_id)}/recordings")["recordings"]
|
|
228
243
|
|
|
229
244
|
def download_recording(self, room_id: str, recording_id: str, file: str) -> bytes:
|
|
245
|
+
if not isinstance(recording_id, str) or not _RECORDING_ID.fullmatch(recording_id):
|
|
246
|
+
raise SfuKitError(400, f'invalid recording id "{recording_id}" (letters, numbers, -, max 64)')
|
|
247
|
+
if not isinstance(file, str) or not _RECORDING_FILE.fullmatch(file) or file in (".", ".."):
|
|
248
|
+
raise SfuKitError(400, f'invalid recording file "{file}" (letters, numbers, . _ @ -, max 128, not . or ..)')
|
|
230
249
|
q = urllib.parse.quote
|
|
231
250
|
return self.request("GET", f"/rooms/{_id(room_id)}/recordings/{q(recording_id, safe='')}/{q(file, safe='')}", raw=bytes)
|
|
232
251
|
|
|
@@ -449,6 +468,39 @@ class SfuKit:
|
|
|
449
468
|
def skip_timetable_run(self, key: str) -> Dict[str, Any]:
|
|
450
469
|
return self.request("POST", f"/timetable-runs/{urllib.parse.quote(key, safe='')}/skip")
|
|
451
470
|
|
|
471
|
+
# ---------- AI assistant ----------
|
|
472
|
+
|
|
473
|
+
def set_assistant_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
|
|
474
|
+
"""Tell the assistant about your app; replaces the whole config.
|
|
475
|
+
|
|
476
|
+
config uses the API's own keys: name, instructions, tools ([{name, description,
|
|
477
|
+
parameters, risk, pinned, assistantAllowed}]), toolsUrl, appMap ([{label, path,
|
|
478
|
+
description, aliases}]), defaultTier, roleTiers, knowledge, retentionDays.
|
|
479
|
+
"""
|
|
480
|
+
return self.request("PUT", "/assistant/config", config)["config"]
|
|
481
|
+
|
|
482
|
+
def get_assistant_config(self) -> Dict[str, Any]:
|
|
483
|
+
return self.request("GET", "/assistant/config")["config"]
|
|
484
|
+
|
|
485
|
+
def create_assistant_token(self, user_id: str, **options: Any) -> Dict[str, Any]:
|
|
486
|
+
"""A token for one signed-in person to chat with the assistant: {"token", "conversationId", "expiresAt"}.
|
|
487
|
+
|
|
488
|
+
options: name, role, conversation_id, tools (names), paths, tier, retention_days,
|
|
489
|
+
monthly_messages (this person's messages per month), metadata (dict of strings, passed back with every tool call),
|
|
490
|
+
context (what your app knows about this person that the assistant should always have, at most 3,000 characters),
|
|
491
|
+
report_usage (add tier, units, cost and tokens to the done event; for a backend that relays answers), ttl_seconds (default 3600, max 43200).
|
|
492
|
+
"""
|
|
493
|
+
body: Dict[str, Any] = {"userId": user_id}
|
|
494
|
+
names = {"conversation_id": "conversationId", "retention_days": "retentionDays", "monthly_messages": "monthlyMessages", "report_usage": "reportUsage", "ttl_seconds": "ttlSeconds"}
|
|
495
|
+
for k, v in options.items():
|
|
496
|
+
if v is not None:
|
|
497
|
+
body[names.get(k, k)] = v
|
|
498
|
+
return self.request("POST", "/assistant/tokens", body)
|
|
499
|
+
|
|
500
|
+
def delete_assistant_conversation(self, user_id: str, conversation_id: str) -> None:
|
|
501
|
+
"""Forget one person's conversation (its memory and transcript)."""
|
|
502
|
+
self.request("DELETE", f"/assistant/conversations/{_id(user_id)}/{_id(conversation_id)}")
|
|
503
|
+
|
|
452
504
|
def health(self) -> Dict[str, Any]:
|
|
453
505
|
return self.request("GET", "/health")
|
|
454
506
|
|
|
@@ -585,3 +637,127 @@ def sign_webhook(secret: str, raw_body: Union[str, bytes], t: Optional[int] = No
|
|
|
585
637
|
t = int(time.time()) if t is None else t
|
|
586
638
|
body = raw_body if isinstance(raw_body, bytes) else raw_body.encode("utf-8")
|
|
587
639
|
return f"t={t},v1=" + hmac.new(secret.encode(), str(t).encode() + b"." + body, hashlib.sha256).hexdigest()
|
|
640
|
+
|
|
641
|
+
|
|
642
|
+
# ---------- AI assistant tools (your toolsUrl) ----------
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
class AssistantToolError(Exception):
|
|
646
|
+
"""Raise this from a tool to tell the model what went wrong (its message is shown to the model)."""
|
|
647
|
+
|
|
648
|
+
|
|
649
|
+
def _parse_signature(signature_header: str) -> Optional[tuple]:
|
|
650
|
+
parts = {}
|
|
651
|
+
for p in signature_header.split(","):
|
|
652
|
+
k, _, v = p.partition("=")
|
|
653
|
+
parts[k.strip()] = v.strip()
|
|
654
|
+
try:
|
|
655
|
+
t = int(parts.get("t", ""))
|
|
656
|
+
except ValueError:
|
|
657
|
+
return None
|
|
658
|
+
v1 = parts.get("v1", "")
|
|
659
|
+
if not re.fullmatch(r"[0-9a-f]{64}", v1):
|
|
660
|
+
return None
|
|
661
|
+
return t, v1
|
|
662
|
+
|
|
663
|
+
|
|
664
|
+
def verify_assistant_tool_call(
|
|
665
|
+
secret: str, raw_body: Union[str, bytes], signature_header: Optional[str], tolerance_seconds: int = 300
|
|
666
|
+
) -> Optional[Dict[str, Any]]:
|
|
667
|
+
"""Check a tool call's signature; the call dict, or None when it is wrong, stale or not an assistant call."""
|
|
668
|
+
if not secret or not signature_header:
|
|
669
|
+
return None
|
|
670
|
+
parsed = _parse_signature(signature_header)
|
|
671
|
+
if parsed is None:
|
|
672
|
+
return None
|
|
673
|
+
t, v1 = parsed
|
|
674
|
+
if abs(time.time() - t) > tolerance_seconds:
|
|
675
|
+
return None
|
|
676
|
+
body = raw_body if isinstance(raw_body, bytes) else raw_body.encode("utf-8")
|
|
677
|
+
expected = hmac.new(secret.encode(), str(t).encode() + b"." + body, hashlib.sha256).hexdigest()
|
|
678
|
+
if not hmac.compare_digest(expected, v1):
|
|
679
|
+
return None
|
|
680
|
+
try:
|
|
681
|
+
call = json.loads(body)
|
|
682
|
+
except ValueError:
|
|
683
|
+
return None
|
|
684
|
+
if not isinstance(call, dict) or call.get("type") != "tool_call" or call.get("kind") != "assistant" or not isinstance(call.get("name"), str):
|
|
685
|
+
return None
|
|
686
|
+
call["arguments"] = call.get("arguments") or {}
|
|
687
|
+
call["metadata"] = call.get("metadata") or {}
|
|
688
|
+
return call
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
class AssistantTools:
|
|
692
|
+
"""Your toolsUrl: checks each request's signature and runs the matching handler.
|
|
693
|
+
|
|
694
|
+
A handler is called as handler(arguments, call); `call` has conversationId, userId,
|
|
695
|
+
role, callId, name and metadata. What it returns goes back to the model (keep it
|
|
696
|
+
small: at most 16 KB is read). Returning None sends "done".
|
|
697
|
+
"""
|
|
698
|
+
|
|
699
|
+
def __init__(
|
|
700
|
+
self,
|
|
701
|
+
secret: str,
|
|
702
|
+
handlers: Dict[str, Callable[[Dict[str, Any], Dict[str, Any]], Any]],
|
|
703
|
+
tolerance_seconds: int = 300,
|
|
704
|
+
on_error: Optional[Callable[[BaseException, Dict[str, Any]], None]] = None,
|
|
705
|
+
):
|
|
706
|
+
if not secret:
|
|
707
|
+
raise ValueError("secret is required (your webhook secret)")
|
|
708
|
+
self._secret = secret
|
|
709
|
+
self._handlers = dict(handlers)
|
|
710
|
+
self.tolerance_seconds = tolerance_seconds
|
|
711
|
+
self.on_error = on_error
|
|
712
|
+
|
|
713
|
+
def verify(self, raw_body: Union[str, bytes], signature_header: Optional[str]) -> Optional[Dict[str, Any]]:
|
|
714
|
+
return verify_assistant_tool_call(self._secret, raw_body, signature_header, self.tolerance_seconds)
|
|
715
|
+
|
|
716
|
+
def handle(self, raw_body: Union[str, bytes], signature_header: Optional[str]) -> Tuple[int, str]:
|
|
717
|
+
"""Check, run and answer one call. Pass the RAW body. Returns (status, JSON body) to send."""
|
|
718
|
+
call = self.verify(raw_body, signature_header)
|
|
719
|
+
if call is None:
|
|
720
|
+
return 401, _json({"error": "bad signature"})
|
|
721
|
+
handler = self._handlers.get(call["name"])
|
|
722
|
+
if handler is None:
|
|
723
|
+
return 200, _json({"error": f"There is no tool called {call['name']}."})
|
|
724
|
+
try:
|
|
725
|
+
result = handler(call["arguments"], call)
|
|
726
|
+
except AssistantToolError as e:
|
|
727
|
+
return 200, _json({"error": str(e)})
|
|
728
|
+
except Exception as e: # noqa: BLE001 (any other failure is hidden from the model)
|
|
729
|
+
if self.on_error is not None:
|
|
730
|
+
try:
|
|
731
|
+
self.on_error(e, call)
|
|
732
|
+
except Exception: # noqa: BLE001
|
|
733
|
+
pass
|
|
734
|
+
return 200, _json({"error": "The tool failed."})
|
|
735
|
+
try:
|
|
736
|
+
return 200, _json({"result": "done" if result is None else result})
|
|
737
|
+
except (TypeError, ValueError) as e:
|
|
738
|
+
if self.on_error is not None:
|
|
739
|
+
try:
|
|
740
|
+
self.on_error(e, call)
|
|
741
|
+
except Exception: # noqa: BLE001
|
|
742
|
+
pass
|
|
743
|
+
return 200, _json({"error": "The tool failed."})
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def assistant_tools(
|
|
747
|
+
secret: str,
|
|
748
|
+
handlers: Dict[str, Callable[[Dict[str, Any], Dict[str, Any]], Any]],
|
|
749
|
+
tolerance_seconds: int = 300,
|
|
750
|
+
on_error: Optional[Callable[[BaseException, Dict[str, Any]], None]] = None,
|
|
751
|
+
) -> AssistantTools:
|
|
752
|
+
"""Your toolsUrl in one call. `secret` is your webhook secret.
|
|
753
|
+
|
|
754
|
+
tools = assistant_tools(os.environ["APPSOCOM_WEBHOOK_SECRET"], {
|
|
755
|
+
"list_students": lambda args, call: db.students(call["metadata"]["school"], args["cls"]),
|
|
756
|
+
})
|
|
757
|
+
|
|
758
|
+
@app.post("/assistant-tools")
|
|
759
|
+
def assistant_tools_route():
|
|
760
|
+
status, body = tools.handle(request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
761
|
+
return body, status, {"Content-Type": "application/json"}
|
|
762
|
+
"""
|
|
763
|
+
return AssistantTools(secret, handlers, tolerance_seconds=tolerance_seconds, on_error=on_error)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: appsocom
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.7.0
|
|
4
4
|
Summary: Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification
|
|
5
5
|
Author: Appsotech Limited
|
|
6
6
|
License-Expression: MIT
|
|
@@ -55,7 +55,38 @@ def hook():
|
|
|
55
55
|
return "", 204
|
|
56
56
|
```
|
|
57
57
|
|
|
58
|
-
|
|
58
|
+
## AI assistant
|
|
59
|
+
|
|
60
|
+
Tell the assistant about your app once, mint a token for each signed-in person, and answer its tool calls at your `toolsUrl`:
|
|
61
|
+
|
|
62
|
+
```python
|
|
63
|
+
from appsocom import AssistantToolError, assistant_tools
|
|
64
|
+
|
|
65
|
+
kit.set_assistant_config({
|
|
66
|
+
"name": "Ada",
|
|
67
|
+
"toolsUrl": "https://app.example/assistant-tools",
|
|
68
|
+
"tools": [{"name": "list_students", "description": "Students in a class", "parameters": {"type": "object", "properties": {"cls": {"type": "string"}}}}],
|
|
69
|
+
"appMap": [{"label": "Fees", "path": "/fees", "aliases": ["bursary"]}],
|
|
70
|
+
})
|
|
71
|
+
tok = kit.create_assistant_token(user.id, name=user.name, role=user.role, metadata={"school": user.school_id})
|
|
72
|
+
# give tok["token"] to the browser (@appsocom/react <AssistantPanel>)
|
|
73
|
+
|
|
74
|
+
def list_students(args, call): # runs as the person who asked
|
|
75
|
+
if call["role"] != "teacher":
|
|
76
|
+
raise AssistantToolError("Only teachers can list students.") # the model sees this message
|
|
77
|
+
return db.students(call["metadata"]["school"], args["cls"])
|
|
78
|
+
|
|
79
|
+
tools = assistant_tools(os.environ["APPSOCOM_WEBHOOK_SECRET"], {"list_students": list_students})
|
|
80
|
+
|
|
81
|
+
@app.post("/assistant-tools")
|
|
82
|
+
def assistant_tools_route():
|
|
83
|
+
status, body = tools.handle(request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
84
|
+
return body, status, {"Content-Type": "application/json"}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
`handle()` refuses bad or stale signatures with 401, answers `{"result": ...}` (`"done"` when a tool returns `None`) or `{"error": ...}`, and hides any exception other than `AssistantToolError` as "The tool failed." (pass `on_error=` to see it). Also: `get_assistant_config`, `delete_assistant_conversation(user_id, conversation_id)`, `verify_assistant_tool_call`.
|
|
88
|
+
|
|
89
|
+
All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `set_assistant_config`, `get_assistant_config`, `create_assistant_token`, `delete_assistant_conversation`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`, `assistant_tools`, `verify_assistant_tool_call`.
|
|
59
90
|
|
|
60
91
|
Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
|
|
61
92
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "appsocom"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.7.0"
|
|
8
8
|
description = "Python server SDK for Appsocom Live video calls: join tokens, rooms, moderation and webhook verification"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
@@ -7,7 +7,16 @@ import time
|
|
|
7
7
|
import unittest
|
|
8
8
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
9
9
|
|
|
10
|
-
from appsocom import
|
|
10
|
+
from appsocom import (
|
|
11
|
+
AssistantToolError,
|
|
12
|
+
SfuKit,
|
|
13
|
+
SfuKitError,
|
|
14
|
+
assistant_tools,
|
|
15
|
+
sign_token,
|
|
16
|
+
sign_webhook,
|
|
17
|
+
verify_assistant_tool_call,
|
|
18
|
+
verify_webhook,
|
|
19
|
+
)
|
|
11
20
|
|
|
12
21
|
SECRET = "x" * 40
|
|
13
22
|
|
|
@@ -70,7 +79,15 @@ class Handler(BaseHTTPRequestHandler):
|
|
|
70
79
|
n = int(self.headers.get("Content-Length") or 0)
|
|
71
80
|
body = json.loads(self.rfile.read(n)) if n else None
|
|
72
81
|
Handler.seen.append((self.command, self.path, self.headers.get("Authorization"), body))
|
|
73
|
-
if self.path
|
|
82
|
+
if self.path == "/assistant/config":
|
|
83
|
+
out, code = {"config": body if self.command == "PUT" else {"name": "Ada"}}, 200
|
|
84
|
+
elif self.path == "/assistant/tokens":
|
|
85
|
+
out, code = {"token": "t", "conversationId": body.get("conversationId", "new"), "expiresAt": 1}, 200
|
|
86
|
+
elif self.path.startswith("/assistant/conversations/"):
|
|
87
|
+
self.send_response(204)
|
|
88
|
+
self.end_headers()
|
|
89
|
+
return
|
|
90
|
+
elif self.path.startswith("/rooms/missing"):
|
|
74
91
|
out, code = {"error": "nope"}, 404
|
|
75
92
|
elif self.command == "PATCH" and "/participants/" in self.path:
|
|
76
93
|
out, code = {"updated": 1}, 200
|
|
@@ -151,6 +168,117 @@ class AdminTests(unittest.TestCase):
|
|
|
151
168
|
with self.assertRaises(SfuKitError) as e:
|
|
152
169
|
self.kit.get_room("bad room!")
|
|
153
170
|
self.assertEqual(e.exception.status, 400)
|
|
171
|
+
sent = len(Handler.seen)
|
|
172
|
+
for args in (("..", "20261118T073712-1a2b3c4d", "transcript"), ("r1", "..", "transcript"), ("r1", "20261118T073712-1a2b3c4d", "..")):
|
|
173
|
+
with self.assertRaises(SfuKitError) as e:
|
|
174
|
+
self.kit.download_recording(*args)
|
|
175
|
+
self.assertEqual(e.exception.status, 400)
|
|
176
|
+
self.assertEqual(len(Handler.seen), sent)
|
|
177
|
+
self.kit.download_recording("r1", "20261118T073712-1a2b3c4d", "001-u1-audio.wav")
|
|
178
|
+
self.assertEqual(Handler.seen[-1][1], "/rooms/r1/recordings/20261118T073712-1a2b3c4d/001-u1-audio.wav")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# A tool call signed by the Worker's own signWebhook (packages/server/src/webhooks.ts), shared by every SDK's tests.
|
|
182
|
+
VECTOR_SECRET = "whsec_assistant_test"
|
|
183
|
+
VECTOR_BODY = '{"type":"tool_call","kind":"assistant","conversationId":"c1","userId":"u_7","role":"teacher","callId":"call_1","name":"list_students","arguments":{"cls":"JSS1"},"metadata":{"school":"s1"}}'
|
|
184
|
+
VECTOR_SIGNATURE = "t=1763500000,v1=6497035b3915fa61b8deb6bfa54b0f22d52ff62c71f077a2d43873d747ed24a9"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def tool_call(name, arguments=None, **extra):
|
|
188
|
+
call = {"type": "tool_call", "kind": "assistant", "conversationId": "c1", "userId": "u_7", "role": "teacher", "callId": "call_1", "name": name, "arguments": arguments or {}, "metadata": {"school": "s1"}}
|
|
189
|
+
call.update(extra)
|
|
190
|
+
return json.dumps(call, separators=(",", ":"))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class AssistantToolsTests(unittest.TestCase):
|
|
194
|
+
def setUp(self):
|
|
195
|
+
self.errors = []
|
|
196
|
+
|
|
197
|
+
def boom(args, call):
|
|
198
|
+
raise RuntimeError("database password is hunter2")
|
|
199
|
+
|
|
200
|
+
def denied(args, call):
|
|
201
|
+
raise AssistantToolError("You can only see your own classes.")
|
|
202
|
+
|
|
203
|
+
self.tools = assistant_tools(
|
|
204
|
+
"s",
|
|
205
|
+
{
|
|
206
|
+
"list_students": lambda args, call: [{"name": "Ada", "cls": args["cls"], "school": call["metadata"]["school"], "asker": call["userId"]}],
|
|
207
|
+
"nothing": lambda args, call: None,
|
|
208
|
+
"boom": boom,
|
|
209
|
+
"denied": denied,
|
|
210
|
+
},
|
|
211
|
+
on_error=lambda e, call: self.errors.append((str(e), call["name"])),
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
def run_call(self, body, secret="s", t=None):
|
|
215
|
+
status, out = self.tools.handle(body, sign_webhook(secret, body, t))
|
|
216
|
+
return status, json.loads(out)
|
|
217
|
+
|
|
218
|
+
def test_verifies_the_workers_signature(self):
|
|
219
|
+
self.assertIsNone(verify_assistant_tool_call(VECTOR_SECRET, VECTOR_BODY, VECTOR_SIGNATURE)) # stale now
|
|
220
|
+
call = verify_assistant_tool_call(VECTOR_SECRET, VECTOR_BODY, VECTOR_SIGNATURE, tolerance_seconds=10**10)
|
|
221
|
+
self.assertEqual((call["name"], call["arguments"], call["metadata"]), ("list_students", {"cls": "JSS1"}, {"school": "s1"}))
|
|
222
|
+
self.assertIsNone(verify_assistant_tool_call("other", VECTOR_BODY, VECTOR_SIGNATURE, tolerance_seconds=10**10))
|
|
223
|
+
self.assertIsNone(verify_assistant_tool_call(VECTOR_SECRET, VECTOR_BODY + " ", VECTOR_SIGNATURE, tolerance_seconds=10**10))
|
|
224
|
+
|
|
225
|
+
def test_runs_the_tool_as_the_person(self):
|
|
226
|
+
status, out = self.run_call(tool_call("list_students", {"cls": "JSS1"}))
|
|
227
|
+
self.assertEqual(status, 200)
|
|
228
|
+
self.assertEqual(out, {"result": [{"name": "Ada", "cls": "JSS1", "school": "s1", "asker": "u_7"}]})
|
|
229
|
+
self.assertEqual(self.run_call(tool_call("nothing")), (200, {"result": "done"}))
|
|
230
|
+
status, out = self.tools.handle(tool_call("nothing").encode(), sign_webhook("s", tool_call("nothing")))
|
|
231
|
+
self.assertEqual(json.loads(out), {"result": "done"})
|
|
232
|
+
|
|
233
|
+
def test_refuses_bad_signatures_and_other_bodies(self):
|
|
234
|
+
body = tool_call("list_students", {"cls": "JSS1"})
|
|
235
|
+
self.assertEqual(self.run_call(body, secret="other")[0], 401)
|
|
236
|
+
self.assertEqual(self.run_call(body, t=int(time.time()) - 301)[0], 401)
|
|
237
|
+
self.assertEqual(self.tools.handle(body, None)[0], 401)
|
|
238
|
+
self.assertEqual(self.tools.handle(body, "t=1,v1=zz")[0], 401)
|
|
239
|
+
self.assertEqual(self.run_call(tool_call("list_students", kind="agent"))[0], 401)
|
|
240
|
+
self.assertEqual(self.run_call(tool_call("list_students", type="call.ended"))[0], 401)
|
|
241
|
+
self.assertEqual(self.run_call("not json")[0], 401)
|
|
242
|
+
|
|
243
|
+
def test_unknown_and_inherited_names(self):
|
|
244
|
+
for name in ("missing", "__class__", "__init__", "get", "keys"):
|
|
245
|
+
self.assertEqual(self.run_call(tool_call(name)), (200, {"error": f"There is no tool called {name}."}))
|
|
246
|
+
|
|
247
|
+
def test_errors(self):
|
|
248
|
+
self.assertEqual(self.run_call(tool_call("denied")), (200, {"error": "You can only see your own classes."}))
|
|
249
|
+
self.assertEqual(self.run_call(tool_call("boom")), (200, {"error": "The tool failed."}))
|
|
250
|
+
self.assertEqual(self.errors, [("database password is hunter2", "boom")])
|
|
251
|
+
|
|
252
|
+
def test_needs_a_secret(self):
|
|
253
|
+
with self.assertRaises(ValueError):
|
|
254
|
+
assistant_tools("", {})
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class AssistantAdminTests(unittest.TestCase):
|
|
258
|
+
@classmethod
|
|
259
|
+
def setUpClass(cls):
|
|
260
|
+
cls.server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
261
|
+
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
|
|
262
|
+
cls.kit = SfuKit(f"http://127.0.0.1:{cls.server.server_port}", "k")
|
|
263
|
+
|
|
264
|
+
@classmethod
|
|
265
|
+
def tearDownClass(cls):
|
|
266
|
+
cls.server.shutdown()
|
|
267
|
+
|
|
268
|
+
def test_admin_calls(self):
|
|
269
|
+
kit = self.kit
|
|
270
|
+
cfg = {"name": "Ada", "toolsUrl": "https://app.example/assistant-tools", "tools": [{"name": "list_students", "description": "Students in a class"}]}
|
|
271
|
+
self.assertEqual(kit.set_assistant_config(cfg), cfg)
|
|
272
|
+
self.assertEqual(Handler.seen[-1], ("PUT", "/assistant/config", "Bearer k", cfg))
|
|
273
|
+
self.assertEqual(kit.get_assistant_config(), {"name": "Ada"})
|
|
274
|
+
self.assertEqual(Handler.seen[-1][:2], ("GET", "/assistant/config"))
|
|
275
|
+
tok = kit.create_assistant_token("u_7", name="Ada", role="teacher", conversation_id="c1", ttl_seconds=600, metadata={"school": "s1"}, tier=None)
|
|
276
|
+
self.assertEqual(tok["conversationId"], "c1")
|
|
277
|
+
self.assertEqual(Handler.seen[-1], ("POST", "/assistant/tokens", "Bearer k", {"userId": "u_7", "name": "Ada", "role": "teacher", "conversationId": "c1", "ttlSeconds": 600, "metadata": {"school": "s1"}}))
|
|
278
|
+
self.assertIsNone(kit.delete_assistant_conversation("u_7", "c1"))
|
|
279
|
+
self.assertEqual(Handler.seen[-1][:2], ("DELETE", "/assistant/conversations/u_7/c1"))
|
|
280
|
+
with self.assertRaises(SfuKitError):
|
|
281
|
+
kit.delete_assistant_conversation("u_7", "..")
|
|
154
282
|
|
|
155
283
|
|
|
156
284
|
if __name__ == "__main__":
|
appsocom-0.6.3/README.md
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
# appsocom (Python)
|
|
2
|
-
|
|
3
|
-
Python server SDK for [Appsocom Live](https://live.appsocom.com): mint join tokens, manage rooms and participants, moderate and verify webhooks. Python 3.9+, standard library only.
|
|
4
|
-
|
|
5
|
-
```bash
|
|
6
|
-
pip install appsocom
|
|
7
|
-
```
|
|
8
|
-
|
|
9
|
-
```python
|
|
10
|
-
import os
|
|
11
|
-
from appsocom import SfuKit, SfuKitError, verify_webhook
|
|
12
|
-
|
|
13
|
-
kit = SfuKit("https://api.appsocom.dev", os.environ["APPSOCOM_API_KEY"]) # project API key from the console
|
|
14
|
-
|
|
15
|
-
tok = kit.create_token("class-1", "u_7", name="Ada", role="student", metadata={"seat": 3})
|
|
16
|
-
tok["token"], tok["expiresAt"]
|
|
17
|
-
|
|
18
|
-
kit.set_role("class-1", "u_9", "student") # promote an observer
|
|
19
|
-
kit.mute("class-1", "*", ["mic"], lock=True) # mute everyone, keep them muted
|
|
20
|
-
kit.set_room_metadata("class-1", {"topic": "Fractions"})
|
|
21
|
-
kit.set_track_permissions("class-1", "u_7", {"allowAll": False, "allow": [{"userId": "u_1"}]})
|
|
22
|
-
kit.remove_participant("class-1", "u_8", ban=True)
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
Errors raise `SfuKitError` with `.status` and `.body`.
|
|
26
|
-
|
|
27
|
-
Webhooks (Flask):
|
|
28
|
-
|
|
29
|
-
```python
|
|
30
|
-
@app.post("/appsocom-webhooks")
|
|
31
|
-
def hook():
|
|
32
|
-
event = verify_webhook(os.environ["APPSOCOM_WEBHOOK_SECRET"], request.get_data(), request.headers.get("X-SfuKit-Signature"))
|
|
33
|
-
if event is None:
|
|
34
|
-
return "", 401
|
|
35
|
-
print(event["event"], event["roomId"])
|
|
36
|
-
return "", 204
|
|
37
|
-
```
|
|
38
|
-
|
|
39
|
-
All methods: `create_token`, `get_room`, `list_participants`, `update_room`, `set_room_metadata`, `lock_room`, `close_room`, `update_participant`, `set_permissions`, `set_role`, `set_participant_metadata`, `set_track_permissions`, `remove_participant`, `unban`, `mute`, `admit`, `post_chat`, `lower_hands`, `get_attendance`, `get_attendance_csv`, `clear_attendance`, `start_breakouts`, `end_breakouts`, `move_to_group`, `health`, `request()`. Standalone: `sign_token`, `verify_webhook`, `sign_webhook`.
|
|
40
|
-
|
|
41
|
-
Self-hosting your own deployment instead? Point `url` at it and pass its admin key; the optional `jwt_secret` signs tokens locally without an HTTP call.
|
|
42
|
-
|
|
43
|
-
Docs: [docs.appsocom.dev](https://docs.appsocom.dev) · License: MIT
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|