Skip to content

Generating content with AI models

Genkit provides a unified interface for working with generative AI models from any supported provider. Configure a model plugin once, then call any model through the same API—making it easy to combine multiple models or swap one out as your app evolves.

If you want to run the code examples on this page, first complete the steps in the Get started guide. All of the examples assume that you have already installed Genkit as a dependency in your project.

Before you can use Genkit to start generating content, you need to load and configure a model plugin. If you’re coming from the Get started guide, you’ve already done this. Otherwise, see the Get started guide or the individual plugin’s documentation and follow the steps there before continuing.

In Genkit, the primary interface through which you interact with generative AI models is the generate() method.

The simplest generate() call takes a text prompt and uses the default model set on Genkit:

from genkit import Genkit
from genkit_google_genai import GoogleAI
ai = Genkit(
plugins=[GoogleAI()],
model=GoogleAI.gemini('gemini-flash-latest'),
)
async def main() -> None:
result = await ai.generate(
prompt='Invent a menu item for a pirate themed restaurant.',
)
print(result.text)
ai.run_main(main())

When you run this brief example it will print out the output of the generate() call, which will usually be Markdown text as in the following example:

## The Blackheart's Bounty
**A hearty stew of slow-cooked beef, spiced with rum and molasses, served in a
hollowed-out cannonball with a side of crusty bread and a dollop of tangy
pineapple salsa.**
**Description:** This dish is a tribute to the hearty meals enjoyed by pirates
on the high seas. The beef is tender and flavorful, infused with the warm spices
of rum and molasses. The pineapple salsa adds a touch of sweetness and acidity,
balancing the richness of the stew. The cannonball serving vessel adds a fun and
thematic touch, making this dish a perfect choice for any pirate-themed
adventure.

Run the script again and you’ll get a different output.

The preceding code sample sent the generation request to the default model, which you specified when you configured the Genkit instance.

You can also specify a model for a single generate() call by using a typed model reference helper from the plugin:

result = await ai.generate(
model=GoogleAI.gemini('gemini-pro-latest'),
prompt='Invent a menu item for a pirate themed restaurant.',
)

GoogleAI.gemini('<model-id>') takes the bare model ID, adds the googleai/ prefix, and returns a ModelRef[GeminiConfig] so type checkers can check config. Other families have their own helpers: GoogleAI.gemini_image(), GoogleAI.gemini_tts(), and GoogleAI.gemma(). Passing an ID from the wrong family raises GenkitError (INVALID_ARGUMENT).

Alternatively, specify the model by using a 'providerid/modelid' string identifier, where the provider prefix (such as 'googleai/' or 'vertexai/') is required so Genkit can route the request to the plugin:

result = await ai.generate(
model='googleai/gemini-pro-latest',
prompt='Invent a menu item for a pirate themed restaurant.',
)

GoogleAI and VertexAI resolve model IDs at request time, so any model the provider serves works, including models released after your plugin version. The plugin’s built-in model list only supplies default capabilities and type hints.

These examples also illustrate an important point: when you use generate() to make generative AI model calls, changing the model you want to use is simply a matter of passing a different value to the model parameter. By using generate() instead of the native model SDKs, you give yourself the flexibility to more easily use several different models in your app and change models in the future.

So far you have only seen examples of the simplest generate() calls. However, generate() also provides an interface for more advanced interactions with generative models, which you will see in the sections that follow.

Some models support providing a system prompt, which gives the model instructions as to how you want it to respond to messages from the user. You can use the system prompt to specify a persona you want the model to adopt, the tone of its responses, the format of its responses, and so on.

If the model you’re using supports system prompts, you can provide one with the system parameter:

result = await ai.generate(
system='You are a food industry marketing consultant.',
prompt='Invent a menu item for a pirate themed restaurant.',
)

For multi-turn conversations, pass the conversation history in messages instead of prompt. Each Message has a role ('system', 'user', 'model', or 'tool') and a list of content parts:

from genkit import Message, Part
result = await ai.generate(
system='You are a helpful travel assistant.',
messages=[
Message(role='user', content=[Part.from_text('Hello, can you help me plan a trip?')]),
Message(role='model', content=[Part.from_text('Of course! Where are you thinking of going?')]),
Message(role='user', content=[Part.from_text('I want to visit Japan for two weeks in spring.')]),
],
)

result.messages holds the system message, the history, and the model’s reply. Pass it back as messages on the next turn and leave out system=. For persistent sessions with automatic history management, use agents instead.

