Skip to content

Gemma 4 API

Gemma 4 můžete přes API volat třemi hlavními způsoby: lokálně přes Ollama, přes Google AI Studio (bezplatný tier) nebo přes OpenRouter (OpenAI-kompatibilní vrstva). Každý se hodí pro trochu jiný scénář.

Pokud máte Ollamu nainstalovanou, API server běží na localhost:11434. Nepotřebujete API klíč, nenarazíte na limity a vše funguje zcela zdarma.

import requests
response = requests.post("http://localhost:11434/api/generate", json={
"model": "gemma4",
"prompt": "Explain async/await in Python like I'm 10",
"stream": False
})
print(response.json()["response"])
Terminal window
curl http://localhost:11434/api/generate -d '{
"model": "gemma4",
"prompt": "Explain async/await in Python like I am 10",
"stream": false
}'
const response = await fetch("http://localhost:11434/api/generate", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "gemma4",
prompt: "Explain async/await in Python like I'm 10",
stream: false,
}),
});
const data = await response.json();
console.log(data.response);

Pro konverzace s historií zpráv použijte:

import requests
response = requests.post("http://localhost:11434/api/chat", json={
"model": "gemma4",
"messages": [
{"role": "system", "content": "You are a helpful coding tutor."},
{"role": "user", "content": "What's the difference between a list and a tuple?"}
],
"stream": False
})
print(response.json()["message"]["content"])
import requests
import json
response = requests.post("http://localhost:11434/api/generate", json={
"model": "gemma4",
"prompt": "Write a short story about a debugging session at 3am",
"stream": True
}, stream=True)
for line in response.iter_lines():
if line:
chunk = json.loads(line)
print(chunk.get("response", ""), end="", flush=True)

Google nabízí Gemma 4 přes AI Studio API s bezplatným tierem. Služba běží na infrastruktuře Google TPU, takže odpovědi bývají rychlé.

  1. Přejděte na aistudio.google.com
  2. Klikněte na „Get API Key“
  3. Vytvořte klíč
Terminal window
pip install google-generativeai
import google.generativeai as genai
genai.configure(api_key="YOUR_API_KEY")
model = genai.GenerativeModel("gemma-4-27b-it")
response = model.generate_content("Write a Python decorator for retry logic")
print(response.text)
Terminal window
curl "https://generativelanguage.googleapis.com/v1beta/models/gemma-4-27b-it:generateContent?key=YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{
"parts": [{"text": "Write a Python decorator for retry logic"}]
}]
}'
Limit Hodnota
Požadavky za minutu (RPM) 15
Požadavky za den (RPD) 1 500
Tokeny za minutu 1 000 000
import google.generativeai as genai
from google.api_core import exceptions
genai.configure(api_key="YOUR_API_KEY")
model = genai.GenerativeModel("gemma-4-27b-it")
try:
response = model.generate_content("Your prompt here")
print(response.text)
except exceptions.ResourceExhausted:
print("Rate limit hit. Wait a minute and try again.")
except exceptions.InvalidArgument as e:
print(f"Bad request: {e}")
except exceptions.NotFound:
print("Model not found. Check the model name.")
import google.generativeai as genai
genai.configure(api_key="YOUR_API_KEY")
model = genai.GenerativeModel("gemma-4-27b-it")
response = model.generate_content(
"Write a short story about a debugging session at 3am",
stream=True
)
for chunk in response:
print(chunk.text, end="", flush=True)

OpenRouter používá stejný formát jako OpenAI API. Pokud už máte kód pro GPT, obvykle stačí změnit identifikátor modelu.

  1. Registrace na openrouter.ai
  2. Dobití kreditu (minimum 5 USD)
  3. Vygenerování API klíče
import requests
response = requests.post(
"https://openrouter.ai/api/v1/chat/completions",
headers={
"Authorization": "Bearer YOUR_OPENROUTER_KEY",
"Content-Type": "application/json",
},
json={
"model": "google/gemma-4-27b-it",
"messages": [
{"role": "user", "content": "Compare React and Vue in 5 bullet points"}
],
},
)
print(response.json()["choices"][0]["message"]["content"])
from openai import OpenAI
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key="YOUR_OPENROUTER_KEY",
)
response = client.chat.completions.create(
model="google/gemma-4-27b-it",
messages=[
{"role": "user", "content": "Explain monads in plain English"}
],
)
print(response.choices[0].message.content)
from openai import OpenAI
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key="YOUR_OPENROUTER_KEY",
)
stream = client.chat.completions.create(
model="google/gemma-4-27b-it",
messages=[{"role": "user", "content": "Write a short story"}],
stream=True,
)
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
print(content, end="", flush=True)
Ollama (lokální) Google AI Studio OpenRouter
Cena Zdarma Bezplatný tier (15 RPM) Platba za token
Rychlost Závisí na HW Rychlé (Google TPU) Rychlé
Soukromí Kompletní (offline) Data jdou na Google Data jdou k poskytovateli
Limity Žádné 15 RPM / 1 500 RPD Podle kreditu
OpenAI kompatibilní Částečně Ne (vlastní SDK) Ano
Ideální pro Soukromí, vývoj Prototypy zdarma Produkci, práci s více modely
  • „Connection refused“ v Ollamě — zkontrolujte, že Ollama server běží (ollama serve)
  • „Model not found“ v Google AI Studio — názvy modelů se mění, takže si ověřte aktuální ID v dokumentaci
  • Pomalé odpovědi v Ollamě — model pravděpodobně běží na CPU; pro GPU setup viz Gemma 4 na DigitalOcean
  • Timeouty — u delších generování zvyšte timeout HTTP klienta