AI Agent Development and Implementation Guide: From Prompts to Production

    This guide breaks down AI agent implementation into four capability layers—model reasoning, knowledge, tools, and orchestration with state management—and walks through a practical build sequence. You will learn how to structure prompts, fix retrieval quality, add tool calls with human confirmation, move from Q&A to workflow automation, manage state for resumable tasks, and set up layered evaluation, gradual rollout, and monitoring. A four-week roadmap and common pitfalls are included to help teams ship a real, reusable agent.

    1. Get the Concepts Right: An Agent Is Not a Q&A Bot With a Longer Prompt

    In real projects, many teams treat an agent as “a longer prompt,” then find after launch that results are unstable and real business cases fail. To understand agents, split them into four capability layers that can evolve independently:

    1. Model reasoning layer: handles intent understanding, text generation, and simple planning. It has general language ability but lacks private knowledge and execution ability.
    2. Knowledge layer: brings in private information such as enterprise documents, policies, tickets, and product manuals through retrieval augmentation, solving the “the model doesn’t know” problem.
    3. Tool layer: lets the agent query databases, call internal APIs, read and write files, and send notifications, solving the “the model can’t do it” problem.
    4. Orchestration and state layer: chains multi-step tasks together and manages intermediate results, retries, and human confirmation, solving the “the task isn’t completed” problem.

    The practical path in the original text is essentially about adding capability layer by layer around these four: start with a low-barrier way to experience persona and knowledge base, then introduce automated workflows and an underlying state machine. You don’t have to go through every stage at once, but you must be clear about what each layer solves; otherwise it is easy to get lost in piling up tools.

    2. Step One: Build Your First Usable Agent Visually

    For beginners, the worst approach is to start with a complex framework. Set the first goal as “build an agent within 30 minutes that can answer business questions and call one tool,” and verify that the chain works end to end.

    2.1 Persona and Prompt Structure

    A high-quality prompt usually contains six blocks; missing one will expose problems in real scenarios:

    1. # Role
    2. You are an after-sales support assistant for a business line, serving frontline customer service.
    3. # Goal
    4. Locate the issue and give actionable steps within 3 conversation turns.
    5. # Knowledge Scope
    6. Answer only based on knowledge base retrieval results; if retrieval is empty, explicitly state that no basis was found.
    7. # Tool Usage Rules
    8. Call the order query tool when order information is needed; do not fabricate order status by guessing.
    9. # Output Format
    10. Give the conclusion first, then the steps (numbered list), and finally label the type of information source.
    11. # Boundaries and Refusal
    12. For price commitments or contract term changes, transfer to a human and output the handoff script.

    The most critical parts here are “Knowledge Scope” and “Boundaries and Refusal.” The former suppresses hallucination; the latter controls business risk. Many agents fail after launch not because they aren’t smart enough, but because they force an answer when they should refuse.

    2.2 Knowledge Base Usability

    Beginners often dump hundreds of pages of documents at once, then complain that retrieval is inaccurate. A more reliable approach is:

    • Split by semantically complete paragraphs; avoid cutting tables and headings into fragments;
    • Add metadata to each chunk (business line, effective time, applicable version), and filter before ranking during retrieval;
    • Build an “evaluation question set” with at least 30 real phrasings, and run regression tests after each change to the splitting strategy or prompt;
    • For long-document Q&A, use a two-stage strategy of “locate the section first, then read locally,” reducing interference from irrelevant context.

    2.3 A Minimal Tool Call Example (Pseudocode)

    1. def handle(user_input, session):
    2. plan = llm.decide(user_input, tools=["query_order", "create_ticket"])
    3. if plan.tool == "query_order":
    4. result = query_order(plan.args["order_id"]) # real business API
    5. return llm.answer(user_input, context=result)
    6. if plan.tool == "create_ticket":
    7. if not session.get("user_confirmed"):
    8. return "Please confirm whether to create the ticket; reply \"confirm\" and I will submit it."
    9. return create_ticket(plan.args)
    10. return llm.answer(user_input, context=retrieve(user_input))

    Note the human confirmation step: any operation with side effects (creating a ticket, sending a notification, changing configuration) should require confirmation by default. This is a basic production constraint.

    3. Step Two: Introduce a Private Knowledge Base and Long-Text Q&A

    When Q&A accuracy becomes the bottleneck, the problem is often not the model but retrieval. Optimize in three areas:

    • Recall layer: run keyword retrieval and vector retrieval in parallel, then apply fusion ranking, covering both proper nouns and semantic similarity;
    • Rerank layer: use a smaller model to score the relevance of candidate chunks, and send only the top few into generation;
    • Generation layer: require the model to cite sources one by one; conclusions that cannot be supported must explicitly state “insufficient basis.”

    Long-text scenarios also require controlling the context budget. Set a clear limit for “system instructions + retrieved chunks + conversation history,” and use rolling summaries for history rather than concatenating everything, which performs more stably in multi-turn scenarios.

    4. Step Three: Move From Q&A to Automated Workflows

    Real business value mostly appears in process tasks, for example “form submission -> information extraction -> content summarization -> notification sending -> archiving.” Expressing such needs with a workflow engine is more reliable than a long prompt, because process nodes are observable, retryable, and replaceable.

    Design points:

    1. Each node has a single responsibility with fixed input and output structures, making failure points easy to locate;
    2. The large model only handles “understanding and unstructured conversion”; deterministic logic goes to code;
    3. Instrument the full chain to record each step’s latency, token consumption, and failure reason;
    4. Grade failure strategies: retry retryable errors automatically, and route business validation failures to a human queue.

    5. Step Four: Understand State Transitions to Build Complex Tasks

    Multi-step tasks that can be interrupted and need human involvement require explicit state management. A minimal state machine can be described like this:

    1. state = {
    2. "goal": "Generate a resolution plan for a complaining customer",
    3. "slots": {"order_id": None, "issue_type": None},
    4. "steps": [],
    5. "pending_confirm": None,
    6. "retry": 0
    7. }
    8. def step(state):
    9. if state["slots"]["order_id"] is None:
    10. state["slots"]["order_id"] = ask("Please provide the order number")
    11. return state
    12. if state["pending_confirm"]:
    13. return confirm_or_rollback(state)
    14. plan = llm.plan(state)
    15. state["steps"].append(plan)
    16. return execute(plan, state)

    The benefit of state is task recoverability: after a process restart, or when a user leaves and comes back, the task can continue from the breakpoint instead of asking everything again. This is also the dividing line between “works in a demo” and “works in production.”

    6. Step Five: Evaluation, Launch, and Continuous Iteration

    An agent without evaluation cannot be iterated. Build three layers of evaluation:

    • Unit layer: whether tool call parameters are correct and formats are compliant;
    • Task layer: whether a given goal can be completed within a limited number of steps, with success rate and average steps;
    • Business layer: manually sample answer quality, and track human handoff rate and user adoption rate.

    At launch, prioritize gradual rollout: first internal trial, then small traffic, watching hallucination rate and tool failure rate. Logs and monitoring alerts should cover model calls, retrieval hit rate, and tool error codes, making it easy to quickly determine whether it is a knowledge problem or an execution problem.

    For enterprise internal deployment, you can combine general cloud capabilities: a container platform to host services, object storage to store documents, a message queue for asynchronous decoupling, and logging and monitoring services for observability. Baidu AI Cloud has corresponding product categories for these general capabilities, and you can select based on compliance and data boundary requirements.

    7. Common Pitfalls and How to Avoid Them

    • Pitfall 1: Chasing an all-platform experience. Tools are only carriers; make one scenario reusable first, then expand horizontally.
    • Pitfall 2: Writing longer and longer prompts. Conflicting instructions significantly reduce stability; structured is better than lengthy.
    • Pitfall 3: Letting the model do deterministic computation. Amounts, inventory, and time calculations should go to code.
    • Pitfall 4: Ignoring refusal design. Clear boundaries build more trust than forced answers.
    • Pitfall 5: Tuning parameters without evaluation. Every change should be backed by a regression question set.

    8. A Pragmatic Pace

    Week one: get single-point Q&A and one read-only tool working; week two: connect the private knowledge base and build an evaluation set; week three: turn the task into a recoverable state-transition workflow; week four: do gradual rollout and monitoring, forming an iteration loop. At this pace, a team can usually deliver a real, usable agent within a month and gain the ability to replicate it to more business scenarios.