Object Detection and LLM-Assisted Crop Disease Diagnosis: System Architecture and Engineering Practices
This article presents an engineering practice for crop disease and pest diagnosis that combines object detection with large language model (LLM)-assisted advisory generation. It covers a four-layer system architecture, local visual inference and cloud-based LLM calls, a 37-class disease taxonomy across 12 crops, data preparation and evaluation practices, structured prompting and output validation, and the handling of batch processing, video, and real-time camera inputs. Readers can use the described module responsibilities, data flow, and engineering considerations to design or evaluate a similar diagnostic system.
1. Background
Frontline agricultural technicians often diagnose crop diseases and pests by relying on experience and reference atlases. The same disease can look very different across growth stages, lighting conditions, and camera angles, making misdiagnosis common for less experienced users. Delayed identification also affects product selection and application timing.
The system therefore needs to do two things at once: identify the disease class from an image and provide actionable treatment recommendations. This article focuses on object detection as the core component and uses a large language model as an auxiliary component. It describes the responsibilities of each module, the data flow, and key engineering considerations.
2. Overall System Architecture
The system can be divided into four layers.
- Access layer: Accepts a single image, an image folder, a local video, or a camera feed.
- Inference layer: The object detection model performs lesion localization and class prediction. It is deployed on a local server or edge device and can run without relying on an external network.
- Service layer: The backend handles task scheduling, result persistence, user authentication, and report generation. LLM API calls are also encapsulated in this layer.
- Presentation layer: The frontend handles uploads, result visualization, statistical charts, and interface personalization.
The data flow for a complete detection task is as follows: the user submits a task, the backend creates a task record, the inference service loads the model and processes the image, the results are written to the database, the LLM generates recommendations based on the structured results, and the frontend displays the results and supports report export.
Visual inference is kept local for two reasons. Field networks are often unstable, and relying on the cloud would affect availability. In addition, raw images contain plot information, and keeping them local makes data control easier. The LLM is deployed in the cloud because it requires strong language capabilities, and a second-level delay is acceptable for advisory text.
3. Visual Detection Module
3.1 Class Taxonomy Design
The system covers 12 crops and 37 classes, as follows.
- Apple: black rot, healthy, scab
- Bell pepper: bacterial spot, healthy
- Cassava: brown streak disease, bacterial blight, green mottle, mosaic virus, healthy
- Cherry: powdery mildew, healthy
- Corn: leaf spot, common rust, northern corn leaf blight, healthy
- Grape: black rot, leaf blight, healthy
- Citrus: huanglongbing
- Peach: bacterial shot hole, healthy
- Potato: early blight, late blight, healthy
- Rice: brown spot, rice blast, healthy
- Strawberry: powdery mildew, angular leaf spot, healthy
- Tomato: bacterial speck, early blight, late blight, leaf mold, Septoria leaf spot, healthy
Two points require attention in taxonomy design. First, “healthy” must be an independent class during training. Otherwise, when the model encounters a disease-free leaf, it can only assign it to the background or to an incorrect disease class, which significantly increases the false-positive rate. Second, class names should use one English identifier and one display name, and the frontend, backend, and database should use the same encoding to avoid multiple spellings for the same disease.
3.2 Data Preparation
Data quality determines the upper bound of model performance, and data preparation usually accounts for most of the work in the project.
- Collection guidelines: Standardize image resolution and record the capture device, lighting conditions, and crop growth stage. The same disease looks different at different stages, and this metadata helps analyze the causes of misclassification later.
- Annotation guidelines: Use rectangular boxes to annotate lesions or diseased leaf areas. When multiple lesions appear in one image, all of them must be annotated; missed annotations teach the model incorrect background features.
- Data splitting: Split training, validation, and test sets by capture batch or plot. If images of the same leaf appear in both the training and test sets, the metrics will be inflated and real-world performance will be worse.
- Data augmentation: Rotation, flipping, brightness adjustment, blur, and occlusion can be used. Color augmentation should be controlled carefully; otherwise, the color features of lesions may be distorted.
3.3 Training and Evaluation
The training stage uses mainstream deep learning frameworks. Common evaluation metrics include precision, recall, and mean average precision (mAP). Evaluation should not rely only on overall metrics; each class should also be checked individually. Metrics for small-sample classes often fluctuate more and require separate attention.
Early blight and late blight in tomato and potato are typical confusing pairs. The leaf lesions of the two diseases are similar in shape and are especially difficult to distinguish under poor capture conditions. For such class pairs, a confusion matrix can be used to identify the specific direction of misclassification, followed by targeted sample collection.
3.4 Inference Flow and Sample Code
The core of the inference stage is converting model outputs into structured data that the business logic can use. The following code is illustrative; function names and data structures should be replaced with the actual implementation.
def detect_image(detector, image_path, conf_threshold=0.5):"""Run detection on a single image and return a structured disease list."""image = read_image(image_path)raw_boxes = detector.predict(image)results = []for box in raw_boxes:if box.score < conf_threshold:continueresults.append({"class_name": box.label,"confidence": round(box.score, 3),"bbox": box.xyxy,})return results
Confidence thresholds should be adjusted by class. A threshold that is too low increases false positives, while a threshold that is too high misses small or indistinct lesions. In practice, the threshold for each class can be selected on the validation set to balance precision and recall.
4. LLM-Assisted Diagnosis
4.1 Separation of Responsibilities
The system does not ask the LLM to “look at the image” and identify the disease directly. Image recognition is handled by the detection model, and the LLM is only responsible for explaining the detection results and generating control recommendations. This makes results traceable: each recommendation can be linked to a specific detection record, and when problems occur, it is possible to determine whether the error came from the visual stage or the language stage.
4.2 Structured Input
The content passed to the LLM should be structured data rather than raw descriptions. Typical fields include crop species, disease class, confidence, lesion area ratio, region, and current season. Clearer fields lead to more stable generated content.
4.3 Prompt Design
The prompt needs to clearly constrain the model’s behavioral boundaries. An example is shown below.
You are a plant protection technical advisor. Provide advice only based on the detection results below; do not speculate about other diseases.Crop: TomatoDetected disease: Late blightAverage confidence: 0.87Lesion area ratio: about 12%Requirements:1. Explain the main symptoms and development conditions of this disease.2. Provide general approaches for cultural and chemical control.3. When mentioning product names, doses, or pre-harvest intervals, note: "Please refer to local agricultural extension recommendations and product labels."4. If confidence is below 0.6, indicate that manual review is required.Output in JSON format: disease, suggestions, cautions, need_review.
4.4 Output Validation and Risk Control
LLM outputs are uncertain, so the backend needs to validate them.
- Require a fixed JSON structure. If parsing fails, retry automatically; after the retry limit is exceeded, mark the result as pending.
- Flag dose numbers and product names in the output and remind users to follow labels and agricultural technician recommendations.
- Label recommendations in the interface as “reference opinions” and do not treat generated content as a final diagnostic conclusion.
5. Batch Processing, Video, and Real-Time Feeds
5.1 Batch Processing
Batch tasks run inference on images one by one through a queue. If a single file is corrupted or in an unsupported format, the system should record the failure reason and skip that file rather than interrupting the entire batch. After the task is completed, summarize the number of successes, the number of failures, and failure details.
5.2 Video Detection
Video detection generally samples frames at fixed time intervals. The same lesion appears repeatedly across consecutive frames; if detections are accumulated directly, the statistics will be seriously inflated. The solution is to associate detection boxes across adjacent frames, merge the same target based on class and position similarity, and then count.
5.3 Real-Time Camera Detection
Real-time detection requires image acquisition and model inference to run in separate threads, connected by a bounded frame queue. When inference cannot keep up with acquisition, stale frames should be dropped and only the latest frame kept. This keeps the displayed content roughly synchronized with the actual scene instead of letting latency accumulate and lose real-time value.
5.4 Statistics and Reports
Detection results can be aggregated by class, plot, and date and displayed as bar charts, line charts, and other visualizations. The frontend also supports report export.