Pass generation settings through config using the model plugin’s typed config class (such as GeminiConfig) or a dict whose keys match that schema. Unknown keys in config raise GenkitError (INVALID_ARGUMENT) before the model is called:

from genkit_google_genai import GeminiConfig
result = await ai.generate(
prompt='Invent a menu item for a pirate themed restaurant.',
config=GeminiConfig(
max_output_tokens=400,
stop_sequences=['<end>', '<fin>'],
temperature=1.2,
top_p=0.4,
top_k=50,
),
)

Other request options:

  • context={'secrets': {'api_key': ...}} sets a per-request API key. Don’t put keys in config.
  • extra={...} on the config class passes fields the class doesn’t declare. The plugin merges them into the request body unchanged.
  • use=[...] attaches middleware.
from genkit_google_genai import GeminiConfig, GoogleAI
from genkit_middleware import Retry
result = await ai.generate(
model=GoogleAI.gemini('gemini-flash-latest'),
prompt='List the allergens in a classic basil pesto.',
config=GeminiConfig(
temperature=0.5,
extra={'generationConfig': {'mediaResolution': 'MEDIA_RESOLUTION_LOW'}},
),
context={'secrets': {'api_key': tenant_api_key}},
use=[Retry()],
)

The exact parameters that are supported depend on the individual model and model API. However, the parameters in the first GeminiConfig example are common to almost every model. The following is an explanation of these parameters:

max_output_tokens

LLMs operate on units called tokens. A token usually, but does not necessarily, map to a specific sequence of characters. When you pass a prompt to a model, one of the first steps it takes is to tokenize your prompt string into a sequence of tokens. Then, the LLM generates a sequence of tokens from the tokenized input. Finally, the sequence of tokens gets converted back into text, which is your output.

The maximum output tokens parameter simply sets a limit on how many tokens to generate using the LLM. Every model potentially uses a different tokenizer, but a good rule of thumb is to consider a single English word to be made of 2 to 4 tokens.

As stated earlier, some tokens might not map to character sequences. One such example is that there is often a token that indicates the end of the sequence: when an LLM generates this token, it stops generating more. Therefore, it’s possible and often the case that an LLM generates fewer tokens than the maximum because it generated the “stop” token.

stop_sequences

You can use this parameter to set the tokens or token sequences that, when generated, indicate the end of LLM output. The correct values to use here generally depend on how the model was trained, and are usually set by the model plugin. However, if you have prompted the model to generate another stop sequence, you might specify it here.

Note that you are specifying character sequences, and not tokens per se. In most cases, you will specify a character sequence that the model’s tokenizer maps to a single token.

The temperature, top-p, and top-k parameters together control how “creative” you want the model to be. Below are very brief explanations of what these parameters mean, but the more important point to take away is this: these parameters are used to adjust the character of an LLM’s output. The optimal values for them depend on your goals and preferences, and are likely to be found only through experimentation.

temperature

LLMs are fundamentally token-predicting machines. For a given sequence of tokens (such as the prompt) an LLM predicts, for each token in its vocabulary, the likelihood that the token comes next in the sequence. The temperature is a scaling factor by which these predictions are divided before being normalized to a probability between 0 and 1.

Low temperature values—between 0.0 and 1.0—amplify the difference in likelihoods between tokens, with the result that the model will be even less likely to produce a token it already evaluated to be unlikely. This is often perceived as output that is less creative. Although 0.0 is technically not a valid value, many models treat it as indicating that the model should behave deterministically, and to only consider the single most likely token.

High temperature values—those greater than 1.0—compress the differences in likelihoods between tokens, with the result that the model becomes more likely to produce tokens it had previously evaluated to be unlikely. This is often perceived as output that is more creative. Some model APIs impose a maximum temperature, often 2.0.

top_p

Top-p is a value between 0.0 and 1.0 that controls the number of possible tokens you want the model to consider, by specifying the cumulative probability of the tokens. For example, a value of 1.0 means to consider every possible token (but still take into account the probability of each token). A value of 0.4 means to only consider the most likely tokens, whose probabilities add up to 0.4, and to exclude the remaining tokens from consideration.

top_k

Top-k is an integer value that also controls the number of possible tokens you want the model to consider, but this time by explicitly specifying the maximum number of tokens. Specifying a value of 1 means that the model should behave deterministically.

You can experiment with the effect of these parameters on the output generated by different model and prompt combinations by using the Developer UI. Start the developer UI with the genkit start command and it will automatically load all of the models defined by the plugins configured in your project. You can quickly try different prompts and configuration values without having to repeatedly make these changes in code.

