◢ build log

Choosing Prompt Templating for Multi-Turn AI Agent Conversations

Select the best prompt templating strategy for your multi-turn AI agent conversations to manage context, reduce errors, and ensure consistent behavior.

Building AI agents that handle multi-turn conversations requires careful prompt management. LLMs are stateless. Each turn, you must re-send relevant context, including the conversation history. Without a clear strategy, your prompts become brittle, hard to debug, and inconsistent.

Prompt templating brings structure. It helps you define how system instructions, user input, and conversation history combine into a single, coherent prompt for the LLM. This is crucial for maintaining context, enforcing agent behavior, and ensuring consistent output across many interactions.

The Challenge of Multi-Turn Conversations

Every time your AI agent interacts with a user, it's a new request to the LLM. The LLM does not remember previous turns. To simulate memory, you must reconstruct the conversation history and send it with each new user input.

This history often includes:

  • System instructions: Guiding the agent's persona, rules, and objectives.
  • Previous user messages: What the user said before.
  • Previous assistant responses: What your agent replied.
  • Tool outputs: Results from any functions or tools the agent used.
  • User's current message: The latest input.

As conversations grow, the prompt gets longer. Managing this manually with string concatenation is error-prone. It's difficult to see the structure. It's easy to miss a crucial piece of context or introduce formatting errors that confuse the LLM.

Simple String Formatting: When to Use It

For straightforward, low-complexity agents, basic string formatting can work. This includes f-strings in Python or template literals in JavaScript. You define a basic structure and inject variables directly.

Example (Python f-string):

def create_simple_prompt(system_message, conversation_history, user_input):
    history_str = "\n".join([f"{m['role']}: {m['content']}" for m in conversation_history])
    return f"""
{system_message}

{history_str}
User: {user_input}
Assistant:
"""

## Hypothetical usage
system_msg = "You are a helpful assistant."
history = [
    {"role": "User", "content": "What's the weather like?"},
    {"role": "Assistant", "content": "I need a location to tell you the weather."}
]
current_input = "It's sunny in London."

prompt = create_simple_prompt(system_msg, history, current_input)
print(prompt)

When to use it:

  • Your agent has a very simple, fixed prompt structure.
  • The number of dynamic parts is small.
  • You prioritize minimal dependencies.

Limitations:

  • Scales poorly with complexity. Adding new sections or conditional logic makes the code messy.
  • No separation of concerns between prompt logic and data.
  • No built-in validation or error checking for missing variables.

Dedicated Templating Libraries: Jinja2, Handlebars

For agents with moderate complexity, a dedicated templating library offers a more robust solution. Libraries like Jinja2 (Python) or Handlebars (JavaScript) allow you to define templates in separate files or strings. You then pass a context object (a dictionary or JSON) to render the final prompt.

These libraries provide features like:

  • Variables: Inject data into placeholders.
  • Control structures: if/else conditions, for loops.
  • Template inheritance: Reusing common prompt components.
  • Filters: Formatting data within the template.

Example (Python with Jinja2):

from jinja2 import Template

template_str = """
{{ system_message }}

{% for message in conversation_history %}
{{ message.role }}: {{ message.content }}
{% endfor %}
User: {{ user_input }}
Assistant:
"""

def create_templated_prompt(system_message, conversation_history, user_input):
    template = Template(template_str)
    return template.render(
        system_message=system_message,
        conversation_history=conversation_history,
        user_input=user_input
    )

## Hypothetical usage
system_msg = "You are a friendly chatbot that helps with bookings."
history = [
    {"role": "User", "content": "I want to book a flight."},
    {"role": "Assistant", "content": "Sure, where are you flying from and to?"}
]
current_input = "From London to New York."

prompt = create_templated_prompt(system_msg, history, current_input)
print(prompt)

When to use it:

  • Your prompts have conditional logic (e.g., enable a feature based on user role).
  • You need to loop through lists (like conversation history or tool outputs).
  • You want to separate prompt logic from your application code.
  • Your agent uses various tools or has different modes that require slight prompt variations.

