Multimodal Search and Reasoning Agents: Building and Training Practices
Learn how to build multimodal agents that combine image cropping, text search, and image search to solve multi-hop questions. This article covers the agent loop, reinforcement learning, reward design, evaluation, and engineering practices for managing context, reliability, and cost.
1. The Problem: The Limits of Static Visual Understanding
Vision-language models are already capable at tasks such as image captioning. In real applications, however, questions often go beyond a single image: they span modalities and sources and require multiple verification steps.
Consider a racing photograph and a question asking for the difference between the founding year of the company represented by a small logo on the driver’s uniform and the driver’s birth year. Answering this requires at least four subtasks:
- Locate and recognize a tiny text logo within the full image.
- Identify the company behind the logo and retrieve its founding year.
- Confirm the identity of the person in the photograph.
- Retrieve the person’s birth year and calculate the difference.
A conventional single-turn model often fails not because it lacks reasoning ability, but because of two capability gaps:
- A perceptual resolution gap: When an image is resized to a fixed input size, small text may be lost during encoding. The model cannot read it clearly and instead guesses from language priors.
- A knowledge freshness gap: Knowledge stored in model parameters is static and bounded by a cutoff. It cannot cover every long-tail entity or recent fact.
The right approach is therefore not to expect the model to remember everything, but to teach it to invoke external capabilities as needed during reasoning. This is where the agent paradigm becomes valuable for visual tasks.
2. Core Architecture: A Reason–Act–Observe Loop
The task can be modeled as a finite-horizon decision process. The state consists of the available images and previous observations. An action invokes a tool, and the environment returns an observation that is appended to the context. The process continues until the model produces a final answer.
The following pseudocode illustrates a minimal implementation using generic interfaces:
MAX_STEPS = 8def run_agent(image, question):ctx = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": [image, question]}]for step in range(MAX_STEPS):out = policy.generate(ctx) # Model output with an optional tool callaction = parse_action(out) # Parse the structured actionif action.type == "final":return action.answerobs = TOOLS[action.type](**action.args)ctx.append({"role": "assistant", "content": out})ctx.append({"role": "user", "content": summarize(obs)})return fallback_answer(ctx)
Three constraints matter:
- Actions must be structured so they can be parsed and validated.
- Observations must be compressed to prevent the context from growing too quickly.
- The number of steps must be bounded to avoid endless loops and uncontrolled costs.
3. Designing the Action Space: Three Complementary Tools
A practical multimodal action space typically contains three tool categories, each addressing a different capability gap.
Image Cropping: Recovering Useful Resolution
The model outputs a bounding box in normalized coordinates. The system crops that region from the original image and sends the crop back to the model. This improves effective resolution for the target region without increasing computation across the entire image.
Important implementation details include:
- Define coordinate semantics explicitly in the prompt: normalized values from 0 to 1 or pixel coordinates. Clamp out-of-range values.
- Set a minimum crop side length, since extremely small crops may become blurry when upsampled.
- Limit repeated cropping of the same region to prevent unproductive chains of progressively tighter crops.
Text Search: Retrieving Current Facts
Text search converts a natural-language query into external webpage excerpts.
The main risk is context pollution. A single search may return thousands of tokens, and repeated searches can overwhelm the model with irrelevant material. A common solution is a summarization stage that compresses raw results into a small set of facts relevant to the current question. Only the summary enters the model context; the original text remains in external storage for reference.
Image Search: Identifying Entities
Reverse image search is useful for answering “Who is this?” or “What is this?” It often serves as a prerequisite for text search: identifying an entity first makes it possible to construct a more precise text query.
In practice, image search and text search frequently form a two-hop path:
Image → entity → attribute
The three tools work together as follows: cropping improves perception, image search identifies the entity, and text search supplies the facts. If a required capability is missing, the multi-hop chain can break at that step.
4. Using Reinforcement Learning to Turn a Workflow into a Policy
A workflow encoded only in prompts can become rigid. The model may follow a fixed sequence without recovering when search results are empty or an entity has been misidentified. Reinforcement learning can train a policy to make adaptive decisions.
Actions and Trajectories
A trajectory consists of a sequence of reasoning, tool calls, and observations, with a final answer as the last action.
Reward Design
Reward design is central to training. A layered approach can include:
- Outcome reward: Give a strong reward for a correct answer. This is the primary signal.
- Format reward: Give a small reward for parseable actions, valid coordinates, and nonempty queries to help the model learn the action format quickly.
- Efficiency penalty: Penalize excessive steps, repeated calls to the same tool, and heavily overlapping crops to discourage unnecessary tool use.
- Optional process reward: Apply a small positive reward for sensible dependency ordering, such as image search before text search. Use this cautiously: overprescribing the process can limit autonomous exploration.
Training Workflow
A reusable training approach is to begin with cold-start fine-tuning on a small set of human-written or rule-generated trajectories so the model learns the action syntax. Then use reinforcement learning with verifiable rewards to expand exploration.
Maintain a fixed evaluation set throughout training and use it for early stopping to guard against reward hacking.
One common failure mode deserves special attention: the model learns to simulate valid tool use. Its output has the correct format, but its parameters are meaningless. Strong tool-side validation helps prevent this. For example, an empty query should return an error observation, ensuring that invalid actions earn no benefit during training.
5. Evaluation: Look Beyond Final-Answer Accuracy
A single metric can hide important weaknesses. Evaluation should cover at least four dimensions:
| Dimension | Metrics | Purpose |
|---|---|---|
| Correctness | Answer accuracy | Primary measure, covering multi-hop questions and numerical calculations |
| Tool efficiency | Average step count, invalid-call rate | Measures whether the policy uses tools economically |
| Perception | Crop hit rate | Measures overlap between crop boxes and annotated small-target regions |
| Robustness | Completion rate when searches return no results or time out | Tests recovery and fallback behavior |
When constructing the evaluation set, prioritize questions with programmatically verifiable answers, such as numbers, dates, and entity names. This supports automated rewards and evaluation while avoiding noise introduced by model-based grading.
6. Production Engineering: Reliability and Cost
Tool Timeouts and Retries
External search is a major source of instability. Configure timeouts, rate limits, and degraded responses. A timeout should be returned to the model as an ordinary observation rather than raised as an exception that terminates the trajectory.
Tiered Context Storage
Keep raw search documents in object storage. Retain only summaries and reference identifiers in the model context, retrieving the original material again when needed.
Concurrency and Queues
Trajectory sampling has long-tail execution times. Use a message queue to decouple sampling from training, and a container platform to host elastic inference replicas.
Observability
Log each tool call’s parameters, latency, response length, and added token count. Monitor step-count distributions and failure rates, and configure alerts.
Without trajectory-level logs, it is difficult to determine why a particular step went wrong.
Cost Control
Smaller models are suitable for high-concurrency online workloads, while larger models can handle offline batch processing and difficult cases. A routing-based deployment can combine the two.
In the Baidu AI Cloud context, these infrastructure needs map to general product categories: object storage for images and raw search content, container platforms for inference and sampling clusters, message queues for task decoupling, and logging and monitoring services for trajectory tracing and failure detection.
7. Common Pitfalls and Recommendations
- Treating prompts as a substitute for training: Prompts can support a demonstration, but they do not cover every long-tail failure path. Training is needed for more reliable behavior.
- Skipping the summarization layer: Without context compression, multi-hop tasks are likely to lose important information partway through.
- Rewarding only the final outcome: Without format and efficiency signals, convergence can be slow and policies may degenerate.
- Leaving the step count unbounded: Long-tail requests can drive costs and latency out of control.
- Using training and evaluation data from the same source: This can substantially overestimate performance. Maintain an independent, verifiable holdout set.
The technical foundation is straightforward: use tools to bridge perception and knowledge gaps, summaries to control context growth, reinforcement learning to develop adaptive planning and self-correction, and trajectory-level observability to support operational reliability.
The same architecture can be reused for document understanding, difficult-case review in industrial inspection, and multi-hop evidence gathering for content moderation. The toolset and reward definitions change, but the core approach remains the same.
