Building Enterprise AI Assistants: From Knowledge Q&A to Code-Driven Diagnosis

    Enterprise AI assistants often start as knowledge Q&A tools but need to evolve into systems that can execute tasks. This article explores a "code as action" paradigm, a six-layer architecture covering identity, planning, data access, tools, sandboxed execution, and audit, plus practical guidance on security governance, traceable evidence, evaluation metrics, and a phased rollout path for safe production deployment.

    From Answering Questions to Completing Tasks

    Enterprise demand for AI assistants usually begins with knowledge Q&A, but it rarely stops there.

    When a user asks “how do I complete this business process,” an assistant can provide instructions based on documentation. But when the user follows up with “help me find out why the process failed,” the system needs to query business status, read relevant records, identify the failing step, and decide whether human intervention is required. At that point, relying solely on a language model to generate natural language answers cannot produce a trustworthy end-to-end result.

    For this reason, an enterprise AI assistant needs to connect three types of capabilities:

    • Understanding: recognizing user intent, business objects, time ranges, and constraints.
    • Action: searching knowledge, querying data, invoking tools, and orchestrating multi-step tasks within authorized boundaries.
    • Feedback: verifying execution results, accumulating reviewed experience, and providing reference for future tasks.

    These capabilities are not simply a matter of “having a powerful enough model.” In real deployments, they must be supported by identity authentication, data governance, an execution environment, and audit mechanisms. A reliable assistant should know clearly which actions it can execute directly, which require additional information, which require approval, and which should be refused.

    Code as Action: Organizing Tasks with Executable Logic

    “Code as action” is a task execution paradigm for AI agents: the model expresses a task plan as code, a controlled runtime executes that code, and program logic orchestrates tool calls, handles intermediate results, and completes computation.

    For example, investigating a failed business request might involve these steps:

    1. Confirm the business identifier and the abnormal time window;
    2. Query the relevant request records;
    3. Aggregate results by error type;
    4. Correlate against resource metrics and change events;
    5. Output evidence, likely causes, and follow-up recommendations.

    If all of these steps were passed back and forth in natural language, the context would grow long, intermediate results could become distorted, and conditional checks could be missed. Code expresses loops, branches, aggregation, and result validation more explicitly, and it makes it easier to reuse already-verified computation logic.

    However, this paradigm does not mean the model can freely execute arbitrary code. Its proper boundary is: let the model organize task logic, let controlled tools provide actual capabilities, and let the execution platform enforce security policies.

    For fixed workflows, a small number of operations, or high-risk business processes, structured tool calling, rule-based orchestration, and human approval may be more appropriate. Code-driven execution delivers the most value when tasks involve substantial data processing, dynamic branching, or multi-step combinations.

    A Layered Architecture to Keep Models from Directly Controlling Business Systems

    A general-purpose enterprise AI assistant architecture can be divided into six layers.

    1. Interaction and Identity Layer

    This layer receives user requests and determines the user’s identity, organization, business role, and current permissions. An assistant must not assume that understanding a user’s language means the user has the corresponding operational privileges.

    For example, when a user asks to query certain business data, the system must first check whether the user is authorized to access that business object. An identity claim made in conversation is only an input—it cannot replace server-side authentication results.

    Session context should also have defined retention scope and expiration, so that sensitive data from old tasks is not unnecessarily carried into new ones.

    2. Intent Recognition and Task Planning Layer

    The planning layer breaks user goals into executable steps and identifies missing conditions.

    “The system is slow, please take a look” is not a sufficiently clear diagnostic request. The assistant should first confirm the system scope, the abnormal time window, the affected features, and observable symptoms. When necessary, it should ask follow-up questions to fill in missing conditions rather than jumping to a generalized conclusion.

    A task plan should also include completion criteria—for example, “obtain the request latency distribution within the abnormal window and produce a diagnostic report with evidence citations”—rather than a vague goal like “analyze the system issue.”

    3. Knowledge and Data Access Layer

    Knowledge Q&A typically requires retrieving policies, operation manuals, incident records, and business documentation. Diagnostic tasks may need access to metrics, logs, traces, and change records.

    Both categories of data should be brought under unified access control, while keeping their respective processing approaches. Document retrieval needs attention to version, effective time, and content provenance; operational data queries need attention to time windows, sampling methods, and field semantics.

    Permission filtering must be completed before data enters the model’s context. Do not hand unauthorized content to the model first and then ask the model not to leak it.

    4. Tool Capability Layer

    The tool layer wraps business capabilities as operations with clear boundaries—querying status, fetching metrics, submitting tickets, or requesting changes.

    Every tool should define input constraints, permission requirements, return structures, and failure behavior. Write operations additionally require idempotency definitions, approval conditions, and possible compensation measures.

    Tool descriptions should be clear enough for the model to understand when to use each tool; at the same time, actual security enforcement must be implemented by the tool service or execution platform, not by description text alone.

    5. Sandboxed Execution Layer

    Model-generated code should run in an isolated, restricted environment, not directly inside core business processes.

    Isolation measures include limiting network access, file read/write, execution time, memory, and compute resources, and forbidding credential access, host environment modification, or installation of unapproved dependencies. By default, the execution environment should not have full access to business systems.

    Code inspection, resource limits, and runtime isolation must work together. Keyword filtering of dangerous statements alone cannot form a complete security defense.

    6. Verification and Audit Layer

    Successful execution does not mean task success. The verification layer must check whether returned data is complete, whether time ranges are correct, whether conclusions are backed by evidence, and whether operations produced the expected results.

    Audit records should cover user requests, task plans, actual invocations, approval information, execution results, and final conclusions. That way, when a mistake or wrong judgment occurs, the team can reconstruct the process instead of seeing only a final answer.

    Understanding the Execution Loop Through a Diagnostic Scenario

    Suppose a user reports: “A business API has been timing out frequently recently. Please help investigate.”

    The assistant should first clarify the business scope and time window, confirm the user has query permissions, and then generate a read-only diagnostic plan. Next, it retrieves request records, resource metrics, and change events through controlled tools.

    The following pseudocode illustrates the workflow—it does not correspond to any specific framework, API, or runnable implementation:

    1. task = parse_request_and_confirm_scope()
    2. verify_user_permissions(task.business_object)
    3. request_records = query_permitted_request_data(task.time_window)
    4. resource_metrics = query_permitted_resource_data(task.time_window)
    5. change_events = query_permitted_change_records(task.time_window)
    6. if request_records is empty:
    7. return "No request evidence found in the current scope; please confirm the time or business object"
    8. error_distribution = aggregate_request_errors(request_records)
    9. correlated_clues = compare_error_periods_with_resource_changes_and_change_events(
    10. error_distribution,
    11. correlated_clues
    12. )
    13. report = organize_evidence_candidate_causes_and_verification_steps(
    14. error_distribution,
    15. correlated_clues
    16. )
    17. validate_evidence_citations_in_report()
    18. return report

    The point of this workflow is not to let the assistant quickly declare a root cause, but to build a verifiable chain of evidence.

    For example, “a configuration change occurred before the errors started” only indicates a temporal correlation—it does not prove the change caused the failure. The assistant still needs to check the affected scope, whether the error behavior matches the expected mechanism, and whether alternative explanations exist.

    The final report should separate confirmed facts, candidate causes, and unverified hypotheses. When evidence is insufficient, the report should say so explicitly rather than filling the gap with a confident tone.

    Knowledge Q&A Must Rest on Traceable Evidence

    Enterprise knowledge often suffers from version conflicts, unclear applicability, and outdated content. Retrieving a relevant passage does not mean it can be used to answer directly.

    Knowledge processing should track, at minimum:

    • Document source, owner, and last update time;
    • Effective time and expiration conditions of the content;
    • Applicable organizations, business types, and user permissions;
    • Priority and conflicts among similar rules.

    When generating answers, provide supporting references where possible, and clearly distinguish explicit rules from the assistant’s own interpretation. If retrieval results conflict, flag the conflict and recommend verification instead of silently merging them into a seemingly complete new rule.

    For high-risk questions—those involving fund operations, permission changes, or critical business approvals—the assistant should provide process guidance and evidence gathering, not replace formal decision-making mechanisms.

    Security Governance Must Cover Input, Execution, and Output

    The risks facing a code-driven assistant come not only from the code itself, but also from what it reads.

    Knowledge documents, log text, or tool responses may contain embedded instructions demanding that rules be ignored, sensitive information be accessed, or additional actions be executed. The assistant should treat such content as data to be analyzed, not as new commands.

    In practice, several independent lines of defense are needed:

    First, permission constraints. All data access and business operations must be validated server-side; the model cannot expand a user’s existing permissions.

    Second, execution constraints. Only approved capabilities may be used; code access scope, runtime resources, and maximum execution time are limited, with support for immediate termination.

    Third, risk classification. Read-only queries can execute automatically after authorization; general write operations require explicit confirmation; high-risk operations such as production changes must go through an approval workflow, with verification and recovery plans prepared in advance.

    Fourth, output inspection. Final responses must avoid leaking sensitive fields, internal credentials, or data the user is not authorized to see, while keeping evidence and conclusions consistent.

    One point deserves special emphasis: read-only operations can still cause data leaks or system load, so they equally require rate limiting, data masking, and query scope control.

    “Being Able to Learn” Does Not Mean Automatically Modifying the Model

    Continuous learning in enterprise scenarios can be achieved through knowledge updates, experience accumulation, and process optimization—it does not have to involve model parameter training.

    An incident handling process that has been manually confirmed can be organized into a case: recording the problem background, key evidence, investigation path, final root cause, and applicable conditions. When similar problems arise later, the assistant can retrieve the case, but it must not mechanically apply its conclusions.

    Before experience enters the knowledge base, it should go through review, data masking, and version management. Wrong answers, coincidentally successful operations, or unverified diagnoses should not become long-term memory.

    Experience should also be allowed to expire and be deleted. When business processes change, old experience may no longer apply; without an update mechanism, so-called “learning” will amplify historical mistakes.

    Evaluate with Task Metrics, Not Just Answer Fluency

    Evaluating an AI assistant should cover task effectiveness, security, and operating cost.

    For knowledge Q&A, check factual accuracy, degree of evidence support, version applicability, and whether the assistant can reasonably decline to answer when evidence is lacking. For diagnostic tasks, check evidence completeness, the ability to distinguish hypotheses, and the actionability of recommendations. For operational tasks, check whether authorization, approval, idempotency, and post-execution verification are in place.

    Test sets should not contain only normal cases. They should also include:

    • Vague user descriptions or missing key conditions;
    • Outdated, conflicting, or inaccessible documents;
    • Tool timeouts, empty responses, or partial failures;
    • Duplicate submissions of the same write request;
    • Inputs containing sensitive information or malicious instructions;
    • Multiple tasks running concurrently and competing for resources.

    After launch, continuously monitor task completion rates, reasons for human takeover, tool failure types, response latency, and resource consumption. Without a real baseline and consistent test conditions, do not claim fixed accuracy rates or efficiency improvement figures.

    Expand Gradually from Low-Risk Scenarios

    The safest deployment path is to start with knowledge Q&A, then read-only diagnosis, and finally controlled operations.

    In the first phase, validate knowledge quality, permission filtering, and evidence citation. In the second phase, integrate operational data so the assistant can produce diagnostic reports, while humans retain decision authority. In the third phase, open automatic execution for operations with clear boundaries that are verifiable and have recovery mechanisms, controlling risk through approval and gradual rollout.

    Starting with a universal assistant covering all business domains is not recommended. Choosing a scenario with clear goals, available data, and verifiable outcomes makes it much easier to build a replicable engineering approach.

    The core value of an enterprise AI assistant lies in connecting “understand the problem—collect evidence—organize action—verify results” into a complete process. Code as action strengthens the ability to express and orchestrate complex tasks, but reliability ultimately depends on permission boundaries, tool design, execution isolation, and governance mechanisms. Only when these foundations mature can an AI assistant grow from a conversational entry point into a trusted business collaboration system.