uplinkswitch-hook 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,131 @@
1
+ """Opt-in runtime routing for the standard OpenAI and Anthropic SDKs."""
2
+
3
+ import functools
4
+ import importlib.abc
5
+ import os
6
+ import sys
7
+ from urllib.parse import urlsplit, urlunsplit
8
+
9
+ _installed = False
10
+
11
+
12
+ def install():
13
+ """Install once, leaving optional HTTP libraries unloaded until needed."""
14
+ global _installed
15
+ key = os.environ.get("UPLINKSWITCH_API_KEY")
16
+ if _installed or not key:
17
+ return
18
+ base = urlsplit(os.environ.get("UPLINKSWITCH_BASE_URL", "https://api.uplinkswitch.com/v1").rstrip("/"))
19
+ if base.scheme not in ("http", "https") or not base.hostname:
20
+ raise ValueError("UPLINKSWITCH_BASE_URL must be an HTTP(S) URL")
21
+ hosts = {"api.openai.com", "api.anthropic.com"}
22
+ hosts.update(h.strip().lower() for h in os.environ.get("UPLINKSWITCH_INTERCEPT_HOSTS", "").split(",") if h.strip())
23
+ prefix = base.path.rstrip("/")
24
+
25
+ def rewrite(url):
26
+ original = urlsplit(str(url))
27
+ if original.hostname not in hosts:
28
+ return None
29
+ path = original.path or "/"
30
+ if prefix.endswith("/v1") and (path == "/v1" or path.startswith("/v1/")):
31
+ path = path[3:]
32
+ return urlunsplit((base.scheme, base.netloc, prefix + "/" + path.lstrip("/"), original.query, original.fragment))
33
+
34
+ def authorize(headers):
35
+ authorization = "authorization" in headers
36
+ api_key = "x-api-key" in headers
37
+ if authorization or not api_key:
38
+ headers["authorization"] = "Bearer " + key
39
+ if api_key or not authorization:
40
+ headers["x-api-key"] = key
41
+ headers.pop("host", None)
42
+
43
+ def patch_httpx(module):
44
+ if getattr(module, "_uplinkswitch_patched", False):
45
+ return
46
+
47
+ def request_hook(request):
48
+ target = rewrite(request.url)
49
+ if target is not None:
50
+ request.url = module.URL(target)
51
+ authorize(request.headers)
52
+ request.headers["host"] = base.netloc
53
+
54
+ async def async_request_hook(request):
55
+ request_hook(request)
56
+
57
+ def wrap(client, hook):
58
+ original = client.__init__
59
+
60
+ @functools.wraps(original)
61
+ def initialize(self, *args, **kwargs):
62
+ hooks = {name: list(values) for name, values in (kwargs.get("event_hooks") or {}).items()}
63
+ hooks.setdefault("request", []).append(hook)
64
+ kwargs["event_hooks"] = hooks
65
+ original(self, *args, **kwargs)
66
+
67
+ client.__init__ = initialize
68
+
69
+ wrap(module.Client, request_hook)
70
+ wrap(module.AsyncClient, async_request_hook)
71
+ module._uplinkswitch_patched = True
72
+
73
+ def patch_requests(module):
74
+ if getattr(module, "_uplinkswitch_patched", False):
75
+ return
76
+ original = module.Session.request
77
+
78
+ @functools.wraps(original)
79
+ def request(self, method, url, **kwargs):
80
+ target = rewrite(url)
81
+ if target is not None:
82
+ headers = module.structures.CaseInsensitiveDict(self.headers)
83
+ headers.update(kwargs.get("headers") or {})
84
+ authorize(headers)
85
+ kwargs["headers"] = headers
86
+ # Explicit auth overrides session auth and .netrc during preparation.
87
+ kwargs["auth"] = lambda prepared: prepared
88
+ url = target
89
+ return original(self, method, url, **kwargs)
90
+
91
+ module.Session.request = request
92
+ module._uplinkswitch_patched = True
93
+
94
+ patches = {"httpx": patch_httpx, "httpx2": patch_httpx, "requests": patch_requests}
95
+
96
+ class Loader(importlib.abc.Loader):
97
+ def __init__(self, original, patch):
98
+ self.original = original
99
+ self.patch = patch
100
+
101
+ def create_module(self, spec):
102
+ create = getattr(self.original, "create_module", None)
103
+ return create(spec) if create else None
104
+
105
+ def exec_module(self, module):
106
+ self.original.exec_module(module)
107
+ try:
108
+ self.patch(module)
109
+ except BaseException:
110
+ pass
111
+
112
+ class Finder(importlib.abc.MetaPathFinder):
113
+ def find_spec(self, fullname, path=None, target=None):
114
+ if fullname not in patches:
115
+ return None
116
+ # Delegate to the remaining finders, preserving custom import loaders.
117
+ remaining = sys.meta_path[sys.meta_path.index(self) + 1:]
118
+ for finder in remaining:
119
+ spec = finder.find_spec(fullname, path, target)
120
+ if spec is not None:
121
+ if spec.loader is not None:
122
+ spec.loader = Loader(spec.loader, patches[fullname])
123
+ return spec
124
+ return None
125
+
126
+ for name, patch in patches.items():
127
+ if name in sys.modules:
128
+ patch(sys.modules[name])
129
+ sys.meta_path.insert(0, Finder())
130
+ _installed = True
131
+ sys.stderr.write(f"[uplinkswitch] Intercepting OpenAI/Anthropic calls -> {base.netloc}\n")
@@ -0,0 +1,5 @@
1
+ try:
2
+ from uplinkswitch_hook import install
3
+ install()
4
+ except BaseException:
5
+ pass
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.5
2
+ Name: uplinkswitch-hook
3
+ Version: 0.1.0
4
+ Summary: Zero-code runtime interceptor for OpenAI and Anthropic SDK calls
5
+ Project-URL: Homepage, https://uplinkswitch.ai
6
+ Project-URL: Repository, https://gitlab.com/uplinkswitch/uplinkswitch-hook
7
+ Author: Uplink Switch LLC
8
+ License-Expression: MIT
9
+ Requires-Python: >=3.9
10
+ Provides-Extra: test
11
+ Requires-Dist: anthropic; extra == 'test'
12
+ Requires-Dist: httpx; extra == 'test'
13
+ Requires-Dist: openai; extra == 'test'
14
+ Requires-Dist: pytest; extra == 'test'
15
+ Requires-Dist: requests; extra == 'test'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # UplinkSwitch runtime hooks
19
+
20
+ Route existing OpenAI and Anthropic SDK calls through UplinkSwitch without editing application code. The hooks intercept `api.openai.com` and `api.anthropic.com`, preserve methods, bodies and other headers, and replace the authentication headers with your destination key. Both packages have no runtime dependencies.
21
+
22
+ ## Node.js 18+
23
+
24
+ ```sh
25
+ npm i -D @uplinkswitch/hook
26
+ export UPLINKSWITCH_API_KEY="your-key"
27
+ export NODE_OPTIONS="-r @uplinkswitch/hook/register"
28
+ node app.js
29
+ ```
30
+
31
+ The hook must be installed in the runtime environment, including when production installs omit development dependencies. It covers global fetch and Node's http/https request/get APIs. Independently imported HTTP implementations are outside its scope.
32
+
33
+ ## Python 3.9+
34
+
35
+ ```sh
36
+ pip install uplinkswitch-hook
37
+ export UPLINKSWITCH_API_KEY="your-key"
38
+ python app.py
39
+ ```
40
+
41
+ The installed wheel includes a startup `.pth` file. Normal interpreter startup activates routing for httpx, httpx2 and requests, including the standard OpenAI and Anthropic clients. Install the wheel in the same environment that runs your application. Python's `-S` option disables site initialization and automatic activation. Existing httpx clients created before manual `install()` are not changed.
42
+
43
+ ## Configuration
44
+
45
+ | Variable | Meaning |
46
+ | --- | --- |
47
+ | `UPLINKSWITCH_API_KEY` | Required destination key. Unset means no interception. |
48
+ | `UPLINKSWITCH_BASE_URL` | Destination base URL; defaults to `https://api.uplinkswitch.com/v1`. Trailing slashes are removed. |
49
+ | `UPLINKSWITCH_INTERCEPT_HOSTS` | Comma-separated additional hostnames to intercept. |
50
+
51
+ If the destination base path ends in `/v1`, the original leading `/v1` is removed before joining paths. Existing authorization and x-api-key headers are replaced; when neither exists, both are added. Unrelated requests continue unchanged. Set environment variables before startup; installation is idempotent. Each active process prints one destination-host activation line to stderr. Node also prints one line when its key is unset.
52
+
53
+ ## Docker
54
+
55
+ ```dockerfile
56
+ ENV NODE_OPTIONS="-r @uplinkswitch/hook/register" UPLINKSWITCH_API_KEY=""
57
+ # Supply UPLINKSWITCH_API_KEY at runtime using your secret manager.
58
+ CMD ["node", "app.js"]
59
+ ```
60
+
61
+ ## Sister brands
62
+
63
+ Use the chosen brand's API key and either base URL:
64
+
65
+ ```sh
66
+ export UPLINKSWITCH_BASE_URL="https://api.pentestllm.ai/v1"
67
+ export UPLINKSWITCH_API_KEY="your-pentestllm-key"
68
+ # Or:
69
+ export UPLINKSWITCH_BASE_URL="https://api.uncensoredllm.ai/v1"
70
+ export UPLINKSWITCH_API_KEY="your-uncensoredllm-key"
71
+ ```
72
+
73
+ The hooks collect no telemetry: no request content or keys are logged, and intercepted requests are sent only to the configured base URL. The single activation line contains the destination host. Unrelated traffic retains its original destination; HTTP clients retain their normal redirect behavior.
74
+
75
+ ## Development
76
+
77
+ Run `npm ci && node --test` in `packages/node-hook`. In `packages/python-hook`, create a venv with `python3 -m venv .venv`, install `.[test]`, `build`, and `twine`, build with `python -m build`, install the resulting wheel, and run `python -I -m pytest`. Tests use only a local HTTP server and fake keys.
78
+
79
+ MIT — Uplink Switch LLC.
@@ -0,0 +1,6 @@
1
+ uplinkswitch_hook/__init__.py,sha256=JbwRM5kd4Q3wUj2hUAHJMRvJcAjex9SKypwoVajiifs,5004
2
+ uplinkswitch_hook/_pth.py,sha256=YiwrKfJ5soSJgAMR0gKjcq6HjLU3y5_7QrjMX0OImG0,92
3
+ uplinkswitch_hook.pth,sha256=emszSSAnrVYAHP3j3s4kKX46PiF92O5OEdeEK0w2HhY,30
4
+ uplinkswitch_hook-0.1.0.dist-info/METADATA,sha256=AuXAMFI1HrhT16Vw5jQsFgvsb2EspdOfJEdFhbOSC9Y,3813
5
+ uplinkswitch_hook-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ uplinkswitch_hook-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
uplinkswitch_hook.pth ADDED
@@ -0,0 +1 @@
1
+ import uplinkswitch_hook._pth