#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 """Minimal client of the EmbeddingGemma 2 server (standard library only). python3 client.py "What causes the northern lights?" "Charged solar particles hit the atmosphere." python3 client.py --prompt-name SearchQuery --dimensions 256 "northern lights" python3 client.py --image photo.jpg --audio clip.wav "a dog barking in a park" # one embedding per input """ from __future__ import annotations import argparse import base64 import json import math import sys import urllib.error import urllib.request def post(url: str, payload: dict, timeout: float = 300.0): req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=timeout) as r: return r.status, json.loads(r.read() or b"{}") except urllib.error.HTTPError as e: try: return e.code, json.loads(e.read() or b"{}") except Exception: # noqa: BLE001 return e.code, {} def get_json(url: str, timeout: float = 10.0): with urllib.request.urlopen(url, timeout=timeout) as r: return json.loads(r.read()) def b64file(path: str) -> str: with open(path, "rb") as f: return base64.b64encode(f.read()).decode("ascii") def embed(base: str, inputs, **opts): """Embeddings (lists of floats): /v1/embeddings for plain texts without options, /embed otherwise.""" if all(isinstance(x, str) for x in inputs) and set(opts) <= {"prompt_name", "dimensions"}: code, body = post(base.rstrip("/") + "/v1/embeddings", {"input": list(inputs), **opts}) if code != 200: raise RuntimeError(f"HTTP {code}: {body}") return [d["embedding"] for d in sorted(body["data"], key=lambda d: d["index"])] code, body = post(base.rstrip("/") + "/embed", {"inputs": list(inputs), **opts}) if code != 200: raise RuntimeError(f"HTTP {code}: {body}") return body["embeddings"] def cosine(a, b) -> float: num = sum(x * y for x, y in zip(a, b)) return num / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)) + 1e-30) def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("texts", nargs="*") ap.add_argument("--url", default="http://127.0.0.1:20000") ap.add_argument("--image", action="append", default=[]) ap.add_argument("--audio", action="append", default=[]) ap.add_argument("--prompt-name", default=None) ap.add_argument("--dimensions", type=int, default=None) a = ap.parse_args() inputs = list(a.texts) + [{"image": b64file(p)} for p in a.image] + [{"audio": b64file(p)} for p in a.audio] if not inputs: ap.error("give texts, --image or --audio") opts = {} if a.prompt_name: opts["prompt_name"] = a.prompt_name if a.dimensions: opts["dimensions"] = a.dimensions e = embed(a.url, inputs, **opts) print(json.dumps({"dim": len(e[0]), "first": [round(v, 6) for v in e[0][:8]]})) for i in range(len(e)): print(" ".join(f"{cosine(e[i], e[j]):7.4f}" for j in range(len(e)))) return 0 if __name__ == "__main__": sys.exit(main())