Production-тағы AI-агент үлкен context window ішіндегі prompt қана емес. Бұл модель әрекетті таңдап, оның нәтижесін бақылап, шектелген нәтижеге жеткенше немесе адамнан көмек сұрағанша жұмысын жалғастыратын сервис. Модель осы сервистің бір компоненті ғана. Control plane модельдің нені көретінін, қандай tools шақыра алатынын, қай әрекеттер approval талап ететінін, state қайта іске қосылғаннан кейін қалай сақталатынын және жаңа нұсқаны шығаруға қандай дәлел керек екенін шешеді.
Бұл мақала аз ғана құралы бар бір агентке арналған reference architecture ұсынады. Сол шекаралар қадамдары алдын ала белгіленген workflow-ға да, кейінгі multi-agent жүйеге де жарайды. Тапсырманы орындай алатын ең кіші loop-тен бастаңыз. Anthropic-тің тиімді агенттер туралы нұсқаулығы алдын ала болжанатын workflow пен модель құралдарды динамикалық басқаратын жүйені де ажыратады. Autonomy өнімдік шешім, архитектураның default параметрі емес.
Reference architecture
Request path, шешім қабылдау loop-ін және сыртқы әлемді өзгертетін effects-ті бөлек ұстаңыз. Gateway caller-ді authentication арқылы тексеріп, request ID және trace ID жасап, quota қолданады, sensitive fields-ті жояды немесе таңбалайды. Orchestrator loop-ке иелік етеді. Model adapter neutral state-ті provider request-ке, ал provider response-ті шағын decision type-қа айналдырады. Tool gateway arguments-ті тексеріп, actor principal-ды authorization арқылы растап, policy қолданып, isolated connector шақырады. State пен event storage процесс сыртында болуы керек, сонда worker crash-тен кейін жалғастыра алады.
[Пайдаланушы немесе API client]
|
[Gateway: identity, limits, request ID]
|
[Orchestrator: policy -> model -> tool loop]
/ | \
[State store] [Approval service] [Tool gateway]
| | |
[Memory/RAG] [Адам шешімі] [API, файлдар, кезектер]
|
[Events және traces]
Модельге raw credentials, шектелмеген network access немесе database-ке тікелей write бермеңіз. Tool gateway "search_orders", "draft_refund", "send_message" сияқты тар операцияларды ұсынуы керек, generic HTTP client немесе SQL console емес. Әр операцияда owner, input schema, permission, risk class, timeout және нәтижесінің құжатталған форматы болуы тиіс.
Request envelope-ті анық түрде қолданыңыз:
| Field | Мақсаты |
|---|---|
| tenantId және actorId | Әрбір read пен effect-ті authenticated principal-ға байлау. |
| requestId және traceId | Retries, approvals, tool calls және logs-ты байланыстыру. |
| goal | User goal-ды model messages-тен бөлек сақтау. |
| policyVersion және modelVersion | Run-ды тексеруге жеткілікті түрде reproducible ету. |
| deadline және stepBudget | Уақыт пен model-tool turns санын шектеу. |
NIST AI RMF Generative AI Profile lifecycle бойындағы risk жұмысын реттеуге көмектеседі. Оның сұрақтарын envelope пен tool gateway ішіндегі нақты controls-қа аударыңыз. Framework-тің өзі нақты deployment қауіпсіз екенін дәлелдемейді.
Tool loop
Loop-тің бір owner-і болсын және әр turn үшін state transition көрінсін:
- Run, policy, conversation summary және рұқсат етілген tool catalog-ті жүктеңіз.
- Bounded model input жасаңыз. User text, retrieved text, tool output және system instructions-ті бөлек trust classes ретінде белгілеңіз.
- Model-ден final response немесе typed tool call сұраңыз. Execution алдында қате name пен arguments-ті қабылдамаңыз.
- Authorization мен risk policy-ді model-ден тыс шешіңіз. Model-дің әрекет қауіпсіз деген сөзі authorization шешімі емес.
- Action approval gate-тен өтсе, pending action-ды сақтап, тоқтаңыз. Explicit decision келгенде saved action-нан жалғастырыңыз.
- Connector-ді deadline және idempotency key арқылы орындаңыз. Redacted result-ті жазып, state-ке қосыңыз.
- Step, token, cost және wall-clock budgets-ті тексеріңіз. Policy тағы бір turn-ге рұқсат етсе ғана жалғастырыңыз.
- Не болғанын, не болмағанын және қандай approval не uncertainty қалғанын түсіндіретін жауап қайтарыңыз.
Model call-ды шексіз "while" loop-ке салмаңыз. Step budget prompt немесе tool бір сұрауды қымбат chain-ге айналдырмауына көмектеседі. Deadline caller мен worker pool-ды қорғайды. Repeated-call detector model-дің бір failure action-ды қайта-қайта сұрағанын байқайды. Circuit breaker degraded connector-ді уақытша өшіріп, read-only tools-ті қалдыра алады.
Model Context Protocol specification resources, prompts және tools-ті стандарттайды, бірақ host application-ның consent, authorization немесе isolation controls-ын алмастырмайды. MCP server-ді external dependency ретінде қабылдаңыз. Оның identity-сін бекітіп, жариялаған tools-ін тексеріп, жіберілетін data-ны шектеп, ішкі connector-ге қолданатын gateway policy-ді қолданыңыз.
State, memory және context
State бір run-ның durable record-ы. User goal, messages немесе олардың references-ін, tool calls пен results-ті, approvals-ты, policy decisions-ті, model және tool versions-ті, timestamps, status және error classification-ды сақтаңыз. Алдымен events-ті append етіп, кейін current run view жасаңыз. Бұл recovery мен audit-ті бір opaque JSON blob-ты mutate етуден жеңілдетеді. Sensitive fields-ті encrypt етіп, tenants-ті оқшаулаңыз, retention орнатыңыз және deletion snapshots, indexes, traces пен caches-ке де әсер етсін.
Conversation history memory-мен бірдей емес. Current run үшін қысқа мерзімді working context сақтаңыз. User немесе business memory-де purpose, retention rule, source және user не administrator түзете алатын жолы болғанда ғана сақтаңыз. Facts provenance және confidence немесе freshness field-пен бірге жазылсын. Model guess-ін шын сияқты естілгені үшін durable memory-ге қоспаңыз.
Retrieval trust boundary-і бар tool. Ranking алдында tenant және authorization filters қолданыңыз. Source identifiers пен timestamps-ті context-ке алып келіңіз. Model-ге retrieved text data екенін, instruction емес екенін айтыңыз. Chunks санын шектеп, қажетсіз secrets-ті алып тастап, query мен document identifiers-ті private content-сыз әдепкіде логтаңыз. PostgreSQL-де lexical және vector candidates-ті салыстырып, rerank-ті тек authorization-нан кейін жасаңыз. Ішкі pgvector hybrid RAG нұсқаулығы осы шекараны нақтылайды.
Context compaction debug жасауға жеткілікті deterministic болсын. Ескі turns-ті decisions, unresolved questions, tool effects, citations және user constraints сақталатын fixed schema арқылы summary жасаңыз. Original event log prompt-тан тыс қалсын. Summary pending action мағынасын өзгертсе, үнсіз жалғастырмай тоқтап, review сұраңыз.
Tools және threat boundaries
Tool schema, model metadata ғана емес, security contract. Gateway types, lengths, enum values, resource ownership және fields арасындағы relationships-ті тексерсін. Authorization-нан кейін names-ті internal identifiers-ке аударыңыз. Read және write tools-ті бөліңіз. Connector-лерге бір tenant пен бір operation-ға scope жасалған қысқа мерзімді credentials беріңіз. Қауіпті code немесе file work-ті filesystem және network allowlist-і бар isolated worker-де орындаңыз.
External content-тің бәрін potentially hostile деп санаңыз. Email, web page, issue, document, tool description немесе MCP resource indirect prompt injection қамтуы мүмкін. Оны model input ішінде анық бөліп көрсетіңіз, керек болса executable markup-ты алып тастаңыз, permissions-ті application шешсін. Output validation model-ден тәуелсіз болсын. Мысалы, payment connector-ге refund жібермес бұрын amount, currency, actor permission және policy maximum-ды order бойынша тексеріңіз.
Threat model мыналарды қамтуы керек:
| Boundary | Алдын алатын failure |
|---|---|
| User → gateway | Account takeover, oversized requests және басқа tenant identifier-лері. |
| Model → tool gateway | Argument injection, privilege confusion және excessive agency. |
| Retrieval немесе MCP → model | Indirect prompt injection және data ішіндегі malicious instructions. |
| Connector → external service | Credential leakage, SSRF, replay және data exfiltration. |
| Worker → state store | Tampered events, stale policy және толық емес audit history. |
OWASP GenAI LLM Top 10 prompt injection, excessive agency, insecure output handling және unbounded consumption-ды application-level mitigation қажет ететін risk деп сипаттайды. Dayfing-тің prompt injection және MCP security нұсқаулығы threat-focused checklist береді. System prompt guidance ретінде пайдалы, бірақ sandbox, authorization layer немесе secret store емес.
Approval gates және human control
Approvals-ты harmless reasoning-ге емес, effects-ке қойыңыз. User-дің өз calendar-ын оқу автоматты болуы мүмкін. External message жіберу, record өзгерту, money шығару, data өшіру немесе code deploy ету actor, target, amount, reversibility және confidence негізіндегі policy decision-ді қажет етеді. Gate application code ішінде болсын, сонда prompt оны айналып өте алмайды.
Proposed tool, normalized arguments, affected resources, reason, policy version, expiration және relevant state hash бар approval request-ті persist етіңіз. Reviewer дәл сол data-ны көрсін. Оның decision-ін action hash және actor-ға байланыстырыңыз. Approval-дан кейін execution алдында authorization, freshness және budget-ті қайта тексеріңіз. Rejection немесе expiry болса, decision-ді жазып, model-ге action болмағанын айтыңыз. Old approval өзгерген payload-ты authorise етпеуі керек.
Human-in-the-loop режимдері:
| Режим | Қолайлы қолдану |
|---|---|
| Observe | Low-risk actions-ты жазу не sampling жасап, agent-ті automatic қалдыру. |
| Confirm | Irreversible effect алдында бірден approval сұрау. |
| Review | Адамға толық draft пен selected evidence-ті тексерту. |
| Take over | Run-ды current state және lock-пен operator-ға беру. |
Pause-ты exception емес, қалыпты state ретінде жобалаңыз. Queue pending approvals-ты жеткізе алады, notification expire болуы мүмкін, worker басқа host-та run-ды жалғастыра алады. User agent-тің ойлап тұрғанын, data күтіп тұрғанын, approval күтіп тұрғанын, retry жасап жатқанын немесе біткенін көрсін.
Retries, idempotency және recovery
Retry жасамай тұрып error-ды жіктеңіз. Validation error түзетілген call немесе user question қажет етеді. Authentication және authorization errors тоқтатуы тиіс. Rate limits provider-дің retry signal-ын құрметтесін. Timeout пен connection reset write үшін ambiguous, себебі remote service effect-ті қолданған болуы мүмкін. Semantics немесе idempotency key қайталауды қауіпсіз ететін operation-ды ғана retry жасаңыз. [RFC 9110 section 9.2.2](https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2 non-idempotent method-тарды effect қауіпсіз екенін анықтайтын амалсыз автоматты retry жасауға болмайтынын түсіндіреді.
Stable key-ді run және logical action-нан жасаңыз, attempt number-дан емес. Connector retry window бойы key мен final result-ті сақтасын. Сол key басқа arguments-пен келсе, reject етіңіз. Jitter қосылған exponential backoff және шағын maximum attempts қолданыңыз. Retry, жаңа model decision емес. Original call, attempt number, response class және connector request identifier-ді persist етіңіз.
Recovery, state machine міндеті. "running", "waiting_for_approval", "retrying", "failed", "completed" және "cancelled" statuses-ін қолданыңыз. Lease екі worker-дің бір run-ды қатар орындауына жол бермейді. Lease жоғалса, келесі effect алдында тоқтаңыз. Worker crash болғаннан кейін reconciler pending actions-ты connector records-пен салыстыра алады. Provider қолдаса, cancellation model requests, tool calls, queues және approval requests-ке таралсын.
Observability
Әр user request үшін бір trace, ал model calls, retrieval, policy checks, approvals және tools үшін spans жасаңыз. Duration, status, retry count, қолжетімді болса input және output token counts, model және prompt versions, tool name, risk class және cost estimate-ті жазыңыз. Export алдында secrets пен sensitive content-ті redact етіңіз. Approval немесе support ticket-ті trace-пен байланыстыру үшін stable run ID қолданыңыз, personal data-ны baggage-ке қоспаңыз. OpenTelemetry context propagation services арасындағы trace context байланысын және untrusted headers пен sensitive baggage қаупін түсіндіреді.
Task completion-ды анық rubric бойынша, successful tool-call rate, validation failures, approval rate, retry және timeout rate, p50 және p95 latency, completed task үшін token пен tool cost, cancellation rate және policy blocks арқылы өлшеңіз. Model version, tool, tenant class және release бойынша бөлшектеңіз. Low error count silent wrong answers-ты жасыруы мүмкін, сондықтан traces-ті sampled transcripts және evaluator results-пен байланыстырыңыз. Chain-of-thought-ты логтамаңыз. Policy рұқсат ететін қысқа decision metadata және user-visible reasoning не citations ғана сақтаңыз.
Ішкі AI-агент observability нұсқаулығы logs-ты secrets-тің екінші базасына айналдырмай signals-ті қолдануды көрсетеді.
Evals: release алдында және кейін
Agent eval, starting state, allowed tools, expected invariants және scoring rule анықталған scenario. Final answer жеткіліксіз. Agent authorized tool қолданғанын, tenant scope-ты сақтағанын, қажет кезде approval сұрағанын, write-ты қайталамағанын, дұрыс source-қа сілтеме жасағанын және budget-те тоқтағанын тексеріңіз. Adversarial scenarios қосыңыз: malicious retrieved text, unavailable connector, write-тен кейін timeout, stale approval, ambiguous request және malformed tool data.
Layered suite қолданыңыз:
- Schemas, authorization, redaction, idempotency, state transitions және budget enforcement үшін deterministic unit tests.
- Recovery тексеруге recorded tool responses және fixed model decisions бар replay tests.
- Task outcome, safety және communication rubric-і бар model scenario tests.
- Direct және indirect injection, data leakage, excessive agency және denial of service үшін red-team tests.
- Privacy controls және human review бар production sampling, failures-ті regression cases-ке айналдыратын жол.
Scenario, tools, policy, prompts, model және evaluator-ді version жасаңыз. Failures-ті trace және ең кіші reproducing input-пен сақтаңыз. Candidate release-ті baseline-пен салыстырып, average quality өссе де hard safety invariants regression-ына жол бермеңіз. Anthropic-тің agent evals нұсқаулығы multi-turn tool use trajectory-level evaluation қажет ететінін түсіндіреді. Ішкі AI-агент evals нұсқаулығы практикалық test matrix береді.
Cost және latency таңдау
Әр model turn, retrieved token, tool call, approval pause және retry time немесе money қосады. Бір global number орнына task class бойынша budgets қойыңыз. Өлшенген accuracy жеткілікті болса, routing, extraction және policy prechecks үшін кішкентай model қолданыңыз. Күшті model-ді ambiguous planning немесе final synthesis-ке қалдырыңыз. Stable tool catalogs және retrieval embeddings-ті cache етіңіз. Context үлкеймей тұрғанда summary жасаңыз, бірақ summary extra turns немесе lost facts тудыратынын өлшеңіз.
Independent read-only calls-ты parallel орындап, нәтижені explicit provenance-пен біріктіріңіз. Connector transaction немесе жобаланған compensation бермесе, writes sequential болсын. Secrets көрсетпей progress-ті stream етіңіз. Long work-ті job ретінде persist етіп, HTTP request аяқталғаннан кейін worker жалғастырсын. Faster model қателері human review, compensating writes немесе repeated runs тудырса, ол cheaper емес. Correct және policy-compliant outcome үшін total cost-ті өлшеңіз.
Минималды runnable loop
Келесі protocol-independent TypeScript example fake model және local tools қолданады, сондықтан provider SDK мен network access қажет емес. Ол typed decision loop, write approval, bounded retries, stable idempotency key және duplicate effect guard көрсетеді. Policy және tool boundary-ді сақтай отырып, model орнына real adapter қоюға болады.
type ToolCall = { id: string; name: string; input: unknown };
type Message =
| { role: "user"; content: string }
| { role: "assistant"; content: string; toolCall?: ToolCall }
| { role: "tool"; callId: string; content: string };
type Decision =
| { kind: "answer"; text: string }
| { kind: "call"; call: ToolCall };
type Tool = {
sideEffect: "read" | "write";
run(input: unknown, idempotencyKey: string): Promise<string>;
};
const issued = new Set<string>();
const tools: Record<string, Tool> = {
getBalance: {
sideEffect: "read",
async run(): Promise<string> {
return JSON.stringify({ account: "demo", cents: 4200 });
},
},
sendInvoice: {
sideEffect: "write",
async run(input: unknown, idempotencyKey: string): Promise<string> {
if (issued.has(idempotencyKey)) return "already-sent";
if (typeof input !== "object" || input === null) throw new Error("invalid input");
issued.add(idempotencyKey);
return "invoice-sent";
},
},
};
const model = {
async decide(messages: readonly Message[]): Promise<Decision> {
const toolCount = messages.filter((message) => message.role === "tool").length;
if (toolCount === 0) {
return { kind: "call", call: { id: "balance-1", name: "getBalance", input: {} } };
}
if (toolCount === 1) {
return { kind: "call", call: { id: "invoice-1", name: "sendInvoice", input: { cents: 1200 } } };
}
return { kind: "answer", text: "The balance was checked and the invoice was sent." };
},
};
const wait = (milliseconds: number) => new Promise((resolve) => setTimeout(resolve, milliseconds));
async function execute(call: ToolCall, tool: Tool, key: string): Promise<string> {
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return await tool.run(call.input, key);
} catch (error) {
if (attempt === 2) throw error;
await wait(10 * 2 ** attempt);
}
}
throw new Error("unreachable");
}
async function run(): Promise<string> {
const state: { messages: Message[]; completed: Set<string> } = {
messages: [{ role: "user", content: "Check the balance and send the invoice." }],
completed: new Set<string>(),
};
const sessionId = "session-demo";
for (let step = 0; step < 6; step += 1) {
const decision = await model.decide(state.messages);
if (decision.kind === "answer") return decision.text;
const tool = tools[decision.call.name];
if (!tool) throw new Error("unknown tool");
const key = sessionId + ":" + decision.call.id;
if (tool.sideEffect === "write" && !process.argv.includes("--approve")) {
return "Paused for approval: " + decision.call.name;
}
if (state.completed.has(key)) continue;
const result = await execute(decision.call, tool, key);
state.completed.add(key);
state.messages.push(
{ role: "assistant", content: "", toolCall: decision.call },
{ role: "tool", callId: decision.call.id, content: result },
);
}
throw new Error("step budget exceeded");
}
run().then(console.log).catch((error: unknown) => {
console.error(error);
process.exitCode = 1;
});
Оны project TypeScript toolchain арқылы compile етіп, emitted JavaScript-ті flag-сыз іске қосыңыз: approval pause көрінеді. Кейін --approve арқылы write-қа рұқсат беріңіз. Мысал state-ті әдейі memory-де ұстайды. Production state durable, tenant-scoped, қажет болса encrypted болып, lease-aware worker арқылы қалпына келуі керек.
Құру реті
Model таңдаудан бұрын task outcome мен forbidden effects-ті анықтаңыз. Schemas және authorization артында бір read tool мен бір reversible write tool жасаңыз. Қосымша tool қоспай тұрып durable events, budgets, approval states және idempotency енгізіңіз. Бірінші end-to-end trace-ті ерте instrument етіңіз. Real failure modes-тан eval scenarios жасап, әр prompt, policy, tool немесе model өзгерісінде іске қосыңыз. MCP немесе multi-agent delegation-ды өлшенген requirement жаңа trust boundary-ді ақтағанда ғана қосыңыз.
Қатысты оқу
- Prompt injection және MCP security
- AI-агент evals
- AI-агент observability
- pgvector бар hybrid RAG
- Anthropic: Building effective agents
- Anthropic: Demystifying evals for AI agents
- Model Context Protocol specification
- NIST AI RMF Generative AI Profile
- OWASP GenAI LLM Top 10
- OpenTelemetry context propagation
- RFC 9110 HTTP Semantics