In the Google AI (GoogleAI) plugin, model aliases such as gemini-flash-latest point to the current release of a model family. While aliases are convenient during development and prototyping, model providers periodically update which snapshot an alias references, which can affect latency, cost, and output consistency. Gemini Enterprise (VertexAI) does not support -latest aliases and always requires a versioned model ID.

For production workloads that require consistent behavior, specify a versioned model ID:

result = await ai.generate(
model=GoogleAI.gemini('gemini-3.8-flash'),
prompt='Invent a menu item for a pirate themed restaurant.',
)

Before changing model versions in production, test against an evaluation dataset.

When using generative AI as a component in your application, you often want output in a format other than plain text. Even if you’re just generating content to display to the user, you can benefit from structured output simply for the purpose of presenting it more attractively to the user. But for more advanced applications of generative AI, such as programmatic use of the model’s output, or feeding the output of one model into another, structured output is a must.

In Genkit, you can request structured output from a model by specifying a schema when you call generate():

from pydantic import BaseModel
class MenuItemSchema(BaseModel):
name: str
description: str
calories: int
allergens: list[str]
result = await ai.generate(
prompt='Invent a menu item for a pirate themed restaurant.',
output_schema=MenuItemSchema,
)

Model output schemas are specified using the Pydantic Models. In addition to a schema definition language, Pydantic also provides runtime type checking, which bridges the gap between static Python types and the unpredictable output of generative AI models. Pydantic lets you write code that can rely on the fact that a successful generate call will always return output that conforms to your Python types.

When you specify a schema in generate(), Genkit does several things behind the scenes:

  • Augments the prompt with additional guidance about the desired output format. This also has the side effect of specifying to the model what content exactly you want to generate (for example, not only suggest a menu item but also generate a description, a list of allergens, and so on).
  • Parses the model output into a Pydantic object.
  • Verifies that the output conforms with the schema.

To get structured output from a successful generate call, use the response object’s output property:

menu_item = result.output # a MenuItemSchema instance, or None on failure
if menu_item:
print(menu_item.name)

When the model truncates output or emits JSON that fails schema validation, ai.generate() does not raise. Instead, result.output is None, result.text retains the raw model text, and result.error holds a Failure with reason == ErrorReason.INVALID_OUTPUT (see error types):

from genkit import ErrorReason
if result.error and result.error.reason == ErrorReason.INVALID_OUTPUT:
print(f'Schema validation failed: {result.error.message}')

Two practical ways to recover:

  • Use a larger model. Smaller models, such as some local models served through Ollama, often fail to emit JSON that matches a strict schema.
  • Retry generate(). If schema failures are rare, retry with backoff or pass the validation error back in a follow-up turn.

Stream tokens as they arrive with ai.generate_stream(). It returns a ModelStreamResponse exposing an async stream iterator and an awaitable response future:

result = ai.generate_stream(
prompt='Suggest a complete menu for a pirate themed restaurant.',
)
async for chunk in result.stream:
print(chunk.text, end='', flush=True)
complete_text = (await result.response).text

To abort an in-flight stream early before reading all chunks, wrap generate_stream() in async with. Exiting the block cleanly cancels the underlying generator:

async with ai.generate_stream(
prompt='Suggest a complete menu for a pirate themed restaurant.',
) as result:
async for chunk in result.stream:
print(chunk.text, end='', flush=True)
if should_stop():
break

Streaming also works with structured output:

from pydantic import BaseModel
class MenuItemSchema(BaseModel):
name: str
description: str
calories: int
allergens: list[str]
class MenuSchema(BaseModel):
starters: list[MenuItemSchema]
mains: list[MenuItemSchema]
desserts: list[MenuItemSchema]
result = ai.generate_stream(
prompt='Invent a menu for a pirate themed restaurant.',
output_schema=MenuSchema,
)
async for chunk in result.stream:
print(chunk.output)
print((await result.response).output)

Streaming structured output works a little differently from streaming text. Each chunk’s output is a partial MenuSchema built from all the text received so far, and fields the model hasn’t reached yet are None. Every chunk of structured output supersedes the one before it.

For example, here’s what the first three outputs from the prior example might look like:

starters=None mains=None desserts=None
starters=[MenuItemSchema(name='Kraken Tentacle Calamari', description='Crispy', calories=None, allergens=None)] mains=None desserts=None
starters=[MenuItemSchema(name='Kraken Tentacle Calamari', description='Crispy fried squid tentacles served with a spicy mermaid tear aioli.', calories=450, allergens=None)] mains=None desserts=None