Limitations:

  • Still primarily text-based; the LLM processes text, not structured data directly.
  • Validation is at the templating layer, not semantic validation for the LLM's understanding.

Structured Data (JSON) for Complex Prompts

For advanced AI agents, especially those involving tool use, function calling, or complex state management, sending structured data like JSON within your prompt is often superior. Many modern LLMs are explicitly trained to process JSON objects. This allows for machine-readable instructions and data.

Instead of just formatting text, you can embed JSON objects that define tools, parameters, or internal state. The LLM can then parse and act upon this structured data.

Example (Hypothetical prompt with JSON for tool use):

def create_json_prompt(system_message, conversation_history, available_tools, user_input):
    messages = [
        {"role": "system", "content": system_message}
    ]
    messages.extend(conversation_history)
    messages.append(
        {"role": "user", "content": user_input}
    )

    # A common pattern is to include tools as part of the system message or a separate instruction
    # For this example, let's assume `available_tools` is a list of tool definitions
    tool_instructions = f"""
    You have access to the following tools:
    {json.dumps(available_tools, indent=2)}

    When you need to use a tool, respond with a JSON object in the format:
    {{"tool_name": "<tool_name>", "tool_params": {{"..."}}}}
    """
    
    # Prepend tool instructions to the system message or add as a separate message
    messages[0]["content"] = f"{messages[0]["content"]}\n\n{tool_instructions}"

    # The final prompt sent to the LLM might be a string representation of these messages
    # or an API call that expects a list of message objects.
    # For demonstration, we'll stringify it.
    return json.dumps(messages, indent=2)

import json

## Hypothetical usage
system_msg = "You are an assistant that can book flights and hotels."
history = [
    {"role": "user", "content": "Find me a hotel in Paris."},
    {"role": "assistant", "content": "Sure, for what dates?"}
]
available_tools_example = [
    {
        "name": "book_hotel",
        "description": "Book a hotel room.",
        "parameters": {"location": "string", "check_in": "string", "check_out": "string"}
    },
    {
        "name": "search_flights",
        "description": "Search for flights.",
        "parameters": {"origin": "string", "destination": "string", "date": "string"}
    }
]
current_input = "Check me in on July 10th and out on July 15th."

prompt = create_json_prompt(system_msg, history, available_tools_example, current_input)
print(prompt)

When to use it:

  • Your agent needs to perform specific actions via tools or functions.
  • You require strict output formats from the LLM (e.g., always return a JSON object).
  • You are orchestrating complex multi-agent systems where agents exchange structured information. This is common in more advanced /ai-agent-developer scenarios.
  • You need to pass complex configuration or state to the LLM.

Benefits:

  • Reduced ambiguity: LLMs are less likely to misinterpret structured instructions.
  • Easier parsing: Your application can reliably parse the LLM's structured output.
  • Schema validation: You can validate the JSON against a schema, catching errors early.

Considerations:

  • Increased token count: JSON can be verbose, potentially using more tokens.
  • Requires careful design of JSON schemas and parsing logic.

Choosing Your Strategy

Start with the simplest approach that meets your needs. If basic f-strings suffice, use them. As your agent's complexity grows:

  1. Move to templating libraries when you need conditional logic, loops, or better separation of concerns for your text-based prompts.
  2. Adopt structured data (JSON) when your agent interacts with tools, requires specific machine-readable outputs, or manages complex internal state. This is often necessary for robust agentic systems.

Always prioritize clarity and maintainability. A well-templated prompt is easier to debug and evolve than a tangled mess of string concatenations.

Where to go from here

Review your agent's current prompt structure. Identify areas where templating could improve clarity or reduce errors. Consider what level of structure your agent truly needs for reliable operation. If you need help designing robust AI agent systems, explore /ai-consulting for expert guidance.

  • prompt templating
  • multi-turn conversations
  • ai agents
  • context management
  • prompt engineering
  • llm development
  • structured prompts
  • jinja2
05 — execute

Ready to build
the future?

Join the developers learning to build with AI. New tutorials, tools and breakdowns every week — straight to your feed.

$ aidevguy --start --now_