Connecting Enterprise Business Data to LLM Agents: An Engineering Practice
This article describes a general architecture for connecting enterprise business data to LLM agents in a controlled, auditable, and extensible way. It uses a sales CRM as the example and covers the gateway layer, atomic tool design, permission and field-level controls, cost tracking, write confirmation, retries, and evaluation before launch.
1. Background and Problem Definition
Sales teams depend heavily on data in their customer relationship management (CRM) systems, such as customer profiles, opportunity stages, follow-up records, contract amounts, and contact details. Traditionally, sales reps switched between several systems to filter opportunities that needed follow-up, summarize customer activity, and write follow-up emails. LLM agents let people give instructions in natural language. The model interprets the intent, calls business interfaces, and returns the results.
This approach improves efficiency, but it also raises new engineering problems:
- Data boundaries: The data an agent can see must match the permissions of the current user. A different call path must not bypass the original access controls.
- Operational safety: Read operations carry low risk. Update and delete operations can cause irreversible data changes, so they need separate confirmation and audit mechanisms.
- Context quality: Business data is large and has complex fields. Putting all records directly into the model context increases cost and reduces answer accuracy.
- Cost attribution: Each call consumes model inference resources and business API quota. Usage must be metered by tenant, user, or feature.
- Reliability: The model may misinterpret instructions, repeat calls, or generate incomplete parameters. The system needs validation, idempotency, and rollback capabilities.
This article does not focus on any specific product. It takes a general technical architecture perspective and explains how to design a controllable, auditable, and extensible approach for connecting agents to data.
2. Typical Application Scenarios
In sales assistance, common requirements fall into the following categories.
1. Daily work briefing
When a user asks for a briefing for today, the system aggregates the follow-up tasks due today, opportunities with no recent updates, contracts about to close, and the latest interactions with high-value customers. The agent organizes this structured data into an action list sorted by priority.
2. Filtering opportunities that need follow-up
Filter conditions typically include: time in the current stage exceeds a threshold, the last activity was more than a specified number of days ago, or the expected deal amount is above a certain value. These conditions can be combined in many ways, so users can describe them in natural language, and the agent converts them into structured queries.
3. Risk identification and proposal updates
Based on fields such as interaction frequency, payment history, and competitor activity, the system can estimate whether an opportunity is at risk of being lost. It can then prompt the sales rep to update the proposal or arrange a senior-level visit.
4. Email and document drafts
Based on customer profiles and recent communication, the agent can generate follow-up email drafts. A user must review each draft before it is sent. The system should never send content to external recipients automatically.
5. Dynamic data views
Users can ask the agent to generate charts or tables along custom dimensions, such as the distribution of opportunity amounts by industry. This capability requires the backend to provide controlled aggregation query interfaces. It should not let the model write arbitrary database statements.
These scenarios share one trait: the agent needs to access several types of data at once, and its output must be traceable to the original records. The main architectural challenge is therefore exposing business capabilities to the model reliably while keeping data boundaries clear.
3. Overall Architecture
We recommend dividing the system into five layers. Each layer has a single responsibility, which makes it easier to evolve and audit independently.
| Layer | Responsibility | Key Requirement |
|---|---|---|
| Interaction layer | Receives user instructions, displays results and confirmation screens | Records session IDs and distinguishes read requests from write requests |
| Model layer | Understands intent, plans tool calls, composes responses | Accesses business data only through the tool gateway |
| Tool gateway layer | Handles unified authentication, parameter validation, rate limiting, metering, and logging | Every tool call must pass through this layer |
| Business service layer | Implements domain logic for customers, opportunities, activities, and so on | Reuses existing business rules and does not reimplement them in the gateway |
| Data and governance layer | Stores business data and manages permission policies, masking rules, and audit records | Policies are configured centrally, and changes are traceable |
The core idea of this layering is that the model never accesses the database or low-level interfaces directly. It can only call the controlled tools that the gateway exposes. The gateway answers three questions: who is making the call, what the caller is allowed to do, and how the result is recorded.
4. Packaging Business Capabilities as Atomic Tools
An agent’s basic unit of action is the tool. How well a tool is designed determines whether the model can complete tasks reliably.
4.1 Tool Design Principles
- Single responsibility: Each tool performs one clearly defined operation, such as listing opportunities, retrieving a customer summary, or creating a follow-up task.
- Explicit parameters: Parameter names, types, value ranges, and default values must be clearly defined, with examples provided.
- Structured output: Return structured data such as JSON, and keep record identifiers so the model can cite results and users can trace them.
- Avoid overly broad access: Do not provide generic tools such as “execute an arbitrary query,” because they can bypass permission controls.
- Separate read and write tools: Define read tools and write tools separately, and require confirmation for write tools by default.
4.2 Tool Definition Example
The code below shows the general structure of a tool definition. It illustrates the approach to parameter validation and permission declaration.
from dataclasses import dataclass, fieldfrom typing import Literal, Optionalfrom datetime import date@dataclassclass ListOpportunitiesArgs:stage: Optional[Literal["prospecting", "proposal", "negotiation", "closed_won", "closed_lost"]] = Noneidle_days_min: int = 0idle_days_max: int = 365amount_min: float = 0.0limit: int = 50def validate(self) -> None:if not 0 <= self.idle_days_min <= self.idle_days_max:raise ValueError("Invalid idle_days range")if not 1 <= self.limit <= 200:raise ValueError("limit must be between 1 and 200")if self.amount_min < 0:raise ValueError("amount_min cannot be negative")@dataclassclass ToolSpec:name: strdescription: strkind: Literal["read", "write"]required_scopes: list[str] = field(default_factory=list)LIST_OPPORTUNITIES = ToolSpec(name="list_opportunities",description="Filter opportunities visible to the current user by stage, idle days, and amount",kind="read",required_scopes=["opportunity:read"],)
Three points matter here. First, parameters are validated before they reach business logic, so abnormal values generated by the model never reach a query. Second, the tool declaration states whether the tool reads or writes and which permission scopes it requires. The gateway can use this information to decide automatically whether extra confirmation is needed. Third, the description is read by the model, so it should state the purpose concisely and avoid ambiguity.
4.3 Parameter Validation and Error Responses
Parameters generated by the model are not always reliable. The gateway should return validation failures to the model in a structured form. This lets the model correct the parameters and retry, instead of reporting a generic “system error.” For example:
{"ok": false,"error": {"code": "INVALID_ARGUMENT","field": "limit","message": "limit must be between 1 and 200","retryable": true}}
A consistent error structure helps the model distinguish retryable errors from non-retryable ones. It also makes log aggregation and analysis easier.
5. Permissions and Data Security
Once an agent can access business data, the largest risk is that permissions get amplified. A regular user can only see the customers they manage through the user interface. If the agent uses a service account with global permissions, it could show that user data belonging to others. Permission checks must therefore be based on the identity of the user who originally made the request.
5.1 Identity Propagation
When the agent calls a tool, the gateway should carry the current user’s identity token, and the business service should complete authorization. Service accounts should be used only for system-level tasks, such as scheduled report generation. Their permission scope should be defined separately and must not be reused for interactive requests.
5.2 Row-Level and Field-Level Controls
Even when a user has read permission on an object, they may not be allowed to see certain sensitive fields, such as contract amounts, contact phone numbers, or internal ratings. Before returning results, the gateway should filter and mask fields. Common approaches include:
- Showing only part of a phone number or email address;
- Hiding internal scoring fields from non-management roles;
- Filtering records by owning team or region.
The following code shows field filtering applied before results are returned:
SENSITIVE_FIELDS_BY_ROLE = {"sales_rep": {"internal_score", "contract_cost"},"sales_manager": set(),}def filter_record(record: dict, role: str) -> dict:hidden = SENSITIVE_FIELDS_BY_ROLE.get(role, set())return {k: v for k, v in record.items() if k not in hidden}
In a production system, field policies should come from centralized configuration rather than being scattered across individual tool implementations. Centralized configuration makes auditing and changes easier.
5.3 Credential and Key Management
Model service keys, business API tokens, and database connection details are sensitive credentials. Store them in a dedicated key management service or in environment variables, and rotate them on a regular schedule. Logs must never contain complete tokens, and debugging output should mask them.
5.4 Audit Logs
Every tool call should record the following: call time, user ID, session ID, tool name, masked parameters, number of returned records, duration, and final status. Store audit logs separately, with stricter access controls than the business data. Audit logs should not contain complete sensitive customer information. Record only record identifiers where possible.
6. Context Management and Cost Control
Sales data often includes a large volume of historical records. Putting hundreds of opportunity and activity records into the model context not only raises inference costs, but also makes it easier for the model to miss key information.
6.1 Layered Retrieval
We recommend a “summarize first, then detail” strategy. In the first step, call summary tools to get the number of opportunities and the amount distribution by stage. In the second step, based on the scope the user cares about, call detail tools to retrieve specific records. This keeps the context limited to what is relevant to the question.
6.2 Structured Summaries
For customers with long-running engagements, the system can generate structured summaries on a regular basis. A summary might include the type, date, and outcome of the last three interactions, along with the next steps. Summaries must follow the same permission rules as the original data. Summary updates can run as asynchronous tasks so they do not block the user request path.
6.3 Caching Strategy
For data that changes infrequently, such as basic customer information and organizational structure, use longer cache times. For data that requires real-time accuracy, such as opportunity stages and the time of the latest activity, use shorter cache times and actively invalidate the cache after writes. Cache keys must include the user’s permission dimension. Otherwise, the cache can cause unauthorized reads.
6.4 Metering and Cost Allocation
Call costs typically include the input and output tokens for model inference, the number of business API requests, and the compute resources used for data queries. We recommend recording usage at the gateway layer by tenant, user, and feature module. Usage can then be summarized regularly into billing or internal cost reports. Metering data should be linked to audit logs so that abnormal consumption can be checked.
7. Reliability and Risk Control
The failure modes of agent systems differ from those of traditional interfaces. The model may misunderstand user intent, or it may repeat the same operation across multiple dialogue turns. The design should treat these cases as normal.
7.1 Confirmation for Write Operations
Before executing any write tool, generate an operation preview. For example: “Update the stage of opportunity A from proposal to negotiation, and add one follow-up record.” The write is submitted only after the user explicitly confirms. The confirmation should include the target object, the proposed changes, and the operator. The confirmation record must also be audited.
7.2 Idempotency and Retries
Network timeouts can cause the same request to be submitted more than once. Write APIs should support idempotency keys, so that repeated requests with the same key run only once. Read APIs can be retried safely, but they should have a maximum retry count and backoff intervals to avoid amplifying failures.
7.3 Timeouts and Degradation
Set timeouts for both model calls and business API calls. When a tool is unavailable, the agent should clearly tell the user which information is missing, instead of drawing conclusions from incomplete data. For briefing tasks, the agent can return the parts it successfully retrieved and mark the missing items.
7.4 Traceable Results
Numbers, conclusions, and recommendations from the agent should include the identifiers of their source records where possible. Users can then open the original record and avoid misreading the output. This design also makes it easier for people to review model output.
8. Testing and Evaluation
Before launch, build a dedicated evaluation set that covers common queries, edge cases, and attempts to access data without permission. The evaluation can cover the following areas:
- Tool selection accuracy: For a given user instruction, does the model call the correct tool?
- Parameter accuracy: Do the generated parameters meet value ranges and match the business meaning?
- Permission denial rate: When a user has no access to certain data, does the system deny the request and give a reasonable message?
- Result consistency: Do the numbers in the agent’s answers match the data returned by the business system?
- Write confirmation rate: Does every write request go through user confirmation?
Update the evaluation set regularly and include it in regression testing. Whenever the model version, prompt template, or tool description changes, run the evaluation again.
Feature rollout can be gradual. Start by opening read-only capabilities to a small group of internal users. Observe audit logs and user feedback, and confirm that the permission policies and cost model are stable. Then open write capabilities step by step.
9. Implementation Recommendations
- Define data boundaries first: Identify which objects, fields, and operations are suitable for agent access, and document them in a permission list.
- Start with read-only, then add writes: Read capabilities carry lower risk, so they are a good first-phase goal.
- Keep the tool set small and focused: A large number of tools increases the chance of the model choosing the wrong one. Design tools around core business scenarios.
- Reuse existing business rules: Validation logic, state transitions, and approval workflows should be implemented in the business services. The gateway should handle only orchestration and governance.
- Build a feedback loop: Collect user ratings of responses, add typical errors to the evaluation set, and keep improving tool descriptions and prompt templates.
10. Summary
Connecting LLM agents to enterprise business data essentially means turning natural language interaction into controlled system calls. Success depends less on the model itself than on whether permissions carry through, whether tools are packaged well, whether write operations can be confirmed, and whether cost and behavior can be traced.
Following the layered approach in this article, a team can first build a unified tool gateway and then gradually expand query, summary, and write capabilities. Each step should rely on audit logs and evaluation results. This approach captures the efficiency gains from agents while controlling data security and operational risk.
