Building a Foreign Trade AI Agent with Open-Source LLMs: Architecture, RAG, and Deployment Guide

    Open-source large language models have become capable and affordable enough for small teams to build domain-specific AI agents. This article walks through a practical architecture for a foreign trade assistant, covering a three-layer design, knowledge base construction with sentence-aware chunking, intent recognition with parseable outputs, multi-step task orchestration, vector database selection, GPU autoscaling, and compliance practices. Each step includes sample code, key parameters, and common risks to watch for.

    At 2 a.m., a friend doing independent development messaged me with just two words: “This is insane.” He had quit his job six months earlier to build a foreign trade assistant, but kept hitting walls over API costs and the barriers to model fine-tuning.

    Over the past year, open-source LLMs have steadily improved while inference costs have dropped. This gives small teams a real opportunity to build vertical-domain intelligent applications. This article avoids tying you to any specific product. Instead, it covers a general architecture, implementation steps, and the parameters and risks to watch at each stage.

    What Are the Two Hard Problems of Vertical Agents?

    When building agents for industries like foreign trade, legal, or healthcare, small teams typically face two problems.

    First, general-purpose models lack industry-specific private data. Product quotes, customs clearance rules, and customer order history in foreign trade simply aren’t in a model’s training data. Ask directly, and the model tends to fabricate parameters or rules—making the system unusable in production.

    Second, engineering costs are high. Full fine-tuning requires large amounts of high-quality corpus and GPU clusters, which independent developers can rarely afford. After deployment, concurrency management, elastic scaling, and monitoring also consume significant engineering time.

    In practice, the most common approach is to skip fine-tuning the base model and instead use Retrieval-Augmented Generation (RAG) to keep industry knowledge external, letting the model answer based on retrieved content. This lets you focus on data quality and process design.

    How Should the Three-Layer Architecture Be Structured?

    A highly available vertical agent is typically divided into three layers.

    Layer Primary Responsibility Common Components
    Data & Knowledge Layer Ingestion, cleaning, chunking, vectorization, storage Object storage, message queues, vector databases
    Model & Inference Layer Load open-source models, serve inference APIs GPU container instances, OpenAI-compatible inference services
    Business & Orchestration Layer Intent recognition, multi-turn dialogue, retrieval triggering, tool calls Web services, workflow engines, business system APIs

    Keep interfaces between the layers clean so you can swap models or vector databases independently. If the inference service exposes an OpenAI-compatible API, switching models later requires almost no changes to business code.

    How Do You Build the Knowledge Base? From Files to Searchable Chunks

    Foreign trade materials are mostly PDF manuals and Excel quotes—messy formats. Knowledge base quality depends heavily on upfront parsing and chunking.

    Chunking by Sentence and Token Count

    Splitting by a fixed character count often cuts sentences in half, breaking semantics. A more reliable approach is to split by sentence first, then combine sentences into chunks within a token budget, keeping a small overlap of sentences for context.

    1. from typing import Callable, List
    2. def split_sentences(text: str) -> List[str]:
    3. """Split sentences by Chinese sentence-ending punctuation and newlines. Use different rules for English text."""
    4. seps = "。!?\n"
    5. sentences, buf = [], ""
    6. for ch in text:
    7. buf += ch
    8. if ch in seps:
    9. if buf.strip():
    10. sentences.append(buf.strip())
    11. buf = ""
    12. if buf.strip():
    13. sentences.append(buf.strip())
    14. return sentences
    15. def chunk_by_tokens(
    16. text: str,
    17. count_tokens: Callable[[str], int],
    18. max_tokens: int = 400,
    19. overlap_sentences: int = 1,
    20. ) -> List[str]:
    21. """Chunk by token budget, keeping overlap_sentences sentences of overlap between adjacent chunks."""
    22. chunks: List[str] = []
    23. current: List[str] = []
    24. current_len = 0
    25. for sent in split_sentences(text):
    26. n = count_tokens(sent)
    27. if current and current_len + n > max_tokens:
    28. chunks.append("".join(current))
    29. current = current[-overlap_sentences:] if overlap_sentences else []
    30. current_len = sum(count_tokens(s) for s in current)
    31. current.append(sent)
    32. current_len += n
    33. if current:
    34. chunks.append("".join(current))
    35. return chunks

    count_tokens should use a tokenizer consistent with your embedding model; otherwise actual lengths won’t match the budget. If a single sentence exceeds max_tokens, you need forced splitting, or you’ll end up with oversized chunks.

    Parsing PDFs and Excel

    • PDF: Extract text with PyMuPDF or pdfplumber. Scanned documents require OCR first, with manual spot-checks of recognition results.
    • Excel: Read each worksheet with pandas and convert each row into “field: value” text, e.g., “Product: stainless steel thermos; FOB price: $3.20; MOQ: 500 units”. Retrieved content then carries its own field meanings.
    • Metadata: Store source file, page number or worksheet, version number, effective date, and applicable customer scope with each chunk. Prices and rules change, so version information helps determine whether content is outdated.

    Writing to a Vector Store and Retrieving

    Convert chunks to vectors using an open-source embedding model (such as the BGE series), and write them to a vector database along with metadata. The typical query flow:

    1. Convert the user’s question to a vector.
    2. Retrieve Top-K candidates (e.g., 20), filtered by metadata such as customer scope and validity period.
    3. Score candidates with a reranking model, keeping roughly the top 5 chunks.
    4. Put these chunks and the question into the prompt, instructing the model to answer only from the given content and cite sources.

    If the top retrieval score falls below a threshold, the system should tell the user “no relevant information found in the knowledge base” rather than letting the model improvise.

    Measuring Quality with Offline Evaluation

    Before launch, prepare 100–200 test questions with reference answers, covering product specs, pricing, clearance rules, and email scenarios. Rerun after every change to chunking or retrieval parameters, tracking these metrics:

    • Recall: Does the correct chunk appear in the Top-K results?
    • Answer faithfulness: Can every part of the answer be traced to retrieved chunks?
    • Hallucination rate: The proportion of numbers, rules, or commitments in answers that lack supporting evidence.

    These metrics reveal whether hallucinations come from retrieval gaps or poor prompt design, guiding the next optimization step.

    How Do You Get Parseable Output from Intent Recognition?

    A foreign trade assistant needs to distinguish whether the user is asking about a product, drafting an email, checking logistics, or something else. Model output must be parseable structured data, or downstream business code can’t run reliably.

    Here’s an example of an intent recognition output:

    1. {
    2. "intent": "product_query",
    3. "confidence": 0.92,
    4. "slots": {
    5. "product_name": "stainless steel thermos",
    6. "quantity": null
    7. },
    8. "tool_call": null
    9. }

    intent values should be a fixed enum: product_query, draft_email, logistics_query, other. The system processes model output as follows:

    1. Parse with json.loads.
    2. Validate field types and value ranges with pydantic or jsonschema.
    3. On validation failure, retry once; if it fails again, fall back to a default path.
    4. If confidence is below 0.6, ask the user for clarification instead of executing.

    Tool calls also need a fixed format. For logistics queries, the model only outputs the structure below; business code performs the actual API request:

    1. {
    2. "name": "get_logistics_status",
    3. "arguments": {
    4. "tracking_no": "extracted from context by the system; ask the user if missing"
    5. }
    6. }

    The model should never construct SQL or shell commands directly. Tool parameters must be validated for type and permissions in code.

    How Do You Orchestrate Multi-Step Tasks?

    Requests like “Find the quote we sent the US client yesterday, then draft a follow-up email” require multi-step execution. A state machine is recommended, with common states including: received, planning, query CRM, extract information, generate draft, human review, completed, and failed.

    Record these fields for every step to enable retries and troubleshooting:

    1. {
    2. "run_id": "2026-11-24-0001",
    3. "step": "fetch_crm_quotes",
    4. "status": "pending",
    5. "idempotency_key": "2026-11-24-0001:fetch_crm_quotes",
    6. "max_retries": 2,
    7. "timeout_seconds": 10,
    8. "on_failure": "human_handoff"
    9. }
    • Timeouts: Every external call needs a timeout, so one slow API doesn’t stall the whole chain.
    • Retries: Retry only network and 5xx errors, with limited attempts and exponential backoff.
    • Idempotency: Use idempotency_key to prevent duplicate execution, such as sending the same email twice.
    • Fallback: On repeated failure or low confidence, hand the task to a human with full context preserved.

    How Do You Choose a Vector Database?

    Selection depends mainly on data scale, filtering needs, update frequency, and operations capacity.

    • Development phase: A lightweight embedded library works for quickly validating the pipeline.
    • Moderate data with an existing relational database: The pgvector extension on Postgres reduces component count and enables joint queries with business data.
    • Large-scale data with high-performance filtering and horizontal scaling: Dedicated vector databases like Milvus or Qdrant are options, but require extra operational work.

    Validate three things before deciding: query latency with metadata filtering, whether incremental updates affect queries, and whether backup and recovery procedures are clear. Base performance numbers on your own data and query workload—don’t rely on other people’s benchmarks.

    How Do You Control Scaling and Cost in Deployment?

    The inference service is the main cost driver, so its scaling strategy needs dedicated design.

    Scaling Metrics

    GPU utilization doesn’t necessarily reflect queue pressure. For LLM inference, concurrent request count or queue length are better scaling metrics. These need to be exposed to the HPA through a custom metrics adapter such as the Prometheus Adapter.

    1. apiVersion: autoscaling/v2
    2. kind: HorizontalPodAutoscaler
    3. metadata:
    4. name: llm-infer
    5. spec:
    6. scaleTargetRef:
    7. apiVersion: apps/v1
    8. kind: Deployment
    9. name: llm-infer
    10. minReplicas: 1
    11. maxReplicas: 4
    12. metrics:
    13. - type: Pods
    14. pods:
    15. metric:
    16. name: inflight_requests
    17. target:
    18. type: AverageValue
    19. averageValue: "8"

    averageValue should be determined through load testing. During testing, monitor both time-to-first-token and GPU memory usage to find the maximum concurrency that stays within your latency target.

    Cold Starts and Model Caching

    Loading a large model can take minutes. If minReplicas is set to 0, the first request waits a long time. Recommendations:

    • Keep at least 1 pre-warmed replica for core services.
    • Pre-load model files from persistent storage or bake them into images, avoiding remote downloads on every scale-up.
    • Scale to 0 only for latency-insensitive offline tasks.

    Cost Estimation

    Monthly cost can be roughly broken down as:

    Monthly cost ≈ model invocation fees + GPU instance hours + storage + vector database + logging and monitoring + operations labor

    Model invocation fees depend on average input/output tokens per request and daily request volume. Estimate with one week of real traffic first, then reserve headroom for peaks. Don’t just look at unit prices—also account for the extra calls from retrieval and reranking.

    What Does Compliance and Risk Control Require?

    Foreign trade involves customer information and commercial data, so compliance can’t be an afterthought.

    • Data masking: Mask personal information such as customer contact details and banking data before ingestion; keep only business-required fields.
    • Least privilege: Grant the agent’s CRM account only the read permissions it needs, with data isolation by customer or tenant.
    • Cross-border data transfer: If using foreign models or APIs, verify applicable cross-border data transfer requirements and confirm the provider’s data processing terms.
    • Validity statements: Clearance rules and tariffs change. Record the effective date for every rule and note in answers that “the latest official announcements prevail.”
    • Human review: Generated emails and quotes must be confirmed by a human before sending; the system should never send outbound messages automatically.
    • Audit logs: Log user requests, retrieval sources, model outputs, and tool calls, with defined retention periods.

    Conclusion

    Open-source models have lowered the barrier to the models themselves, but a reliably deployable agent still requires a high-quality knowledge base, parseable output structures, controlled scaling strategies, and clear compliance processes. With clear data conditions, well-defined business scenarios, and solid engineering capabilities, small teams can build usable vertical applications at relatively low cost. Doing better depends on understanding the business and continuous evaluation and iteration—not on any single technology.