-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext_scope.py
More file actions
63 lines (45 loc) · 1.71 KB
/
context_scope.py
File metadata and controls
63 lines (45 loc) · 1.71 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
"""
Context scoping example for FMTools.
Demonstrates task-local session/model access via `session_scope(...)`.
"""
from __future__ import annotations
import asyncio
from examples._support import AppleFMSetupError, raise_sdk_setup_error, require_apple_fm
try:
from fmtools._context import get_instructions, get_model, get_session, session_scope
from fmtools.protocols import get_backend, set_backend
except Exception as exc: # pragma: no cover - import error path
raise_sdk_setup_error("context_scope.py", exc)
class DemoModel:
def is_available(self) -> tuple[bool, str | None]:
return (True, None)
class DemoSession:
def __init__(self, instructions: str) -> None:
self.instructions = instructions
async def respond(self, prompt: str, generating=None):
del generating
return f"{self.instructions} | {prompt}"
class DemoBackend:
def create_model(self) -> DemoModel:
return DemoModel()
def __call__(self, model: DemoModel, instructions: str) -> DemoSession:
del model
return DemoSession(instructions=instructions)
async def main() -> None:
require_apple_fm("context_scope.py")
original = get_backend()
set_backend(DemoBackend())
try:
async with session_scope("Extract entities.") as session:
assert get_session() is session
print("Instructions:", get_instructions())
print("Model type:", type(get_model()).__name__)
print("Response:", await session.respond("Alice is 31"))
finally:
set_backend(original)
if __name__ == "__main__":
try:
asyncio.run(main())
except AppleFMSetupError as exc:
print(exc)
raise SystemExit(2) from exc