Building a Multi-Model Enterprise AI Research Platform
Machine LearningModel answerLast updated
Design a production agent system for financial analysts, covering model customization strategies, agent orchestration patterns, structured output enforcement, and multi-tenant serving.
You're architecting an AI-powered research platform for quantitative analysts at an investment firm. The system will help analysts process unstructured market documents, extract financial data, and execute complex research tasks through natural language interaction.
Analysts will use the platform to analyze earnings transcripts, pull metrics from regulatory documents, query proprietary databases, run analytical computations, and chain together multi-step investigations. The output feeds both human decision-making and downstream quantitative pipelines that require precise, validated data.
Scale and Performance Targets
- User base: Approximately 1,000 analysts
- Daily volume: 50,000 agent sessions under normal conditions
- Seasonal peaks: 5× traffic during quarterly earnings periods
- Latency goals:
- Simple tool invocations: 95th percentile under 2.5 seconds
- Multi-step research tasks: 95th percentile under 12 seconds
- Infrastructure: Fixed GPU cluster (H100/A100 nodes)
Core Capabilities Required
Model Customization: Starting from open foundation models (such as 70B-parameter models), adapt them to understand firm-specific vocabulary, proprietary metric definitions, and specialized output formats.
Tool Integration: Enable the agent to orchestrate actions across internal systems—querying timeseries databases, searching document collections, invoking computation engines—while maintaining safe, bounded execution.
Structured Output: Produce validated JSON conforming to strict schemas for programmatic consumption by downstream systems.
Safety and Auditability: Ensure complete traceability of agent decisions, validate tool executions, detect hallucinated numbers, and guarantee reproducibility for compliance review.
Your Design Should Address
-
Model customization approach: Evaluate full fine-tuning, parameter-efficient methods (LoRA, QLoRA), and retrieval-augmented generation. Consider training cost, memory requirements, serving overhead, and risk of degrading base capabilities.
-
Agent execution architecture: Choose an orchestration pattern and explain how you manage state, enforce execution limits, handle tool failures, and prevent runaway loops.
-
Output validation strategy: Compare prompt engineering, API-based structured generation, and grammar-constrained decoding for guaranteeing valid outputs.
-
Multi-task serving infrastructure: Design a system that can serve multiple specialized model variants efficiently on shared hardware.
-
Monitoring and quality assurance: Define metrics for tracking agent reliability, tool selection accuracy, and output correctness.
Discuss trade-offs explicitly. What breaks first under load? Where do you accept risk? What would you build differently at 10× or 0.1× scale?
Hints
Hint 1
Think about where knowledge should live: what belongs in model weights versus external systems?
Hint 2
Agent orchestration isn't just about prompting—consider how you enforce hard limits on execution time and prevent infinite loops.
Hint 3
Structured output validation has a spectrum from soft (prompting) to hard (grammar enforcement)—what does production reliability require?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This design requires balancing model capability, infrastructure efficiency, and production safety. Start by translating requirements into concrete system constraints, then work through each component with explicit trade-offs.
1. Quantify the System Load
Turn qualitative requirements into numbers that inform architecture decisions:
- Request rate: 50k sessions across an 8-hour trading day averages about 1.7 requests/second, peaking at roughly 8.5/s during earnings season.
- LLM invocations per session: A typical multi-step workflow requires 4–6 model calls (initial planning, 2–3 tool steps, final synthesis). Peak load reaches approximately 40–50 LLM calls/second.
- Token throughput: Estimating 4,000 input tokens and 300 output tokens per call gives peak prefill demand of 160–200k tokens/s and decode demand of 12–15k tokens/s.
- Model memory: A 70B parameter model in BF16 requires roughly 140 GB for weights alone. With activation memory and KV cache, a tensor-parallel deployment across 4 H100s is typical. Factor in 6–8 replicas for throughput plus redundancy.
Key clarifications to establish: Does output go directly into automated trading systems (requiring stricter validation)? Must we maintain point-in-time correctness for backtesting? What are compliance retention windows for audit trails?
2. Model Customization Strategy
The central question: where should knowledge live?
Principle: Put stable behavioral patterns in weights; keep factual, numerical, and time-sensitive data in retrieval systems and live APIs.
| Method | Memory (70B model) | Training Speed | Serving Cost | Capability Risk |
|---|---|---|---|---|
| Full fine-tuning | ~1.1 TB (16 bytes/param for weights, gradients, optimizer state) | High compute, needs 16+ H100s with FSDP | 140 GB per specialized model | High forgetting risk |
| LoRA | ~180 GB (frozen base + adapter + optimizer) | Fast, 4 H100s sufficient | Adapters are 50–300 MB, share one base | Minimal forgetting |
| QLoRA | ~45 GB (4-bit quantized base) | 25–35% slower than LoRA | Same as LoRA at serving | Minimal forgetting |
| Pure RAG | Zero training | N/A | Higher prefill cost from long contexts | No forgetting |
What belongs in weights:
- Firm-specific terminology and jargon
- Standard output formatting conventions
- Tool-calling protocols and argument structure
- House analytical style
What must stay external:
- All numerical data (prices, metrics, exposures)
- Document content and filings
- Real-time market information
- Anything requiring citation or audit trail
Recommended approach: Build a hybrid system with RAG for all factual grounding, plus 2–3 task-specific LoRA adapters (document extraction, research planning, summary generation). Use QLoRA during development for fast iteration, then serve the adapters on a shared BF16 or FP8 base model.
Reserve full fine-tuning only if evaluation proves adapter capacity is insufficient—an unlikely scenario for this use case.
3. Agent Orchestration Architecture
Pattern choice: Implement a DAG-based planner with constrained execution, not free-form ReAct loops.
Why: ReAct's open-ended "thought-action-observation" pattern makes termination guarantees difficult. For production systems serving quantitative models, we need deterministic bounds.
Architecture:
- Planning phase: LLM generates a structured execution plan as a directed acyclic graph. Nodes represent tool invocations; edges represent data dependencies. Use constrained decoding to ensure valid plan structure.
- Execution engine: A deterministic scheduler runs independent nodes in parallel. For example, a document search and a database query execute concurrently rather than sequentially, reducing end-to-end latency.
- Bounded refinement: If a tool returns ambiguous results, allow up to 2 retry iterations with refined parameters before proceeding.
Hard safety limits (enforced in code, not by prompting):
- Maximum 8 steps per workflow
- 15-second wall-clock timeout
- Token budget ceiling (16k working window)
- Cycle detection via hashing (tool_name, arguments) tuples
When any limit triggers, return a partial result with explicit status: incomplete and reason.
State management:
- Persist workflow state in PostgreSQL or Redis
- Store plan, inputs/outputs per step, timestamps, retry counts
- Enable replay for debugging and audit review
- Support resume from failure points
Tool safety:
- Every tool is a typed RPC with JSON schema validation
- Execute with read-only, user-scoped credentials
- Run compute-intensive operations (backtests) in isolated containers with CPU and memory quotas
- Use idempotency keys to prevent duplicate expensive operations
- Implement exponential backoff retry, then fallback to cached results or degraded mode
Context window management (16k budget):
- System prompt and tool definitions: 2k tokens (prefix-cached across requests)
- Generated plan: ~1k tokens
- Retrieved document chunks: 8k tokens (reranked for relevance)
- Tool execution results: 3k tokens
- Output generation: 2k tokens
Critical: Never paste large tool outputs (timeseries, full documents) into context. Store them externally and provide the model with a handle plus summary statistics.
4. Structured Output Validation
Production systems cannot tolerate malformed outputs when feeding downstream pipelines.
Three approaches:
Prompt engineering: "Output valid JSON with fields X, Y, Z."
- Success rate: 95–98%
- At 50 calls/second, expect 1–2 malformed outputs per second at peak
- Each retry adds 2+ seconds
- Verdict: Insufficient for programmatic ingestion
Function calling APIs: Structured generation via API parameters
- Better than prompting (~99% valid)
- On open models, often implemented as enhanced prompting plus parsing
- No formal guarantee
- Verdict: Better, but still permits occasional failures
Grammar-constrained decoding (Outlines, vLLM guided generation):
- Compile JSON schema to finite state machine
- Mask invalid tokens at each generation step
- Output is syntactically valid by construction
- Overhead: <5% after grammar caching
- Verdict: Required for production reliability
Implementation: Use constrained decoding for all outputs feeding downstream systems.
Critical caveat: Constraints guarantee syntax, not semantics. Still validate:
- Value ranges (e.g., percentages between 0–100)
- Currency and unit enums
- Cross-field consistency (e.g., start_date < end_date)
- Business logic rules
Pattern for quality: Include a reasoning field that generates first, allowing the model to think through the problem before committing to structured fields.
Reproducibility: Determinism requires temperature 0, pinned model/adapter versions, and logged inputs. Note that GPU batching can still introduce variance; true auditability requires storing all inputs/outputs for replay.
5. Multi-Adapter Serving Infrastructure
Use vLLM's multi-LoRA serving capability, based on S-LoRA and Punica architectures.
Architecture:
- One shared base model (BF16 or FP8) loaded in GPU memory per replica
- Hot adapters cached in GPU memory
- Full adapter library in CPU RAM
- Async adapter loading on cache miss
Batching: Custom CUDA kernels (SGMV/BGMV) enable heterogeneous batching—one batch can serve requests using different adapters. Each forward pass computes output = base_weights · x + adapter_weights · x, maintaining high GPU utilization without dedicating separate replicas per task.
Memory management: Unified paging for KV cache and adapter weights from a shared pool prevents fragmentation and enables dynamic allocation.
Request routing:
- Gateway tags requests with adapter ID based on task type
- Router maintains adapter affinity (prefer nodes with hot adapters)
- Consider prefix cache hits (shared system prompts)
- Limit concurrent adapters per batch (e.g., max 4)
- LRU eviction for cold adapters
Load shedding: Under peak load, prioritize extraction jobs over exploratory chat. Implement autoscaling based on queue depth and KV cache pressure.
6. Observability and Evaluation
Distributed tracing: Use OpenTelemetry to instrument:
- Workflow-level spans (end-to-end latency)
- LLM call spans (prefill/decode time, token counts, adapter ID)
- Retrieval spans (query, reranking, latency)
- Tool execution spans (tool name, arguments, result summary, success/failure)
Agent-specific metrics:
- Step success rate per tool type
- Plan validity rate (parseable, executable DAG)
- Tool selection accuracy (does the chosen tool match intent?)
- Termination reason distribution (success vs. timeout vs. token limit)
- Retry rate per tool
Output quality metrics:
- Schema validation pass rate
- Semantic validation failure rate (valid syntax, invalid semantics)
- Numerical hallucination detection: compare extracted numbers against source documents using fuzzy matching
- Human feedback loop: analysts flag incorrect extractions
Cost and efficiency:
- Tokens per dollar by task type
- GPU utilization and KV cache hit rate
- Adapter cache hit rate
- Cost per research workflow
Evaluation datasets: Maintain golden sets of representative tasks with validated outputs. Run regression tests on each model/adapter update. Track task success rate, output correctness, and latency distributions.
Common Pitfalls
-
Putting knowledge in weights that should be retrieved: Never train revenue numbers or market data into the model. These cannot be cited, updated, or audited.
-
Underestimating context window pressure: Multi-step workflows accumulate context quickly. Budget explicitly and summarize aggressively.
-
Assuming prompts guarantee structure: Even careful prompt engineering fails 1–5% of the time, which is unacceptable for programmatic pipelines.
-
Ignoring termination guarantees: Rely on code-level limits, not model cooperation, to prevent infinite loops.
-
Neglecting adapter interference: When serving multiple adapters, monitor for quality degradation from adapter conflicts or cache thrashing.
Complexity
- Training: LoRA training on 70B model with QLoRA: O(dataset_size × sequence_length × adapter_rank); typically hours on one H100 for thousands of examples
- Serving latency: Dominated by prefill (O(input_length)) and decode (O(output_length × batch_size))
- Memory: O(model_params + active_adapters × adapter_params + batch_size × sequence_length) for KV cache
Code Sketch (Agent Executor)
from dataclasses import dataclass
from typing import List, Dict, Any, Optional
import asyncio
import hashlib
@dataclass
class ToolCall:
tool_name: str
arguments: Dict[str, Any]
dependencies: List[str] # IDs of prior steps
@dataclass
class ExecutionPlan:
steps: List[ToolCall]
max_steps: int = 8
timeout_seconds: float = 10.0
class AgentExecutor:
def __init__(self, tools: Dict[str, callable]):
self.tools = tools
self.seen_calls = set()
async def execute_plan(self, plan: ExecutionPlan) -> Dict[str, Any]:
results = {}
start_time = asyncio.get_event_loop().time()
for step_idx, step in enumerate(plan.steps):
# Check termination conditions
if step_idx >= plan.max_steps:
return {"status": "incomplete", "reason": "max_steps", "results": results}
if asyncio.get_event_loop().time() - start_time > plan.timeout_seconds:
return {"status": "incomplete", "reason": "timeout", "results": results}
# Cycle detection
call_hash = hashlib.sha256(
f"{step.tool_name}:{sorted(step.arguments.items())}".encode()
).hexdigest()
if call_hash in self.seen_calls:
return {"status": "incomplete", "reason": "cycle", "results": results}
self.seen_calls.add(call_hash)
# Wait for dependencies
if any(dep not in results for dep in step.dependencies):
return {"status": "error", "reason": "missing_dependency"}
# Execute tool with retry logic
try:
tool_fn = self.tools[step.tool_name]
result = await self._execute_with_retry(tool_fn, step.arguments)
results[f"step_{step_idx}"] = result
except Exception as e:
results[f"step_{step_idx}"] = {"error": str(e)}
return {"status": "incomplete", "reason": "tool_failure", "results": results}
return {"status": "success", "results": results}
async def _execute_with_retry(self, tool_fn: callable, args: Dict, max_retries: int = 2):
for attempt in range(max_retries + 1):
try:
return await asyncio.wait_for(tool_fn(**args), timeout=5.0)
except asyncio.TimeoutError:
if attempt == max_retries:
raise
await asyncio.sleep(2 ** attempt) # Exponential backoff
This architecture provides production-grade safety, observability, and efficiency for enterprise AI agent systems.