Defining AI workflows
AI workflows typically require more than just a model call. They need pre- and post-processing steps like retrieving context, managing session history, reformatting inputs, validating outputs, or combining multiple model responses.
A flow is a special Genkit function that wraps your AI logic to provide:
- Type-safe inputs and outputs: Define schemas using Pydantic Models for static and runtime validation
- Streaming support: Stream partial responses or custom data
- Developer UI integration: Test and debug flows with visual traces
- Easy deployment: Deploy as HTTP endpoints to any platform
Flows are lightweight. They’re written like regular functions with minimal abstraction.
Defining and calling flows
Section titled “Defining and calling flows”In its simplest form, a flow just wraps a function. The following example wraps a function that makes a model generation request:
from genkit import Genkitfrom genkit_google_genai import GoogleAIfrom pydantic import BaseModel, Field
ai = Genkit( plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'),)
class MenuSuggestionInput(BaseModel): theme: str = Field(description='Restaurant theme')
class MenuSuggestionOutput(BaseModel): menu_item: str = Field(description='Generated menu item')
@ai.flow()async def menu_suggestion_flow(input: MenuSuggestionInput) -> MenuSuggestionOutput: """Generate a menu item suggestion based on a theme.""" response = await ai.generate( prompt=f'Invent a menu item for a {input.theme} themed restaurant.', ) return MenuSuggestionOutput(menu_item=response.text)The flow name defaults to the function name and the description to the
docstring. Pass name= or description= to @ai.flow() to override them.
Input and output schemas come from the type hints.
Just by wrapping your generate calls like this, you add some functionality: doing so lets you run the flow from the Genkit CLI and from the developer UI, and is a requirement for several of Genkit’s features, including deployment and observability (later sections discuss these topics).
Input and output schemas
Section titled “Input and output schemas”One of the most important advantages Genkit flows have over directly calling a model API is type safety of both inputs and outputs. When defining flows, you can define schemas for them.
You can define schemas using Pydantic models. While you can use primitive types directly as input and output parameters, prefer Pydantic model schemas:
- Better developer experience: Model-based schemas render labeled input fields in the Developer UI.
- Backward-compatible evolution: Adding optional fields to a Pydantic input or output model preserves wire compatibility for existing callers.
Here’s a refinement of the last example, which defines a flow that takes a string as input and outputs an object:
from pydantic import BaseModel, Field
class MenuSuggestionInput(BaseModel): theme: str = Field(description='Restaurant theme')
class MenuItemSchema(BaseModel): dishname: str = Field(description='Name of the dish') description: str = Field(description='Description of the dish')
@ai.flow()async def menu_suggestion_flow(input: MenuSuggestionInput) -> MenuItemSchema: """Generate a menu item suggestion based on a theme.""" response = await ai.generate( prompt=f'Invent a menu item for a {input.theme} themed restaurant.', output_schema=MenuItemSchema, ) if response.output is None: raise RuntimeError(f'Response did not satisfy schema: {response.error}') return response.outputNote that the schema of a flow does not necessarily have to line up with the schema of the model generation calls within the flow (in fact, a flow might not even contain model calls). Here’s a variation of the example that uses the structured output to format a simple string, which the flow returns.
from pydantic import BaseModel, Field
class MenuSuggestionInput(BaseModel): theme: str = Field(description='Restaurant theme')
class MenuItemSchema(BaseModel): dishname: str = Field(description='Name of the dish') description: str = Field(description='Description of the dish')
class FormattedMenuOutput(BaseModel): formatted_menu_item: str = Field(description='Formatted menu item in markdown')
@ai.flow()async def menu_suggestion_flow(input: MenuSuggestionInput) -> FormattedMenuOutput: """Generate a menu item suggestion based on a theme.""" response = await ai.generate( prompt=f'Invent a menu item for a {input.theme} themed restaurant.', output_schema=MenuItemSchema, ) if response.output is None: raise RuntimeError(f'Response did not satisfy schema: {response.error}') output = response.output return FormattedMenuOutput( formatted_menu_item=f'**{output.dishname}**: {output.description}' )Calling flows
Section titled “Calling flows”Once you’ve defined a flow, you can call it from your code:
item = await menu_suggestion_flow( MenuSuggestionInput(theme='bistro'), context={'uid': 'user-123'},)print(item)# => menu_item='Truffle Croque Monsieur'
# Call .run() when you need the trace ID or an on_chunk callbackresult = await menu_suggestion_flow.run(MenuSuggestionInput(theme='bistro'))print(result.response)# => menu_item='Truffle Croque Monsieur'.run() wraps the flow’s output: read it from .response, and the trace ID
from .trace_id.
The argument to the flow must conform to the input schema.
If you defined an output schema, the flow response will conform to it. For
example, if you set the output schema to MenuItemSchema, the flow output will
contain its properties:
item = await menu_suggestion_flow(MenuSuggestionInput(theme='bistro'))print(item.dishname)print(item.description)Streaming flows
Section titled “Streaming flows”Flows support streaming using an interface similar to the model generation streaming interface. Streaming is useful when your flow generates a large amount of output, because you can present the output to the user as it’s being generated, which improves the perceived responsiveness of your app. As a familiar example, chat-based LLM interfaces often stream their responses to the user as they are generated.
Here’s an example of a flow that supports streaming:
from genkit import FlowContextfrom pydantic import BaseModel, Field
class MenuSuggestionInput(BaseModel): theme: str = Field(description='Restaurant theme')
class MenuOutput(BaseModel): theme: str = Field(description='Restaurant theme') menu_item: str = Field(description='Generated menu item')
@ai.flow()async def menu_suggestion_flow( input: MenuSuggestionInput, ctx: FlowContext[str],) -> MenuOutput: """Generate a menu item suggestion based on a theme.""" stream_response = ai.generate_stream( prompt=f'Invent a menu item for a {input.theme} themed restaurant.', ) async for chunk in stream_response.stream: ctx.send_chunk(chunk.text)
final_response = await stream_response.response
return MenuOutput( theme=input.theme, menu_item=final_response.text, )The optional second parameter ctx: FlowContext[ChunkT] exposes per-request
context (ctx.context) and ctx.send_chunk(...). Call ctx.send_chunk(...)
whenever your flow has an incremental chunk to emit, either forwarding chunks
from ai.generate_stream() or sending your own progress updates between steps.
Calling streaming flows
Section titled “Calling streaming flows”flow.stream() returns a StreamResponse exposing an async stream iterator
and an awaitable response future:
stream_response = menu_suggestion_flow.stream( MenuSuggestionInput(theme='bistro'))async for chunk in stream_response.stream: print(chunk)
print(await stream_response.response)To cancel an in-flight flow run before consuming all chunks, wrap .stream() in async with. Exiting the block cleanly terminates the flow:
async with menu_suggestion_flow.stream( MenuSuggestionInput(theme='bistro')) as stream_response: async for chunk in stream_response.stream: print(chunk) if should_stop(): breakThe chunk type (ChunkT in FlowContext[ChunkT]) does not have to
match the flow’s final return type.
Running flows from the command line
Section titled “Running flows from the command line”You can run flows from the command line using the Genkit CLI tool:
genkit flow:run menu_suggestion_flow '{"theme": "French"}' -- uv run main.pyFor streaming flows, you can print the streaming output to the console by adding
the -s flag:
genkit flow:run menu_suggestion_flow '{"theme": "French"}' -s -- uv run main.pyRunning a flow from the command line is useful for testing a flow, or for running flows that perform tasks needed on an ad hoc basis—for example, to run a flow that ingests a document into your vector database.
Debugging flows
Section titled “Debugging flows”One of the advantages of encapsulating AI logic within a flow is that you can test and debug the flow independently from your app using the Genkit developer UI.
To start the developer UI, run the following command from your project directory:
genkit start -- uv run main.pyUpdate uv run main.py to match the way you normally run your app.
From the Run tab of developer UI, you can run any of the flows defined in your project:
After you’ve run a flow, you can inspect a trace of the flow invocation by either clicking View trace or looking on the Inspect tab.
In the trace viewer, you can see details about the execution of the entire flow, as well as details for each of the individual steps within the flow.
Flow steps
Section titled “Flow steps”Each of Genkit’s fundamental actions shows up as separate steps in the trace viewer:
ai.generate()ai.embed()
If you want to include other code in your traces (for example retrieval against
your own vector store, or calls to third-party libraries), wrap it in an
ai.run() call.
For example, here’s a flow with two steps: the first step retrieves a menu using
some unspecified method, and the second step includes the menu in a generate()
call.
from genkit import Genkitfrom genkit_google_genai import GoogleAIfrom pydantic import BaseModel, Field
ai = Genkit( plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'),)
class MenuQuestionInput(BaseModel): question: str = Field(description="User's question about today's menu")
class MenuQuestionOutput(BaseModel): answer: str = Field(description="Answer to the user's question")
@ai.flow()async def menu_question_flow(input: MenuQuestionInput) -> MenuQuestionOutput: """Answer questions about today's menu.""" async def retrieve_daily_menu() -> str: # Retrieve today's menu. (This could be a database access or simply # fetching the menu from your website.) # # ... # return "Soup: tomato bisque\nMain: roast chicken\nDessert: panna cotta"
menu = await ai.run(name='retrieve-daily-menu', fn=retrieve_daily_menu)
response = await ai.generate( system="Help the user answer questions about today's menu.", prompt=f"Today's menu:\n{menu}\n\nQuestion:\n{input.question}", ) return MenuQuestionOutput(answer=response.text)Because the retrieval step is wrapped in an ai.run() call, it’s included as a
step in the trace viewer:

Deploying flows
Section titled “Deploying flows”You can deploy your flows directly as web API endpoints, ready for you to call from your app clients. Deployment is discussed in detail on several other pages, but this section gives brief overviews of your deployment options.
FastAPI
Section titled “FastAPI”Install genkit-fastapi, then mount the flow with serve_flow so requests use
the Genkit HTTP envelope ({"data": ...}):
import os
from fastapi import FastAPIfrom pydantic import BaseModel, Field
from genkit import Genkitfrom genkit_fastapi import serve_flowfrom genkit_google_genai import GoogleAI
ai = Genkit( plugins=[GoogleAI()], model=GoogleAI.gemini('gemini-flash-latest'),)
app = FastAPI()
class MenuSuggestionInput(BaseModel): theme: str = Field(description='Restaurant theme')
class MenuSuggestionOutput(BaseModel): menu_item: str = Field(description='Generated menu item')
@ai.flow()async def menu_suggestion_flow(input: MenuSuggestionInput) -> MenuSuggestionOutput: """Generate a menu item suggestion based on a theme.""" response = await ai.generate( prompt=f'Invent a menu item for a {input.theme} themed restaurant.', ) return MenuSuggestionOutput(menu_item=response.text)
app.include_router(serve_flow(menu_suggestion_flow))
if __name__ == '__main__': import uvicorn
uvicorn.run( 'main:app', host='0.0.0.0', port=int(os.environ.get('PORT', 3400)), )To attach per-request context (auth, tenancy, and so on), pass a FastAPI dependency as context_dependency. Its return value must be a dict; Genkit exposes that dict on the flow as ctx.context:
from fastapi import Headerfrom genkit import FlowContext
async def user_context(authorization: str = Header(...)) -> dict[str, object]: return {'auth_token': authorization.removeprefix('Bearer ').strip()}
@ai.flow()async def menu_suggestion_flow( input: MenuSuggestionInput, ctx: FlowContext,) -> MenuSuggestionOutput: """Generate a menu item suggestion based on a theme.""" token = ctx.context.get('auth_token') ...
app.include_router( serve_flow(menu_suggestion_flow, context_dependency=user_context),)For production, run your app with a production ASGI server (for example, Uvicorn with Gunicorn workers):
gunicorn -k uvicorn.workers.UvicornWorker -b 0.0.0.0:3400 main:appCalling deployed flows
Section titled “Calling deployed flows”serve_flow mounts each flow at /<flow name>, so the function name is the
route. Call it with a POST request:
curl -X POST "http://localhost:3400/menu_suggestion_flow" \ -H "Content-Type: application/json" -d '{"data": {"theme": "banana"}}'# => {"result":{"menu_item":"Banana Foster Crepes"}}For streaming responses, add the Accept: text/event-stream header. The server
sends data: {"message": ...} events for each chunk, then a final
data: {"result": ...} event:
curl -X POST "http://localhost:3400/menu_suggestion_flow" \ -H "Content-Type: application/json" \ -H "Accept: text/event-stream" \ -d '{"data": {"theme": "banana"}}'Pass base_path= to serve_flow to mount a flow at a different route. For the
error body and status codes, see
Errors and timeouts.
Learn more about deployment
Section titled “Learn more about deployment”For detailed deployment instructions and platform-specific guides, see:
-
FastAPI tutorial (
serve_flow, plus experimentalserve_agentingenkit_fastapi.exp)