Get started
Cheatsheet

Google Gemini

The google-genai Python calls you reach for: requests, settings, chat, streaming, JSON, tools, embeddings, tokens and errors.

Practice this path

Set up

Keep the key in an environment variable, never in the code.

  • export GEMINI_API_KEY="your-key"

    Make the key available to the SDK (new terminal, set it again)

  • from google import genai
    from google.genai import types, errors

    The imports almost every script starts with

  • client = genai.Client()

    Create a client; it reads GEMINI_API_KEY (or GOOGLE_API_KEY) itself

  • for m in client.models.list(): print(m.name)

    List the available models

  • info = client.models.get(model="gemini-3.8-flash")

    Read one model's token limits (input_token_limit, output_token_limit)

Generate text

  • response = client.models.generate_content(
        model="gemini-3.8-flash", contents="Explain DNS.")

    One request, one response

  • print(response.text)

    The answer text (None when blocked or when only a function call came back)

  • response.candidates[0].finish_reason.name

    Why it stopped: STOP, MAX_TOKENS or SAFETY

  • response.usage_metadata.total_token_count

    Tokens used (also prompt_token_count and candidates_token_count)

  • config=types.GenerateContentConfig(
        system_instruction="Answer in one sentence.")

    Standing rules for role, tone and format

Settings

  • types.GenerateContentConfig(temperature=0)

    Repeatable answers (0 to 2; higher is more varied)

  • types.GenerateContentConfig(max_output_tokens=200)

    Cap the answer length (a cut answer ends with MAX_TOKENS)

  • types.GenerateContentConfig(stop_sequences=["END"])

    End the answer when this text appears

  • types.GenerateContentConfig(candidate_count=3, seed=7)

    Several answers; the seed makes sampling repeatable

  • types.GenerateContentConfig(top_p=0.9, top_k=20)

    Trim the word choices the model samples from

Chat and streaming

  • chat = client.chats.create(model="gemini-3.8-flash")
    print(chat.send_message("Hello!").text)

    A conversation that resends its history for you

  • chat.get_history()

    The turns so far, as a list of Content with role and parts

  • client.chats.create(model=..., history=[types.Content(role="user", parts=[types.Part.from_text(text="Hi")])])

    Start a chat from saved turns

  • for chunk in client.models.generate_content_stream(model=..., contents="..."):
        print(chunk.text, end="", flush=True)

    Print the answer as it arrives

  • for chunk in chat.send_message_stream("..."): print(chunk.text, end="")

    Stream a chat reply

Structured output

  • config=types.GenerateContentConfig(
        response_mime_type="application/json",
        response_schema=schema)

    Ask for JSON that fits a schema

  • schema = {"type": "OBJECT",
              "properties": {"name": {"type": "STRING"}, "age": {"type": "INTEGER"}},
              "required": ["name"]}

    A schema as a plain dict

  • {"type": "STRING", "enum": ["billing", "technical", "other"]}

    Limit a field to listed values

  • response_schema=list[Recipe]    # Recipe is a TypedDict

    Use Python types instead of a dict

  • data = json.loads(response.text)    # or response.parsed

    Turn the answer into Python data (validate it: it can be cut off)

Function calling

  • config=types.GenerateContentConfig(tools=[get_weather])

    Automatic mode: the SDK runs your Python function when the model asks

  • def get_weather(city: str) -> dict:
        """Get the weather for a city."""

    The name, docstring and type hints are what the model sees

  • types.FunctionDeclaration(name="get_weather", description="...", parameters=types.Schema(type="OBJECT", properties={...}))

    Declare a function by hand

  • call = response.function_calls[0]; call.name; call.args

    Read the model's request in manual mode

  • types.Part.from_function_response(name=call.name, response=result)

    Send your function's result back in a user turn

Embeddings

  • result = client.models.embed_content(
        model="gemini-embedding-001", contents=["a", "b"])

    Embed one text or a batch of texts

  • vectors = [e.values for e in result.embeddings]

    The list of numbers for each text

  • types.EmbedContentConfig(output_dimensionality=256)

    Ask for shorter vectors (use the same size everywhere)

  • dot(a, b) / (sqrt(dot(a, a)) * sqrt(dot(b, b)))

    Cosine similarity: higher means closer in meaning

Tokens, errors and safety

  • client.models.count_tokens(model=..., contents=text).total_tokens

    Count the input tokens before you send

  • try:
        ...
    except errors.APIError as e:
        print(e.code, e.status, e.message)

    Catch API errors (ClientError is 4xx, ServerError is 5xx)

  • if e.code == 429 or e.code >= 500: time.sleep(delay); delay *= 2

    Retry only rate limits and server errors, with growing waits

  • genai.Client(http_options=types.HttpOptions(timeout=5000))

    A request deadline, in milliseconds

  • response.prompt_feedback.block_reason

    Set when the prompt itself was blocked (candidates is then empty)

  • types.SafetySetting(category="HARM_CATEGORY_HARASSMENT", threshold="BLOCK_MEDIUM_AND_ABOVE")

    Choose how strict the safety filter is, for each harm category

Cheatsheet for the Google Gemini path · Deboistech · All cheatsheets