AWSでDottxt Outlinesを使用してLLMから構造化出力を生成する
AWS MarketplaceのAmazon SageMakerでDottxtのOutlinesフレームワークを実装し、LLMからの構造化出力を実現する実践的アプローチを解説。
キーポイント
構造化出力は金融・医療・ECなど高精度が求められる分野でのAI実用化に不可欠
Dottxt OutlinesはJSON Schema・正規表現・文法など多様な制約をLLM出力に適用可能
AWS MarketplaceとSageMaker連携による実装アプローチを提案
構造化出力によりAI生成の信頼性向上と運用リスク低減を実現
影響分析・編集コメントを表示
影響分析
この記事は、大規模言語モデル(LLM)の実用化における最大の課題の一つである「出力の構造化」に焦点を当て、AWS環境での実装方法を具体的に示している。金融・医療・ECなど厳格なデータ形式が要求される分野でのAI導入を加速させ、生成AIを単なるテキスト生成ツールから信頼性の高い業務インフラへ進化させる可能性を示唆している。
編集コメント
AWS公式ブログとDottxt CEOの共著という信頼性の高い情報源が、LLM実用化の核心課題に具体的な解決策を提示。生成AIの「使える技術」への進化を後押しする重要な内容。
AWS のDottxt Outlines を用いた LLM からの構造化出力の生成
本記事は、Dottxt の CEO かつ技術創業者である Remi Louf と共著です。
AI アプリケーションにおける構造化出力とは、事前に定義され、検証され、しばしば厳格に指定された形式に従う AI 生成応答を指します。これには、出力のスキーマや、出力内の特定のフィールドがどのようにマッピングされるべきかという方法が含まれます。構造化出力は、一貫性、検証、および下流システムとのシームレスな統合を必要とするアプリケーションにとって不可欠です。例えば、銀行の融資承認システムでは厳格なフィールド検証を伴う JSON 出力を生成する必要があり、医療システムでは患者データの形式を検証し、薬剤投与量の制約を強制する必要があります。また、EC システムでは会計システム向けに標準化された請求書の生成が必要です。
本記事では、Amazon SageMaker の AWS Marketplace を用いて構造化出力を実装するための実用的なアプローチとして、.txt の Outlines フレームワークの実装について探ります。
構造化出力:ユースケースとビジネス価値
構造化出力は、生成 AI をその場限りのテキスト生成から信頼性の高いビジネスインフラへと昇華させ、高リスクかつ統合が複雑な環境において、精密なデータ交換、自動化された意思決定、エンドツーエンドのワークフローを可能にします。スキーマと予測可能なフォーマットを強制することで、正確性、追跡可能性、相互運用性が妥協できないユースケース——財務報告や医療業務から e コマース物流、企業ワークフロー自動化まで——での活用が実現します。本節では、構造化出力がいかにして最大の価値を生み出し、エラーの削減、運用リスクの低下、測定可能な ROI(投資対効果)に直接結びつくのかを探ります。
構造化出力とは何か?
「構造化出力」というカテゴリは、モデルが特定の制約メカニズムに従って出力を生成する方法に関する複数の要件を組み合わせたものです。以下に制約メカニズムの例を示します。
スキーマベースの制約:JSON Schema や XML Schema は、型要件、必須フィールド、プロパティ制約、ネストされた階層構造を持つオブジェクト構造を定義します。モデルはこれらの仕様に正確に一致する出力を生成し、transaction_id などのフィールドが正しく扱われることを保証するのに役立ちます。
列挙(Enumeration)ベースの制約:Enum 式は、出力を事前に定義されたカテゴリ値に制限します。分類タスクでは Enum を使用
パターンベースの制約:正規表現は、電子メールアドレス、電話番号、日付、またはカスタム識別子などの特定の形式を検証します。正規表現パターンにより、後処理での検証を行わずに、出力が必要な構造と一致することが保証されます。
文法ベースの制約:文脈自由文法(CFG)および EBNF 記法は、コード、SQL クエリ、設定ファイル、またはドメイン固有言語を生成するための構文ルールを定義します。制約付きデコーディングフレームワークが、トークン生成時にこれらのルールを強制します。
意味論的検証:構文ベースの制約を超えて、大規模言語モデル(LLM)は、出力を自然言語基準に対して検証できます。これにより、コンテンツが専門的、ファミリーフレンドリー、または建設的なものであることを保証し、ルールベースの検証では捉えきれない主観的な要件に対応します。
構造化出力から恩恵を受ける重要なコンポーネント
現代のアプリケーションでは、AI モデルは非 AI 型の処理やビジネスシステムと統合されています。これらの統合および接続点には、一貫性、型安全性、機械可読性が不可欠です。なぜなら、解析の不確実性やフォーマットからの逸脱がワークフローを破綻させる可能性があるからです。以下に、LLM とインフラストラクチャコンポーネントの間で重要な相互運用性を確認できる一般的なアーキテクチャパターンをいくつか挙げます。
API 統合とデータパイプライン:抽出、変換、ロード(ETL)プロセスおよび REST API は厳格なフォーマット準拠を必要とします。モデルの出力における誤りは構文解析エラーを引き起こし、データベースへの直接挿入やシームレスな変換ロジックを損なう可能性があります。
ツール呼び出しと関数実行:エージェント型ワークフローは、LLM モデルが正しく型付けされたパラメータで関数を呼び出す能力に依存しており、これにより各エージェントが検証済みの入力を受け取る多段階自動化が可能になります。
文書抽出およびデータキャプチャ:請求書、契約書、または医療記録の構文解析には、モデルが所望のエントリを意味的に特定し、ベンダー名、金額、日付などを抽出して事前定義されたスキーマ(特定の分類オプションなどを含む)に収めることで、真にデータ入力自動化を実現する形式で返す必要があります。
リアルタイム意思決定システム:不正検出や取引処理のように、50 ミリ秒未満の意思決定を必要とするシステムでは、出力構造における冗長性や再試行は許容されません。信頼性の高いリスクスコア、分類フラグ、および意思決定メタデータを生成することで、下流システムがデータを即座に消費できるようになります。
ビジネスアプリケーション:構造化出力が最も価値を発揮する領域
高リスクで統合依存度の高いドメイン全体において、構造化出力は生成モデルを柔軟なテキストエンジンから、予測可能性、監査可能性、およびエンドツーエンドの自動化を提供する信頼性の高いビジネスインフラへと変換します。
金融サービスおよび取引処理:金融機関において、構造化された出力は、報告、監査、規制遵守における精度と一貫性を促進します。取引データ、リスク評価、ポートフォリオ分析は、リアルタイムの照合、マネーロンダリング防止(AML)レビュー、および規制提出書類をサポートするために、事前に定義されたスキーマに準拠する必要があります。構造化された出力により、決済システム、リスクエンジン、監査ツール間のシームレスな交換が可能となり、人的監視を削減しながらも、高リスクの金融業務全体で完全な追跡可能性とデータ整合性を維持します。
医療および臨床業務:規制遵守には厳格な検証が求められます。バイタルサイン、投薬量、検査結果に対する範囲チェックは、重大なエラーを防ぐために役立ちます。医療文書からの構造化抽出により、自動コーディング、請求の正確性、HIPAA 遵守のための監査証跡作成が可能になります。
エンタープライズワークフロー自動化:レガシーシステムでは、カスタム解析ロジックを必要としない機械可読データが必要です。顧客サポートとのやり取りからの構造化された出力は、感情スコア、アクションアイテム、ルーティングメタデータを備えたケースサマリーを生成し、これらは顧客関係管理(CRM)システムに直接統合されます。
Ecommerce and logistics: Address validation, payment verification, and order attribute consistency reduce failed deliveries and fraudulent transactions. Structured outputs coordinate multi-party workflows where carriers, warehouses, and payment processors require standardized formats.
Regulatory compliance and audit readiness: Industries facing strict oversight benefit from structured content management with immutable audit trails. Component-level repositories track every change with metadata (who, when, why, approver), so that auditors can verify compliance through direct system access rather than manual document review.
The common thread is operational complexity, integration requirements, and risk sensitivity. Structured outputs transform AI from text generation into reliable business infrastructure where predictability, auditability, and system interoperability drive measurable ROI through reduced errors, faster processing, and seamless automation.
Introducing .txt Outlines on AWS to produce structured outputs
Structured output can be achieved in several ways. Most frameworks will, at the core, focus on validation to identify if the output adheres to the rules and requirements requested. If the output doesn't conform, the framework will request a new output, and keep iterating as such until the model achieves the requested output structure.
Outlines は、生成時の検証と呼ばれる高度なアプローチを提供します。これは、モデルがトークンを生成している最中に検証が行われることを意味し、完了後の検証ではなく、生成プロセスの初期段階で検証を行うようにシフトするものです。Amazon Bedrock とは統合されていませんが、Outlines を理解することは、ハイブリッド実装戦略に示唆を与える最先端の構造化出力技術への洞察をもたらします。
.txt チームによって開発された Outlines は、言語モデルの出力に決定論的な構造と信頼性をもたらすために設計された Python ライブラリであり、LLM を本番環境アプリケーションで展開する際の主要な課題に対処しています。従来の自由形式の生成とは異なり、Outlines を使用することで、事後ではなく生成中に厳格な出力フォーマットと制約を強制することが可能です。このアプローチにより、精度、予測可能性、および下流システムとの統合が求められるタスクに LLM を活用することが可能になります。
Outlines の仕組み
Outlines は、主に以下の 3 つのメカニズムを通じて制約を強制します:
文法コンパイル:スキーマをトークンマスクに変換し、モデルの選択をガイドする
接頭辞木(プレフィックスツリー):ビームサーチ中に無効なパスを剪定して有効な構造を維持する
サンプリング制御:生成中に有効なトークン選択のために有限オートマトンを使用する
生成中、Outlines は以下の正確なワークフローに従います:
言語モデルが入力シーケンスを処理し、トークンのロジット(logits)を生成する
Outlines のロジットプロセッサが、無効なトークンの確率を 0% に設定する
トークンは、定義された構造に従って許可されたトークンのセットからのみサンプリングされます
このプロセスは生成が完了するまで繰り返され、出力が必要な形式に準拠していることを保証するのに役立ちます
例えば、^\d*(\.\d+)?$ というパターンの場合
パフォーマンス上の利点
生成中に構造化出力を強制することは、本番環境における信頼性とパフォーマンスに対して顕著な利点をもたらします。これにより、出力構造の有効性が高まり、パフォーマンスが大幅に向上します:
推論オーバーヘッドゼロ:構造化生成技術は、推論時に実質的な計算コストを追加しません
5 倍高速な生成:.txt Engineering の結合アプローチによると、構造化生成は標準的な生成よりも劇的に高速です
計算リソースの削減:制約によりモデルの意思決定が簡素化され、無効なパスが排除されるため、全体の処理要件が減少します
精度の向上:出力空間を絞り込むことで、ベースモデルでも構造化タスクにおいてより高い精度を達成できます
ベンチマーク上の利点
Outlines ライブラリの証明された利点の一部は以下の通りです:
正規表現ベースの検証パイプラインよりも 2 倍高速
生成後の検証と比較して 98% のスキーマ準拠(76%)
再帰的な JSON スキーマなどの複雑な制約をサポート
Outlines の始め方
Outlines は、既存の Python ワークフローにシームレスに統合できます:
from pydantic import BaseModel # Define your data structure class Patient(BaseModel): id: int name: str diagnosis: str age: int # Load model and create structured generator model = models.transformers("microsoft/DialoGPT-medium") generator = generate.json(model, Patient) # Generate structured output prompt = "Create a patient record for John Smith, 45, with diabetes" result = generator(prompt) # Returns valid Patient instance print(result.name) # "John Smith" print(result.age) # 45
For more complex schemas:
from enum import Enum class Status(str, Enum): ACTIVE = "active" INACTIVE = "inactive" PENDING = "pending" class User(BaseModel): username: str email: str status: Status created_at: datetime # Generator enforces enum values and datetime format user_generator = generate.json(model, User)
Using .txt's dotjson in Amazon SageMaker
You can directly deploy .txt's Amazon SageMaker real-time inference solution for generating structured output by deploying one of .txt's models such as DeepSeek-R1-Distill-Qwen-32B through AWS Marketplace. The following code assumes that you have already deployed an endpoint in your AWS account.
A Jupyter Notebook that walks through deploying the endpoint end-to-end is available in the product repository.
import json import boto3 # Set this based on your SageMaker endpoint endpoint_name = "dotjson-with-DeepSeek-R1-Distill-Qwen-32B" session = boto3.Session()
必ず JSON 形式で返してください。translation フィールドのみ。他のフィールド (technical_terms 等) は一切追加しないこと — 余計なフィールドを書こうとして本文翻訳がトークン上限で打ち切られる事故を防ぐため:
{"translation": "翻訳全文"}
原文を表示
Generate structured output from LLMs with Dottxt Outlines in AWS
This post is cowritten with Remi Louf, CEO and technical founder of Dottxt.
Structured output in AI applications refers to AI-generated responses conforming to formats that are predefined, validated, and often strictly entered. This can include the schema for the output, or ways specific fields in the output should be mapped. Structured outputs are essential for applications that require consistency, validation, and seamless integration with downstream systems. For example, banking loan approval systems must generate JSON outputs with strict field validation, healthcare systems need to validate patient data formats and enforce medication dosage constraints, and ecommerce systems require standardized invoice generation for their accounting systems.
This post explores the implementation of .txt’s Outlines framework as a practical approach to implementing structured outputs using AWS Marketplace in Amazon SageMaker.
Structured output: Use cases and business value
Structured outputs elevate generative AI from ad hoc text generation to dependable business infrastructure, enabling precise data exchange, automated decisioning, and end-to-end workflows across high‑stakes, integration-heavy environments. By enforcing schemas and predictable formats, they unlock use-cases where accuracy, traceability, and interoperability are non-negotiable, from financial reporting and healthcare operations to ecommerce logistics and enterprise workflow automation. This section explores where structured outputs create the most value and how they translate directly into reduced errors, lower operational risk, and measurable ROI.
What is structured output?
The category structured output combines multiple types of requirements for how models should produce outputs that follow specific constraints mechanisms. The following are examples of constraint mechanisms.
Schema-based constraints: JSON Schema and XML Schema define object structures with type requirements, required fields, property constraints, and nested hierarchies. Models generate outputs matching these specifications exactly, helping to ensure that fields like transaction_id
Enumeration constraints: Enum expressions restrict outputs to predefined categorical values. Classification tasks use enum
Pattern-based constraints: Regular expressions validate specific formats such as email addresses, phone numbers, dates, or custom identifiers. Regex patterns make sure outputs match required structures without post-processing validation.
Grammar-based constraints: Context-free grammars (CFGs) and EBNF notation define syntactic rules for generating code, SQL queries, configuration files, or domain-specific languages. Constrained decoding frameworks enforce these rules at token generation time.
Semantic validation: Beyond syntactic constraints, large language models (LLMs) can validate outputs against natural language criteria—helping to ensure that content is professional, family-friendly, or constructive—addressing subjective requirements that rule-based validation can’t capture.
Critical components that benefit from structured output
In modern applications, AI models are integrated with non-AI types of processing and business systems. These integrations and junction points require consistency, type safety, and machine readability, because parsing ambiguities or format deviations would break workflows. Here are some of the common architectural patterns where we see critical interoperability between LLMs and infrastructure components:
API integration and data pipelines: Extract, transform, and load (ETL) processes and REST APIs require strict format compliance. Mistakes in the output of the model can create parsing errors and compromise direct database insertion or seamless transformation logic.
Tool calling and function execution: Agentic workflows depend on the ability of the LLM model to invoke functions with correctly typed parameters, enabling multi-step automation where each agent consumes validated inputs.
Document extraction and data capture: Parsing invoices, contracts, or medical records requires the model to semantically identify the desired entities and return them in a format that can truly automate data entry by extracting vendor names, amounts, and dates into predefined schemas, including specific categorization options among others.
Real-time decision systems: Systems that require sub-50 millisecond decisions, such as fraud detection and transaction processing, can’t afford verbosity or retries on the structure of the output. Producing reliable and conformed risk scores, classification flags, and decision metadata mean that downstream systems can consume data instantly.
Business applications: Where structured output provides the most value
Across high-stakes, integration-heavy domains, structured outputs transform generative models from flexible text engines into reliable business infrastructure that delivers predictability, auditability, and end‑to‑end automation.
Financial services and transaction processing: In financial institutions, structured outputs facilitate precision and consistency across reporting, auditing, and regulatory compliance. Transaction data, risk assessments, and portfolio analytics must adhere to predefined schemas to support real-time reconciliation, anti-money laundering (AML) reviews, and regulatory filings. Structured outputs enable seamless exchange among payment systems, risk engines, and audit tools—reducing manual oversight while maintaining full traceability and data integrity across high-stakes financial operations.
Healthcare and clinical operations: Regulatory compliance demands strict validation—range checking for vital signs, medication dosages, and lab results helps prevent critical errors. Structured extraction from medical documents enables automated coding, billing accuracy, and audit trail creation for HIPAA compliance.
Enterprise workflow automation: Legacy systems require machine-readable data without custom parsing logic. Structured outputs from customer support interactions generate case summaries with sentiment scores, action items, and routing metadata that integrate directly into customer relationship management (CRM) systems.
Ecommerce and logistics: Address validation, payment verification, and order attribute consistency reduce failed deliveries and fraudulent transactions. Structured outputs coordinate multi-party workflows where carriers, warehouses, and payment processors require standardized formats.
Regulatory compliance and audit readiness: Industries facing strict oversight benefit from structured content management with immutable audit trails. Component-level repositories track every change with metadata (who, when, why, approver), so that auditors can verify compliance through direct system access rather than manual document review.
The common thread is operational complexity, integration requirements, and risk sensitivity. Structured outputs transform AI from text generation into reliable business infrastructure where predictability, auditability, and system interoperability drive measurable ROI through reduced errors, faster processing, and seamless automation.
Introducing .txt Outlines on AWS to produce structured outputs
Structured output can be achieved in several ways. Most frameworks will, at the core, focus on validation to identify if the output adheres to the rules and requirements requested. If the output doesn’t conform, the framework will request a new output, and keep iterating as such until the model achieves the requested output structure.
Outlines offers an advanced approach called generation-time validation, meaning that the validation happens as the model is producing tokens, which shifts validation to early in the generation process instead of validating after completion. While not integrated with Amazon Bedrock, understanding Outlines provides insight into cutting-edge structured output techniques that inform hybrid implementation strategies.
Outlines, developed by the .txt team, is a Python library designed to bring deterministic structure and reliability to language model outputs—addressing a key challenge in deploying LLMs for production applications. Unlike traditional free-form generation, developers can use Outlines to enforce strict output formats and constraints during generation, not just after the fact. This approach makes it possible to use LLMs for tasks where accuracy, predictability, and integration with downstream systems are required.
How Outlines works
Outlines enforces constraints through three main mechanisms:
Grammar compilation: Converts schemas into token masks that guide the model’s choices
Prefix trees: Prunes invalid paths during beam search to maintain valid structure
Sampling control: Uses finite automata for valid token selection during generation
During generation, Outlines follows a precise workflow:
The language model processes the input sequence and produces token logits
The Outlines logits processor sets the probability of illegal tokens to 0%
A token is sampled only from the set of legal tokens according to the defined structure
This process repeats until generation is complete, helping to ensure that the output conforms to the required format
For example, with a pattern like ^\d*(\.\d+)?$
Performance benefits
Enforcing structured output during generation offers significant advantages for reliability and performance in production environments. It helps to increase the validity of the output’s structure and can significantly improve performance:
Zero inference overhead: The structured generation technique adds virtually no computational cost during inference
5 times faster generation: According to .txt Engineering’s coalescence approach, structured generation can be dramatically faster than standard generation
Reduced computational resources: Constraints simplify model decision-making by removing invalid paths, reducing overall processing requirements
Improved accuracy: By narrowing the output space, even base models can achieve higher precision on structured tasks
Benchmark advantages
Here are some of the proven benefits of the Outlines library:
2 times faster than regex-based validation pipelines
98% schema adherence compared to 76% for post-generation validation
Supports complex constraints like recursive JSON schemas
Getting started with Outlines
Outlines can be seamlessly integrated into existing Python workflows:
from pydantic import BaseModel # Define your data structure class Patient(BaseModel): id: int name: str diagnosis: str age: int # Load model and create structured generator model = models.transformers("microsoft/DialoGPT-medium") generator = generate.json(model, Patient) # Generate structured output prompt = "Create a patient record for John Smith, 45, with diabetes" result = generator(prompt) # Returns valid Patient instance print(result.name) # "John Smith" print(result.age) # 45
For more complex schemas:
from enum import Enum class Status(str, Enum): ACTIVE = "active" INACTIVE = "inactive" PENDING = "pending" class User(BaseModel): username: str email: str status: Status created_at: datetime # Generator enforces enum values and datetime format user_generator = generate.json(model, User)
Using .txt’s dotjson in Amazon SageMaker
You can directly deploy .txt’s Amazon SageMaker real-time inference solution for generating structured output by deploying one of .txt’s models such as DeepSeek-R1-Distill-Qwen-32B through AWS Marketplace. The following code assumes that you have already deployed an endpoint in your AWS account.
A Jupyter Notebook that walks through deploying the endpoint end-to-end is available in the product repository.
import json import boto3 # Set this based on your SageMaker endpoint endpoint_name = "dotjson-with-DeepSeek-R1-Distill-Qwen-32B" session = boto3.Session()
関連記事
今日のまとめ
AI日報で今日の重要ニュースをまとめ読み