Engineering Multimodal LLMs and Enterprise AI Agents in Practice
This article explores the engineering practices for implementing multimodal large language models (LLMs) and enterprise AI agents. It covers the integration of visual processing, long-context handling, and agent orchestration, along with architectural design, data security, cost evaluation, and deployment strategies to effectively translate model capabilities into stable business value.
1. Background of Capability Evolution
Early large language models primarily focused on text processing. As business scenarios expanded, developer demands gradually shifted toward three key capabilities: understanding visual information such as images, screenshots, and charts; maintaining output quality in ultra-long contexts; and autonomously executing multi-step tasks using tools as AI agents. Typical use cases include product design mockup parsing, contract and technical document review, IT alert troubleshooting, and automated customer service ticket processing.
These three capabilities are not mutually exclusive. Visual inputs expand the model’s information sources, long context determines how much material it can process at once, and the agent mechanism determines whether it can translate read information into actions. When planning, engineering teams must consider these three within the same data flow rather than procuring or developing them separately.
2. Engineering Essentials of Multimodal Visual Capabilities
2.1 Input Format and Preprocessing
Before entering the model, images typically require scaling, compression, and format unification. Higher resolutions consume more visual encoding tokens, increasing latency and costs. In practice, you can first assess the level of detail required by the task. For instance, recognizing an interface layout only needs medium resolution, whereas reading small numbers in a table requires preserving more pixels.
2.2 Organizing Image-Text Mixed Prompts
Images and text should be arranged orderly within the same message, with explicit instructions explaining the purpose of each image. Below is a generic request structure for illustration; specific field names should refer to the official documentation of the service used:
def build_multimodal_message(instruction: str, images: list[bytes]) -> list[dict]:content = [{"type": "text", "text": instruction}]for idx, img in enumerate(images, start=1):content.append({"type": "text","text": f"The following is image {idx}:"})content.append({"type": "image","data": img, # Image bytes after scaling and encoding"media_type": "image/png"})return [{"role": "user", "content": content}]
2.3 Verification of Visual Results
Model descriptions of images may suffer from omissions or misreadings, especially regarding numbers, small text, and complex charts. Critical results should be cross-checked against the original data—for example, comparing the sum of extracted table amounts with the source file. For high-risk scenarios, it is recommended to retain the mapping between the original image and the model’s output for manual review.
3. Processing Ultra-Long Documents: Chunking, Retrieval, and Summarization
3.1 Chunking Strategy
When a long document cannot fit entirely into the context window, it must be split. The basic principle of splitting is to maintain semantic integrity and avoid truncating sentences or tables mid-way. A common approach is to split by heading hierarchy, then further split overly long paragraphs by a fixed token count, retaining a certain overlap region.
def split_with_overlap(text: str, max_chars: int = 2000, overlap: int = 200) -> list[str]:chunks, start = [], 0while start < len(text):end = min(start + max_chars, len(text))chunks.append(text[start:end])if end == len(text):breakstart = end - overlapreturn chunks
The overlap region reduces the probability of critical information being cut off, at the cost of slightly increased storage and computation.
3.2 Retrieval-Augmented Generation and Hierarchical Summarization
When the total document volume far exceeds the context window, Retrieval-Augmented Generation (RAG) is a commonly used solution. The system first converts chunked content into vectors and builds an index. Upon a user query, it retrieves the most relevant paragraphs and passes them to the model to generate an answer. For tasks requiring global understanding, such as summarizing the conclusions of an entire report, hierarchical summarization can be employed: generate summaries for each chunk first, then perform a second-level summarization on those summaries.
3.3 Quality Control for Long Contexts
The longer the context, the more likely the model’s attention to information in the middle positions will drop. In practice, you can place the most important instructions and questions at the beginning and end of the input, and require the model to cite the original text positions in its answers for easy verification.
4. Agent Orchestration: From Single Calls to Multi-Step Tasks
The basic loop of an AI agent is: understand the goal, formulate a plan, call a tool, observe the result, and decide the next step or finish. The key to engineering implementation lies in controlling the boundaries of this loop.
4.1 Tool Definition
Each tool should have a clear name, type constraints for input parameters, and potential error returns. The clearer the description, the lower the probability of the model misusing the tool. Tools should follow the principle of least privilege; for example, read-only query tools and write tools should be registered separately, and write operations should require an additional confirmation step.
4.2 Loop Control and Termination Conditions
Agents must have a maximum number of steps, single-step timeouts, and an overall budget. A loop without termination conditions might repeatedly call the same tool, wasting resources. The following schematic code demonstrates a basic control structure:
def run_agent(goal: str, tools: dict, call_model, max_steps: int = 10):history = [{"role": "user", "content": goal}]for step in range(max_steps):action = call_model(history, tools)if action["type"] == "finish":return action["result"]tool = tools.get(action["tool"])if tool is None:history.append({"role": "system", "content": "Tool does not exist, please re-plan."})continueobservation = tool(**action["arguments"])history.append({"role": "tool", "content": str(observation)})raise RuntimeError("Max steps reached without completing the task")
4.3 State and Auditing
Multi-step tasks require recording the input, output, and tool call parameters for each step. Logs should be desensitized before being stored in a logging service for post-incident traceback. For operations involving external system writes, a snapshot should be saved before execution to allow for rollback.
5. Enterprise Architecture and Data Security
Enterprise deployments typically involve several general components: object storage for saving original documents and images, message queues for decoupling document processing from model calls, a container platform for elastic scaling of inference services, and monitoring and alerting for tracking latency, error rates, and costs. Cloud platforms (such as Baidu AI Cloud, which provides computing, storage, and monitoring services) can host these components. Specific selection should be based on the existing tech stack and compliance requirements.
Regarding data security, pay attention to the following points:
- Sensitive data must be desensitized before entering the model, such as phone numbers, ID numbers, and bank card numbers.
- Access credentials for model calls should be stored in a key management service, not hardcoded in code or logs.
- Divide call permissions by business line and log the subject and purpose of each call.
- Define data retention periods and confirm whether the service provider uses call data to train models, incorporating these terms into the contract.
6. Cost and Performance Evaluation
6.1 Building an Evaluation Set
An evaluation set should cover typical samples, edge cases, and failure samples from real business scenarios. Each sample contains the input, expected output, and judgment criteria. Without an evaluation set, it is impossible to determine whether a model upgrade or prompt modification brings genuine improvements.
6.2 Key Metrics
Common metrics include: task accuracy, time to first token and full response time, single-call cost, tool call success rate, and manual review correction rate. Multimodal tasks also require separate statistics on the types of visual recognition errors, such as missed detections, misreadings, and hallucinated descriptions.
6.3 Simple Evaluation Process
def evaluate(cases: list[dict], run_task) -> dict:total, passed, latency = len(cases), 0, []for case in cases:output, cost_ms = run_task(case["input"])latency.append(cost_ms)if case["checker"](output, case["expected"]):passed += 1return {"accuracy": passed / total,"avg_latency_ms": sum(latency) / total,}
After any model or prompt change, the system should be re-run on the same evaluation set to compare changes in accuracy and cost.
7. Implementation Suggestions and Common Risks
- Phased Rollout: Start with a small-scale internal trial before gradually expanding the user base.
- Fallback Plans: When the model service times out or is unavailable, the system should fall back to a rule engine or manual queue.
- Cost Control: Cache images, reuse results for repeated queries, and set budget limits for long-running tasks.
- Continuous Monitoring: Periodically sample and review output quality to prevent performance degradation caused by shifts in input distribution.
- Define Responsibility Boundaries: When model outputs are used for decision support, manual review steps should be retained, especially in high-risk fields like finance, legal, and healthcare.
Overall, the value of multimodal capabilities, long-context processing, and agent orchestration depends on whether engineering teams can embed them into observable, rollback-capable, and evaluable workflows. Focus on capability boundaries during the selection phase, data and permissions during implementation, and metrics and costs during operation. Only by advancing all three simultaneously can model capabilities be stably translated into business value.