The examples you’ve seen so far have used text strings as model prompts. While this remains the most common way to prompt generative AI models, many models can also accept other media as prompts. Media prompts are most often used in conjunction with text prompts that instruct the model to perform some operation on the media, such as to caption an image or transcribe an audio recording.

The ability to accept media input and the types of media you can use are completely dependent on the model and its API. For example, Gemini models accept images, video, and audio as prompts.

To provide a media prompt to a model that supports it, instead of passing a simple text prompt to generate, pass a list consisting of a media part and a text part:

from genkit import Part
result = await ai.generate(
prompt=[
Part.from_media(url='https://example.com/photo.jpg', content_type='image/jpeg'),
Part.from_text('Compose a poem about this image.'),
],
)

In the above example, you specified an image using a publicly-accessible HTTPS URL. You can also pass media data directly by encoding it as a data URL. For example:

import base64
from pathlib import Path
from genkit import Part
image_bytes = Path('image.jpg').read_bytes()
base64_encoded_image = base64.b64encode(image_bytes).decode('utf-8')
result = await ai.generate(
prompt=[
Part.from_media(
url=f'data:image/jpeg;base64,{base64_encoded_image}',
content_type='image/jpeg',
),
Part.from_text('Compose a poem about this image.'),
],
)

All models that support media input support both data URLs and HTTPS URLs. Some model plugins add support for other media sources. For example, the Gemini Enterprise (VertexAI) plugin also lets you use Cloud Storage (gs://) URLs.

Image, video, and speech models use the same generate() call. Generated media arrives in result.media, a list of Media values with url and content_type. Image and speech models return base64 data URLs:

import base64
from pathlib import Path
from genkit_google_genai import GoogleAI
result = await ai.generate(
model=GoogleAI.gemini_image('gemini-3.1-flash-image'),
prompt='A sunlit sourdough bakery counter with loaves on cooling racks.',
)
for media in result.media:
print(media.content_type)
# => image/jpeg
_, data = media.url.split(',', 1)
Path('bakery.jpg').write_bytes(base64.b64decode(data))

See the Google Generative AI plugin for image, video, music, and speech models and their config classes.

Problems found before the model is called, such as an unregistered model or an unknown config key, raise GenkitError. Once generation starts, generate() does not raise: provider errors (such as UNAVAILABLE or RESOURCE_EXHAUSTED), tool failures, and hitting max_turns come back on result.error as a Failure, with result.finish_reason set to FinishReason.FAILED or FinishReason.ABORTED. Check result.error before using the result:

result = await ai.generate(prompt='Suggest a dish for a guest with a nut allergy.')
if result.error:
print(result.error.status, result.error.message)
# => UNAVAILABLE This model is currently experiencing high demand. ...
else:
print(result.text)

To bound a single Gemini call, set timeout in seconds on the config, for example GeminiConfig(timeout=60). See Error types for the full rules, including how to resend result.messages after a failed tool loop.

Middleware wraps generate() calls to add behavior such as retries or model fallbacks. Pass instances in use=[...]. See Middleware for the built-in middleware and how to write your own.

  • Many of your users will have interacted with large language models for the first time through chatbots. Although LLMs are capable of much more than simulating conversations, it remains a familiar and useful style of interaction. Read Agents to learn how Genkit manages multi-turn sessions, history, and tools for you.
  • One way to enhance the capabilities of LLMs is to prompt them with a list of ways they can request more information from you, or request you to perform some action on their behalf. This is called tool calling or function calling. Models trained to support this feature can respond with specially-formatted responses, which indicate to the calling application that it should take some action and send the result back to the LLM. Read more at the Tool calling page.
  • Retrieval-augmented generation (RAG) is a technique used to introduce domain-specific information into a model’s output. It’s accomplished by inserting relevant information into a model’s prompt before passing it to the model. A complete RAG implementation requires you to bring together several technologies: text embedding generation models, vector databases, and large language models. See the Retrieval-augmented generation (RAG) page to learn how Genkit streamlines the process of coordinating these various elements.

As a software engineer, you’re probably accustomed to deterministic systems, where a given input always produces the same output. However, with AI models being probabilistic, the output can vary based on subtle nuances in the input, the model’s training data, and even deliberately-introduced randomness via parameters like temperature.

Genkit’s evaluators are structured ways to assess the quality of your LLM’s responses using a variety of strategies. Read more on the Evaluation page.

Genkit Python 0.13 is the last release with evaluators (ai.define_evaluator(), ai.evaluate(), genkit.evaluator) and the genkit-evaluators package. Genkit 1.0 cuts evaluators from the 1.0 release; evaluation will return as an additive feature in a later release. To keep using evaluators, pin genkit==0.13.*.