Implementing agentic patterns
Building powerful AI systems involves more than just calling a model; it requires structuring interactions in a way that balances reliability with flexibility. This is the core idea behind the agentic scale.
At one end of the scale, you have Workflows: structured, predictable sequences of tasks. They are highly reliable but less flexible. At the other end, you have Agents: autonomous systems that can reason, plan, and use tools to handle complex, unpredictable tasks. They are highly flexible but can be less reliable.
The key to building effective AI is to find the right point on this scale for your use case, often creating a hybrid that combines the best of both worlds. This guide explores key patterns along the agentic scale and shows you how to implement them using Genkit’s core primitives like flows, tools, and interrupts.
All of the code samples in this guide can be found in the agentic-patterns sample on GitHub.
Patterns on the agentic scale
Section titled “Patterns on the agentic scale”We will cover the following patterns, moving from more structured workflows to more autonomous agents:
- Sequential Processing: The simplest workflow, decomposing a task into a fixed sequence of LLM calls.
- Conditional Routing: Adding branching logic to a workflow based on an LLM’s output.
- Parallel Execution: Running multiple LLM calls concurrently for speed or to gather diverse perspectives.
- Tool Calling: Introducing flexibility by allowing an LLM to call external functions to retrieve information or perform actions.
- Iterative Refinement: Creating a feedback loop where an LLM critiques and improves its own work.
- Autonomous Operation: Building agents that can independently plan and execute tasks to achieve a goal.
- Stateful Interactions: Turning any workflow into a stateful, conversational experience by managing history.
Workflow: Sequential processing
Section titled “Workflow: Sequential processing”This is the simplest workflow pattern, where a task is broken down into a fixed sequence of steps. Each step processes the output of the previous one. Genkit flows are the ideal tool for orchestrating these sequences.
A key advantage of this pattern is the ability to use different models for different steps. For example, you could use a fast, cheaper model to generate an initial idea, and then a more powerful model to elaborate on it. You can also create multi-modal scenarios, like using one model to generate a text prompt for an image generation model.
In this example, the flow first generates a story idea and then uses that idea to write the beginning of the story.
This first example is a complete program. Every later snippet shows only its
types and its flow: the flow is defined inside the same main, reusing this g
and ctx, and any package-level helper it declares sits beside main in the
same file. The package clause and the import block are left out.
package main
import ( "context" "errors" "fmt" "log"
"github.com/firebase/genkit/go/ai" "github.com/firebase/genkit/go/genkit" "github.com/firebase/genkit/go/plugins/googlegenai")
type StoryWriterRequest struct { Topic string `json:"topic"`}
type StoryIdea struct { Idea string `json:"idea" jsonschema_description:"A short, compelling story concept"`}
func main() { ctx := context.Background()
g := genkit.Init(ctx, genkit.WithPlugins(&googlegenai.GoogleAI{}), genkit.WithDefaultModel("googleai/gemini-flash-latest"), )
storyWriterFlow := genkit.DefineFlow(g, "storyWriterFlow", func(ctx context.Context, req *StoryWriterRequest) (string, error) { // Step 1: Generate a creative story idea idea, _, err := genkit.GenerateData[StoryIdea](ctx, g, ai.WithPrompt("Generate a unique story idea about a %v.", req.Topic), ) if err != nil { return "", err } // GenerateData returns a nil value with no error when the response // carried nothing to parse, such as a tool request or an interrupt. if idea == nil { return "", errors.New("the model returned no story idea") }
// Step 2: Use the idea to write the beginning of the story storyResponse, err := genkit.Generate(ctx, g, ai.WithPrompt("Write the opening paragraph for a story based on this idea: %v", idea.Idea), ) if err != nil { return "", err } return storyResponse.Text(), nil }, )
story, err := storyWriterFlow.Run(ctx, &StoryWriterRequest{Topic: "lighthouse keeper"}) if err != nil { log.Fatal(err) } fmt.Println(story)}This flow uses a text model to generate a detailed prompt for an image generation model, creating a piece of art based on a simple concept.
genai.GenerateContentConfig is the Google GenAI SDK’s own config type, so this
one needs import "google.golang.org/genai" on top of the imports above.
type ImageGeneratorRequest struct { Concept string `json:"concept"`}
imageGeneratorFlow := genkit.DefineFlow(g, "imageGeneratorFlow", func(ctx context.Context, req *ImageGeneratorRequest) (string, error) { // Step 1: Use a text model to generate a rich image prompt promptResponse, err := genkit.Generate(ctx, g, ai.WithModelName("googleai/gemini-flash-latest"), ai.WithPrompt("Create a detailed, artistic prompt for an image generation model. The concept is: \"%v\".", req.Concept), ) if err != nil { return "", err } imagePrompt := promptResponse.Text()
// Step 2: Use the generated prompt to create an image imageResponse, err := genkit.Generate(ctx, g, ai.WithModelName("googleai/gemini-3.1-flash-image"), ai.WithPrompt(imagePrompt), // Without IMAGE in ResponseModalities the model describes what it // would draw instead of drawing it. ai.WithConfig(&genai.GenerateContentConfig{ ResponseModalities: []string{"IMAGE", "TEXT"}, }), ) if err != nil { return "", err } for _, m := range imageResponse.Message.Content { if m.IsMedia() { return m.Text, nil } } return "", errors.New("did not generate an image") },)Workflow: Conditional routing
Section titled “Workflow: Conditional routing”This pattern adds branching logic to a workflow. An initial LLM call classifies the input, and the flow then routes the task to a specialized downstream path.
This is a great place to optimize for cost and latency. The initial classification step can often be handled by a smaller, faster model (like gemini-flash-latest or even gemini-flash-lite-latest), while the more complex downstream tasks can be routed to more powerful models.
This flow determines if a user’s request is a simple question or a request for creative writing and handles it accordingly.
type RouterRequest struct { Query string `json:"query"`}
type Intent struct { Intent string `json:"intent" jsonschema_enum:"question,creative"`}
routerFlow := genkit.DefineFlow(g, "routerFlow", func(ctx context.Context, req *RouterRequest) (string, error) { // Step 1: Classify the user's intent intent, _, err := genkit.GenerateData[Intent](ctx, g, ai.WithPrompt("Classify the user's query as either a 'question' or a 'creative' request. Query: %v", req.Query), ) if err != nil { return "", err } if intent == nil { return "", errors.New("the model returned no intent") }
// Step 2: Route based on the intent switch intent.Intent { case "question": // Handle as a straightforward question answerResponse, err := genkit.Generate(ctx, g, ai.WithPrompt("Answer the following question: %v", req.Query), ) if err != nil { return "", err } return answerResponse.Text(), nil case "creative": // Handle as a creative writing prompt creativeResponse, err := genkit.Generate(ctx, g, ai.WithPrompt("Write a short poem about: %v", req.Query), ) if err != nil { return "", err } return creativeResponse.Text(), nil default: return "Sorry, I couldn't determine how to handle your request.", nil } },)Workflow: Parallel execution
Section titled “Workflow: Parallel execution”This pattern executes multiple LLM calls simultaneously, either to perform independent sub-tasks faster (Sectioning) or to generate multiple diverse outputs for comparison (Voting). A flow is a good place to fan the calls out and join their results.
This example uses sectioning to generate a product name and a marketing tagline at the same time.
Run the branches in goroutines and join them with
golang.org/x/sync/errgroup,
which propagates the first error and cancels the rest:
import "golang.org/x/sync/errgroup"
type MarketingCopyRequest struct { Product string `json:"product"`}
type MarketingCopyResponse struct { Name string `json:"name"` Tagline string `json:"tagline"`}
marketingCopyFlow := genkit.DefineFlow(g, "marketingCopyFlow", func(ctx context.Context, req *MarketingCopyRequest) (*MarketingCopyResponse, error) { prompts := []string{ fmt.Sprintf("Generate a creative name for a new product: %v.", req.Product), fmt.Sprintf("Generate a catchy tagline for a new product: %v.", req.Product), } results := make([]string, len(prompts))
group, gctx := errgroup.WithContext(ctx) // Cap the fan-out so a wide batch does not walk into the provider's // rate limit. Drop the line to run every branch at once. group.SetLimit(4)
for i, prompt := range prompts { group.Go(func() error { resp, err := genkit.Generate(gctx, g, ai.WithPrompt(prompt)) if err != nil { return err } // Each branch owns one slot, so no lock is needed. results[i] = resp.Text() return nil }) }
// Wait returns the first error, and cancelling gctx has already // stopped the siblings. if err := group.Wait(); err != nil { return nil, err }
return &MarketingCopyResponse{Name: results[0], Tagline: results[1]}, nil },)A *genkit.Genkit is safe for concurrent genkit.Generate calls, so the
branches can share the one instance. Because gctx derives from the flow’s
context, it still carries the flow’s span, and each concurrent generation nests
under the flow in the trace tree rather than appearing as an orphan.
Hybrid: Tool calling
Section titled “Hybrid: Tool calling”This is where workflows start becoming more agentic. Instead of following a fixed path, the LLM can dynamically decide to call external functions (tools) to retrieve information or perform actions. This allows the workflow to interact with the outside world.
This flow provides an LLM with a getWeather tool. The LLM can then decide whether to call this tool based on the user’s prompt.
type ToolCallingRequest struct { Prompt string `json:"prompt"`}
type GetWeatherRequest struct { Location string `json:"location"`}
// Define a tool that can be called by the LLM.getWeather := genkit.DefineTool(g, "getWeather", "Get the current weather in a given location.", func(ctx *ai.ToolContext, req *GetWeatherRequest) (string, error) { // In a real app, you would call a weather API here. return fmt.Sprintf("The weather in %s is 75°F and sunny.", req.Location), nil },)
toolCallingFlow := genkit.DefineFlow(g, "toolCallingFlow", func(ctx context.Context, req *ToolCallingRequest) (string, error) { response, err := genkit.Generate(ctx, g, ai.WithPrompt(req.Prompt), ai.WithTools(getWeather), ) if err != nil { return "", err } return response.Text(), nil },)A more advanced form of tool use is Agentic RAG (Retrieval-Augmented Generation). Here, the agent uses a retrieval tool to fetch relevant documents from a vector store and uses them to answer a question.
localvec.Retriever(g, "menuQA") only looks up a retriever that
localvec.DefineRetriever(g, "menuQA", cfg, opts) already registered, and it
returns nothing until the menu documents are loaded with
localvec.Index(ctx, docs, ds). Do both during startup, before the flow runs.
See Local vector store and
RAG for that half.
import ( "strings"
"github.com/firebase/genkit/go/plugins/localvec")
type AgenticRagRequest struct { Question string `json:"question"`}
type MenuRagToolRequest struct { Query string `json:"query"`}
// 1. Define a retrieval toolretriever := localvec.Retriever(g, "menuQA")
menuRagTool := genkit.DefineTool(g, "menuRagTool", "Use to retrieve information from the Genkit Grub Pub menu.", func(ctx *ai.ToolContext, req *MenuRagToolRequest) (string, error) { response, err := genkit.Retrieve(ctx.Context, g, ai.WithRetriever(retriever), ai.WithDocs(ai.DocumentFromText(req.Query, nil)), ai.WithConfig(&localvec.RetrieverOptions{K: 3}), ) if err != nil { return "", err } var b strings.Builder for _, doc := range response.Documents { for _, part := range doc.Content { b.WriteString(part.Text) b.WriteString("\n") } } return b.String(), nil },)
// 2. Use the tool in a flowagenticRagFlow := genkit.DefineFlow(g, "agenticRagFlow", func(ctx context.Context, req *AgenticRagRequest) (string, error) { llmResponse, err := genkit.Generate(ctx, g, ai.WithPrompt(req.Question), ai.WithTools(menuRagTool), ai.WithSystem(`You are a helpful AI assistant that can answer questions about the food available on the menu at Genkit Grub Pub.Use the provided tool to answer questions.If you don't know, do not make up an answer.Do not add or change items on the menu.`), ) if err != nil { return "", err } return llmResponse.Text(), nil },)Hybrid: Iterative refinement
Section titled “Hybrid: Iterative refinement”This pattern creates a feedback loop to improve output quality. An “optimizer” LLM generates content, and an “evaluator” LLM provides critiques. The process repeats until the output meets a desired standard, moving further toward agent-like behavior.
This flow writes a short blog post, then repeatedly evaluates and refines it until the evaluator is satisfied.
type IterativeRefinementRequest struct { Topic string `json:"topic"`}
type Evaluation struct { Critique string `json:"critique"` Satisfied bool `json:"satisfied"`}
iterativeRefinementFlow := genkit.DefineFlow(g, "iterativeRefinementFlow", func(ctx context.Context, req *IterativeRefinementRequest) (string, error) { // Step 1: Generate the initial draft. resp, err := genkit.Generate(ctx, g, ai.WithPrompt("Write a short, single-paragraph blog post about: %v.", req.Topic), ) if err != nil { return "", err } content := resp.Text()
// Step 2: Iteratively refine the content. for i := 0; i < 3; i++ { // The "Evaluator" provides feedback. eval, _, err := genkit.GenerateData[Evaluation](ctx, g, ai.WithPrompt("Critique the following blog post. Is it clear, concise, and engaging? Provide specific feedback for improvement. Post: \"%v\"", content), ) if err != nil { return "", err } if eval == nil || eval.Satisfied { break }
// The "Optimizer" refines the content based on feedback. resp, err := genkit.Generate(ctx, g, ai.WithPrompt("Revise the following blog post based on the feedback provided.\nPost: \"%v\"\nFeedback: \"%v\"", content, eval.Critique), ) if err != nil { return "", err } content = resp.Text() } return content, nil },)Agent: Autonomous operation
Section titled “Agent: Autonomous operation”At the far end of the scale, an autonomous agent can independently plan and execute a series of steps to achieve a goal, using a set of tools. Genkit’s tool-calling mechanism, combined with interrupts for human-in-the-loop scenarios, provides a robust foundation for building these systems.
This example shows a simple research agent that can search the web and ask for clarification. It will continue to execute until it believes the task is complete or it reaches its turn limit.
type ResearchAgentRequest struct { Task string `json:"task"`}
type SearchWebRequest struct { Query string `json:"query"`}
type AskUserRequest struct { Question string `json:"question"`}
// UserAnswer is what askUser is resumed with if it runs again.type UserAnswer struct { Text string `json:"text"`}
// A tool for the agent to search the web.searchWeb := genkit.DefineTool(g, "searchWeb", "Search the web for information on a given topic.", func(ctx *ai.ToolContext, req *SearchWebRequest) (string, error) { // In a real app, you would implement a web search API call here. return fmt.Sprintf("You found search results for: %s", req.Query), nil },)
// A tool for the agent to ask the user a question. It pauses on the first// call, and the flow answers it with the user's reply.askUser := genkit.DefineResumableTool(g, "askUser", "Ask the user a clarifying question.", func(ctx context.Context, req *AskUserRequest, answer *UserAnswer) (string, error) { if answer == nil { return "", tool.Interrupt(ctx, nil) } return answer.Text, nil },)
const maxRounds = 5
researchAgent := genkit.DefineFlow(g, "researchAgent", func(ctx context.Context, req *ResearchAgentRequest) (string, error) { response, err := genkit.Generate(ctx, g, ai.WithSystem("You are a helpful research assistant. Your goal is to provide a comprehensive answer to the user's task."), ai.WithPrompt("Your task is: %v. Use the available tools to accomplish this.", req.Task), ai.WithModelName("googleai/gemini-pro-latest"), ai.WithTools(searchWeb, askUser), ai.WithMaxTurns(5), // Limit the number of back-and-forth turns ) if err != nil { return "", err }
for round := 0; round < maxRounds && response.FinishReason == ai.FinishReasonInterrupted; round++ { var answers []*ai.Part for _, part := range response.Interrupts() { // Every interrupt in the turn has to be answered, so an // unrecognized one is an error rather than a skip. call, ok := askUser.Interrupted(part) if !ok { return "", fmt.Errorf("no handler for interrupt from tool %q", part.ToolRequest.Name) }
// In a real app, you would put the question to the user and // wait for their answer. call.Input is the model's request. userAnswer := fmt.Sprintf("The user answered: \"Sample answer for '%s'\"", call.Input.Question) // Respond answers the call outright: the tool does not run again. answers = append(answers, call.Respond(userAnswer)) }
response, err = genkit.Generate(ctx, g, ai.WithMessages(response.History()...), // The model and the turn limit are request options, not // messages, so repeat them on every resume. ai.WithModelName("googleai/gemini-pro-latest"), ai.WithMaxTurns(5), ai.WithTools(searchWeb, askUser), ai.WithResume(answers...), ) if err != nil { return "", err } }
return response.Text(), nil },)askUser is a resumable tool, and tool is the
github.com/firebase/genkit/go/ai/tool package. askUser.Interrupted() claims
each paused call and decodes its input, and call.Respond() answers it with the
user’s reply. response.History() is the request’s messages plus the response, and
ai.WithSystem adds a real system message, so the system prompt rides along and
does not need repeating. The model name and the turn limit do not: leave them
off a resume and the call falls back to the registry’s default model and the
default limit of five turns. ai.WithMaxTurns bounds one genkit.Generate
call, not the resume loop, which is why the loop carries its own round cap.
See interrupts for the rest of the resume surface.
Genkit also ships a managed agent primitive that owns this loop for you, along with session persistence and streaming. The basic-agents sample defines seven agents in seven styles behind one CLI; those APIs are in preview, so it initializes Genkit with genkit.WithExperimental().
Bonus: Stateful interactions
Section titled “Bonus: Stateful interactions”Any of the patterns above can be turned into a stateful, conversational interaction by managing conversation history. This allows the agent or workflow to remember previous turns in the conversation and maintain context.
The key is to:
- Load the history for the current session.
- Append the new user message to the history.
- Call the model with the full message history. This is where you can plug in any of the other patterns (like tool calling or routing) to make your conversational agent more powerful.
- Save the updated history (including the model’s response) for the next turn.
This example shows a simple chat flow that maintains state.
This snippet needs slices and sync on top of the imports above.
type StatefulChatRequest struct { SessionID string `json:"sessionId"` Message string `json:"message"`}
// A simple in-memory store for conversation history. A flow served over HTTP// is called concurrently, so the map needs a lock.// In a real app, you would use a database like Firestore or Redis.var ( historyMu sync.RWMutex historyStore = make(map[string][]*ai.Message))
func loadHistory(sessionID string) []*ai.Message { historyMu.RLock() defer historyMu.RUnlock() // Clone, so the caller's append cannot reach into the stored slice. return slices.Clone(historyStore[sessionID])}
func saveHistory(sessionID string, history []*ai.Message) { historyMu.Lock() defer historyMu.Unlock() historyStore[sessionID] = history}
statefulChatFlow := genkit.DefineFlow(g, "statefulChatFlow", func(ctx context.Context, req *StatefulChatRequest) (string, error) { // 1. Load history. history := loadHistory(req.SessionID)
// 2. Append new message. history = append(history, ai.NewUserMessage(ai.NewTextPart(req.Message)))
// 3. Generate response with history. response, err := genkit.Generate(ctx, g, ai.WithMessages(history...), ) if err != nil { return "", err }
// 4. Save updated history. saveHistory(req.SessionID, response.History())
return response.Text(), nil },)Hand-rolling the store is the lowest-level of three options. Chat carries the history for a single caller without a store at all, and Sessions and state persists it behind an agent’s session store, which is what you want once the conversation has to survive a restart.
Moving the wording of a multi-turn prompt out of code is a separate step: the basic-prompts sample defines the same chat prompt inline and as a .prompt file, with {{history}} marking where the conversation lands.