Spaces:
Configuration error
Configuration error
Download clients/python/google_gemini.py from AnthropicallyHuggingFaces/ai-platform-toolbox: direct link, hf CLI and curl.
- Browser
- Download file 1.4 kB
-
https://huggingface.co/spaces/AnthropicallyHuggingFaces/ai-platform-toolbox/resolve/main/clients/python/google_gemini.py
- Command line
-
hf download hf://spaces/AnthropicallyHuggingFaces/ai-platform-toolbox/clients/python/google_gemini.py
-
curl -L -o google_gemini.py https://huggingface.co/spaces/AnthropicallyHuggingFaces/ai-platform-toolbox/resolve/main/clients/python/google_gemini.py
1.4 kB
| """Google Gemini client - generateContent via generativelanguage.googleapis.com. | |
| Key comes from GOOGLE_API_KEY env (never commit a real key). | |
| """ | |
| import os | |
| import requests | |
| BASE = os.getenv("GEMINI_API_BASE", "https://generativelanguage.googleapis.com/v1beta") | |
| KEY = os.getenv("GOOGLE_API_KEY") | |
| def _req(method, path, **kwargs): | |
| if not KEY: | |
| raise RuntimeError("GOOGLE_API_KEY not set") | |
| return requests.request(method, f"{BASE}{path}", params={"key": KEY}, **kwargs) | |
| def generate_content(text, model="gemini-flash-latest", **kwargs): | |
| body = {"contents": [{"parts": [{"text": text}]}], **kwargs} | |
| r = _req("POST", f"/models/{model}:generateContent", json=body, timeout=120) | |
| try: | |
| return r.json() | |
| except Exception: | |
| return {"status_code": r.status_code, "text": r.text} | |
| def chat(messages, model="gemini-flash-latest", **kwargs): | |
| """Simple OpenAI-style -> Gemini mapping for the router fallback chain.""" | |
| system_parts = [m["content"] for m in messages if m.get("role") == "system"] | |
| user_text = " ".join(m["content"] for m in messages if m.get("role") in ("user", "assistant", "tool")) | |
| kwargs.setdefault("systemInstruction", {"parts": [{"text": system_parts[-1]}]} if system_parts else None) | |
| return generate_content(user_text, model=model, **kwargs) | |
| def list_models(): | |
| r = _req("GET", "/models", timeout=30) | |
| return r.json() | |