iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🏗️

Designing a Python-Driven LLM Application Architecture

に公開

Introduction

This article summarizes the architectural patterns used in a prototype designed around the philosophy: "Python maintains control, and the LLM provides the intelligence."

Prerequisites:
https://zenn.dev/akring/articles/874140ac7bdb8c

Contents of this article:

  • Division of roles between LLM and Python
  • Structuring processing through Phase separation
  • Responsibilities and boundaries of each Phase
  • Design of the data flow

Not included in this article:

  • Numerical comparisons/benchmarks (→ Please refer to the comparative analysis report)
  • The entire implementation code (conceptual and partial explanations only)

Note:
This is a summary based on experimental results from a small-scale prototype. Alternative approaches may be more suitable for production environments.

Provided Features

As a virtual application, we assume a pipeline that searches for AWS What's New information using natural language. While the implementation has been verified, this article focuses on the conceptual architecture.

Web app implemented for verification
Verification Web App - A Python-led LLM application runs in the background

Search examples:

✅ "EC2 in Tokyo last month"
   → Amazon EC2-related updates in ap-northeast-1 for December 2025

✅ "Summarize container-related updates in ASEAN around Christmas"
   → Summary of ECS/EKS-related updates in Southeast Asia from mid-to-late December 2025

Three Search Axes

User input is decomposed into three search axes to execute the search.

Axis Natural Language Expression Example Interpretation Content
Time "Last month", "Around Christmas", "Last 3 months" Relative expressions, event-based, specific dates
Service "EC2", "Machine Learning", "Container" Abbreviations, categories, multiple specifications
Region "Tokyo", "ASEAN", "Asia" City names, organizational names, regional names

Supported range:

  • Supports unordered, multiple, and partial specifications
  • Also supports relative expressions ("last month"), events ("around Christmas"), and organizational names ("ASEAN")

Phase-Separation Architecture

Let us organize the overall architecture here with a diagram.

The following shows the difference between an LLM-led (Agentic) design style and the Python-led (Pipeline) design style adopted in this article.


Overview of the Python-led Pipeline Architecture

We will explain the Python-led pipeline shown on the right side of this figure by decomposing it into Phases in the following sections.

Design Philosophy

Our approach is for Python to control the processing flow. The key points for organization are:

  1. Control flow is explicitly defined in Python
  2. Each Phase has a single responsibility
  3. Data flow between Phases consists of structured data
  4. The LLM's role is limited within each Phase

Four Phases and Responsibilities

Phase Responsibility Input Output Technology Selection
Phase 1 Structuring natural language Natural language query Structured intent LLM
Phase 2 Keyword resolution Standardized values Search criteria Python (Rules + Graph search) + LLM fallback
Phase 3 Database search Search criteria Search results Python SQL generation + Execution
Phase 4 Result formatting Search results User output Python template or LLM

Why the LLM was integrated into Python's control flow

In this prototype, we utilize the Structured Output function provided by Strands Agents. By using this feature, we can treat the return value of the LLM as explicitly defined structured data in every phase.

The structure is defined using Pydantic, and the LLM output is generated in a form that matches the schema.

# Define the return structure with Pydantic models
class IntentResult(BaseModel):
    time_expression: Optional[str]
    region_keywords: Optional[list[str]]
    service_keywords: Optional[list[str]]
    action: Literal["list", "count", "latest", "summarize", "analyze"]
    max_results: int

# Specify the schema when calling the LLM
agent = create_intent_understanding_agent()
invocation = agent(
    user_request,
    structured_output_model=IntentResult  # ← Enforce schema
)

# The return value can always be retrieved as an IntentResult type
intent: IntentResult = invocation.structured_output
print(intent.service_keywords)  # type-safe

https://strandsagents.com/latest/documentation/docs/user-guide/concepts/agents/structured-output/

With this mechanism, whether processed by Python or fallen back to an LLM, a state is achieved where the type of the return value is always consistent. As a result, we were able to safely embed the LLM into our Python code while keeping the control flow fixed on the Python side.

This is the primary reason we adopted structured output for every LLM call.

Phase 1: Intent Understanding

Convert natural language queries into structured data

Input: "EC2 in Tokyo last month"

↓ LLM Processing

Output: {
  time_expression: "last month",
  region_keywords: ["Tokyo"],
  service_keywords: ["EC2"],
  action: "list"
}

Points:

  • Supports out-of-order input
  • Absorbs variations in expressions (e.g., EC2, Elastic Compute Cloud)
  • Partial specification is acceptable
  • LLM used with temperature=0 to ensure reproducibility

Phase 2: Keyword Resolution

Phase 2a: Normalization of time expressions

Input: "last month" (+ current time)

↓ Rule-based processing

Output: {
  date_from: "2025-12-01",
  date_to: "2026-01-01"
}

Implementation:

  • Fast Path: High-speed processing via rule-based logic
  • Slow Path: Fallback to LLM for undefined expressions

Phase 2b: Keyword expansion and resolution

Input: {region_keywords: ["Tokyo"], service_keywords: ["EC2"]}

↓ Graph search + LLM fallback

Output: {
  region_codes: ["ap-northeast-1"],
  service_keywords: ["EC2", "Amazon EC2", "Elastic Compute Cloud", ...]
}
  • Frequent patterns processed quickly in Python
  • Complex expressions resolved by LLM
  • Relationships expanded via graph search

Phase 3: Search Execution

Search the database using structured search criteria

Input: {
  date_from: "2025-12-01",
  date_to: "2026-01-01",
  region_codes: ["ap-northeast-1"],
  service_keywords: ["EC2", ...]
}

↓ SQL Execution

Output: {
  items: [{id: "item-001", title: "...", url: "...", service: "EC2"}, ...]
}
  • SQL generation and execution performed in Python
  • Ensures reproducibility, speed, and ease of debugging

Phase 4: Result Formatting

Format search results for the user

  • Simple list/count/latest → High-speed output via Python templates
  • Complex summarization/analysis → Natural language generation via LLM
Input: {items: [...]}

↓ Python template expansion

Output:
## Search results: 5 items
- [EC2 GameLift Streams](...)
- [RDS Zero-ETL to EC2](...)
Input: {items: [11 update information items]}

↓ LLM summarization

Output:
## Summary
In the ASEAN region, enhancements were primarily made to Aurora and DynamoDB. ...

Overall Data Flow

Phase 1 → IntentResult →
Phase 2 → KeywordResolutionResult →
Phase 3 → SearchResult →
Phase 4 → FormattedOutput
  • Phases connected via structured data
  • Achieves type safety, ease of debugging, and loose coupling

Summary

Design Principles:

  1. Python controls the flow
  2. LLM focuses on providing intelligence
  3. Maximize deterministic processing

Benefits:

  • High speed
  • Reproducibility
  • Cost efficiency
  • Flexibility
  • Maintainability
  • Ease of debugging

Caution: These are results from a small-scale prototype; different approaches may be necessary for production operations.

Next Steps

https://zenn.dev/akring/articles/874140ac7bdb8c
https://zenn.dev/akring/articles/8b073fca0ba078

Discussion