跪拜 Guibai
← Back to the summary

Stop Patching Agent Prompts: Route by Intent or You'll Break Working Features

An Agent that has been in production for a few weeks tends to have its Prompt grow longer and longer. Every time a problem appears, the team adds a "must" or a "never" sentence. The problem in front of you gets solved, but another feature that used to work correctly may start failing.

A very typical example:

User asks: "What does log query support?"
The user only wants to know what features log query supports, but the Agent treats it as an execution request and directly triggers a production log query.

Fixing this mis-call is not hard; what is hard is avoiding over-fixing: if you only append a sentence at the end of the Prompt like "don't query", then when the user really asks to query logs, the Agent may also be blocked by that rule.

Fixing the problem in front of you without affecting features that already work correctly is the hardest thing to manage after a Prompt has grown too long.

The whole article only solves one problem:

When a Prompt grows too long, how do you fix the current problem without affecting features that were previously correct?

Why patching the Prompt breaks old features

Both sentences mention logs, but one asks about the feature and the other really wants to query. In this case, feature explanations are based on the knowledge base documentation, so the Agent has two relevant tools: search_docs to look up docs, and query_logs to query real logs.

User: What does log query support?
Correct behavior: call search_docs, explain the feature based on docs

User: Query the error logs of the order service in production for the last ten minutes
Correct behavior: call query_logs, return real logs

The first sentence is about understanding capabilities, the second is about executing a query. The difference is not whether "log" appears in the sentence, but whether the request should go to the documentation tool or the real-time query tool.

More patches make old features worse

Initially the Prompt rule was one sentence:

When the user mentions log query, judge it as a real-time query.

Under this rule, the first example "What does log query support?" would also be judged as a real-time query. As a result, the Agent did not explain the feature and directly called query_logs, querying production logs.

To fix this, the engineer started appending patches:

When the user mentions log query, judge it as a real-time query.
If the user asks what log query supports, do not call the tool.
If the user is learning about log capabilities or asking whether they can query, forbid calling the tool.
If the user explicitly gives a service name and log type, must call the tool.

Each of these four sentences looks correct by itself. But the first sentence is the root cause: it judges based on "mentions logs" rather than on "what task the user wants to accomplish and what data source they need." The other three sentences are patching a wrong principle. When combined, there is no unified specification, so tool routing is naturally unstable.

Later you will see behavior like this:

Can I look at logs?
→ sometimes it still calls the tool

Help me check the error logs of the order service.
→ sometimes it does not call the tool

The root cause is not that the Prompt is too long, but that the first judgment principle is wrong, and the other three sentences are patching that wrong principle. The more conflicting instructions, the more likely tool routing will be unstable and regress.

The real danger: after changing, you cannot verify or roll back

Code usually already has types, unit tests, and release rollback. If the Prompt is only edited in the console, is not in the repository, and is not recorded together with the model and tool configuration, three things are usually missing:

1. You don't know which old rule was changed.
2. You don't know whether old features have regressed.
3. After a problem occurs, you cannot determine which version of the Prompt and configuration was actually in production at that time.

Some Prompt platforms have built-in version history, but text history alone is not enough. Only by correlating the Prompt version, model version, tool definitions, and release records can you reproduce the behavior at that time.

So once a Prompt change affects production behavior, it can no longer be treated as "just editing the copy." It is closer to a behavior release.

Fix the rule first, then decide where to change

Replace conflicting rules, don't keep appending

First preserve the incident scene:

Input: What does log query support?
Judgment: real-time query
Action: call query_logs
Result: query request sent to the production log system

The problem is in the first step, the judgment. So instead of appending exceptions, replace the whole section.

Before (the wrong example):

// src/prompts/agent-prompt.ts
export const AGENT_PROMPT = `
When the user mentions log query, judge it as a real-time query.
If the user asks what log query supports, do not call the tool.
If the user is learning about log capabilities or asking whether they can query, forbid calling the tool.
If the user explicitly gives a service name and log type, must call the tool.
`;

These four rules are exactly the result of patching: the first rule judges by keyword, and the next three use "don't," "forbid," and "must" to add exceptions. Each looks reasonable in isolation, but together they lack a unified judgment standard.

After (src/prompts/agent-prompt.ts):

// The main Prompt only handles routing, does not repeat tool parameter definitions
export const AGENT_PROMPT = `
You are an operations assistant. Based on the task the user wants to accomplish and the data source needed, choose the next step:

1. User asks about features, concepts, or usage, needs documentation information → search_docs
2. User explicitly asks to view logs from a real environment, and information is complete → query_logs
3. User wants to view real logs but is missing service, environment, or time range → ask first

Examples:
- "What does log query support?" → search_docs
- "Can I look at logs?" → search_docs
- "Query the error logs of the order service in production for the last ten minutes" → query_logs
- "Check its error logs" (cannot determine who "it" is) → ask first
`;

After this change, the two types of requests will be routed to different tools:

User: What does log query support?
→ search_docs

User: Query the error logs of the order service in production for the last ten minutes
→ query_logs

If you still write "when log query is mentioned, query," explanation-type requests will be sent to query_logs. If you only add a "don't query logs" sentence, real queries may be blocked as well.

How to divide responsibilities between the main Prompt and tool descriptions

Wrong approach: stuffing everything into the main Prompt:

// src/prompts/agent-prompt.ts
// Wrong: judgment, tool details, and field constraints are all piled together
export const AGENT_PROMPT = `
You are an operations assistant.

When the user mentions log query, judge it as a real-time query.
If the user asks what log query supports, do not call the tool.
If the user is learning about log capabilities, forbid calling the tool.
If the user explicitly gives a service name and log type, must call the tool.
query_logs is used to query production logs.
environment can only be prod or test.
`;

The correct approach is to separate by responsibility:

The code below is written against @langchain/core 1.1.x, @langchain/langgraph 1.2.x, and Zod 3. The main Prompt is already changed; here I only add the two Tools and Agent assembly. docsRetriever and logClient represent business-layer data clients and are not part of LangChain.

src/tools/search-docs.ts

import { DynamicStructuredTool } from '@langchain/core/tools';
import { z } from 'zod';
import { docsRetriever } from '../data/docs-retriever';

// Documentation tool: answers explanation-type questions such as "what supports" and "how to use"
export const searchDocsToolConfig = {
  name: 'search_docs' as const,
  description: `
Queries system documentation, integration guides, FAQs, and technical manuals.
Suitable for questions like "what supports", "how to use", "how to configure" that need documentation information.
`,
  schema: z.object({
    // Parameter constraints are maintained in the schema, no longer duplicated in the main Prompt
    query: z.string().describe('The question the user wants to understand from the docs'),
    topK: z.number().optional().describe('Number of results to return, default 1'),
  }),
  func: async ({ query, topK }: { query: string; topK?: number }) => {
    // The tool only connects to the document retrieval service
    return docsRetriever.search(query, { topK: topK ?? 1 });
  },
};

export const searchDocsTool = new DynamicStructuredTool(
  // Avoid deep TypeScript generic instantiation with complex Zod schemas;
  // if your project doesn't have this compilation issue, you can omit as any
  searchDocsToolConfig as any,
);

src/tools/query-logs.ts

import { DynamicStructuredTool } from '@langchain/core/tools';
import { z } from 'zod';
import { logClient } from '../data/log-client';

// Log tool: only handles explicit requests to query real logs
export const queryLogsToolConfig = {
  name: 'query_logs' as const,
  description: `
Queries logs of a service in a real environment.
Usage condition: the user explicitly asks to view real logs and provides service, environment, and time range.
`,
  schema: z.object({
    // When required fields are missing, the Agent should ask first instead of guessing parameters
    service: z.string().describe('Service name, e.g. order-service'),
    environment: z.enum(['prod', 'test']).describe('Runtime environment'),
    timeRange: z.string().describe('Time range, e.g. last_10m'),
    level: z.enum(['error', 'warn', 'info']).optional().describe('Optional log level'),
    query: z.string().optional().describe('Optional log filter condition'),
  }),
  func: async ({
    service,
    environment,
    timeRange,
    level,
    query,
  }: {
    service: string;
    environment: 'prod' | 'test';
    timeRange: string;
    level?: 'error' | 'warn' | 'info';
    query?: string;
  }) => {
    // Still validate user permissions, environment permissions, and query range server-side before actually executing
    return logClient.query({
      service,
      environment,
      timeRange,
      level,
      query,
    });
  },
};

export const queryLogsTool = new DynamicStructuredTool(
  // Same as above: decide whether to add as any based on your project's compilation
  queryLogsToolConfig as any,
);

src/agent.ts

import type { BaseMessage } from '@langchain/core/messages';
import { AGENT_PROMPT } from './prompts/agent-prompt';
import { createModel } from './model';
import { queryLogsTool } from './tools/query-logs';
import { searchDocsTool } from './tools/search-docs';

export async function runAgent(messages: BaseMessage[]) {
  // Dynamic import here makes the example easier to run in mixed ESM/CJS environments;
  // in a real project, import directly according to build config
  const { createReactAgent } = await import('@langchain/langgraph/prebuilt');
  const llm = createModel();
  const tools = [searchDocsTool, queryLogsTool];
  const agent = createReactAgent({ llm, tools, prompt: AGENT_PROMPT });

  // values mode returns a stream containing the full message state
  return agent.stream(
    { messages },
    { streamMode: 'values' as const },
  );
}

It is impossible for the main Prompt and tool descriptions to have zero overlap:

Security boundaries must also be stated clearly: the Prompt is only responsible for judgment and routing; it cannot replace production permission control. The execution code of query_logs must still perform user authentication, environment authorization, query range limits, timeouts, auditing, and result masking. Even if the model mistakenly triggers a call, an unauthorized request should never actually reach production logs.

When troubleshooting, locate by actual result:

Explanation-type request selected query_logs → compare the main Prompt and the two tool descriptions
Tool selected correctly but parameters wrong → check schema and parameter descriptions
Tool exceeding access to production environment → check authentication and environment permissions in the execution code

After the change, how to prove old features still work

A corrected Prompt does not mean production is safe. The real danger is not that this fix failed, but that after the fix, requests that previously could query logs also break, and nobody notices at the time.

Lock down these four categories of results before going live

This change refactors "query when log query is mentioned" into routing by intent and data source. The most likely damage is exactly the real queries that previously worked. So don't only test the just-fixed sentence. At a minimum, lock down these four categories of results:

Input Before After must reach
What does log query support? mistakenly calls query_logs calls search_docs
Query the error logs of the order service in production for the last ten minutes calls query_logs calls query_logs
What logs can you query? No need to actually query mistakenly calls query_logs calls search_docs
Check its error logs from a moment ago mistakenly calls query_logs ask first

The judgment standard is one sentence: The thing you want to fix must get better; the thing that was correct before must not get worse.

Turn the comparison table into executable regression

First write the inputs, expected tools, and key parameters as test cases. Don't just record "whether a tool was called"; also check the tool name and key parameters:

export const cases = [
  // This fix's goal: explanation-type questions must go to the docs tool
  {
    name: 'When asking about functionality, use the docs tool',
    input: 'What does log query support?',
    expectedTool: 'search_docs',
    expectedArgs: { query: 'What does log query support?' },
  },
  // Protect old feature: explicit query requests must still go to the log tool
  {
    name: 'When explicitly querying logs, call the log tool',
    input: 'Query the error logs of the order service in production for the last ten minutes',
    expectedTool: 'query_logs',
    expectedArgs: {
      service: 'order-service',
      environment: 'prod',
      timeRange: 'last_10m',
      level: 'error',
    },
  },
  // Add similar phrasings to avoid fixing only one fixed expression
  {
    name: 'When explicitly saying not to query, still use the docs tool',
    input: 'What logs can you query? No need to actually query',
    expectedTool: 'search_docs',
    expectedArgs: { query: 'What logs can you query? No need to actually query' },
  },
  // When information is insufficient, do not call a tool; the Agent continues asking
  {
    name: 'When information is insufficient, ask first',
    input: 'Check its error logs from a moment ago',
    expectedTool: null,
  },
] as const;

When testing, you must not connect to the real logging service. Keep the production tool's name, description, and schema, but replace func with a test implementation, and then inspect the tool name and parameters from the AIMessage.tool_calls returned by LangGraph:

import { AIMessage, HumanMessage } from '@langchain/core/messages';
import { DynamicStructuredTool } from '@langchain/core/tools';
import { describe, expect, it } from 'vitest';
import { createModel } from '../src/model';
import { AGENT_PROMPT } from '../src/prompts/agent-prompt';
import { searchDocsToolConfig } from '../src/tools/search-docs';
import { queryLogsToolConfig } from '../src/tools/query-logs';
import { cases } from './log-intent.cases';

async function runCase(input: string) {
  // Also use dynamic import to ensure the example runs directly; in a real project, import directly
  const { createReactAgent } = await import('@langchain/langgraph/prebuilt');

  // Reuse the formal tool's name, description, and schema, but replace the execution function
  // This tests model routing without accessing real docs or production logs
  const mockSearchDocsTool = new DynamicStructuredTool({
    ...searchDocsToolConfig,
    func: async (args) => JSON.stringify({ mock: true, args }),
  } as any);
  const mockQueryLogsTool = new DynamicStructuredTool({
    ...queryLogsToolConfig,
    func: async (args) => JSON.stringify({ mock: true, args }),
  } as any);
  const agent = createReactAgent({
    llm: createModel(),
    tools: [mockSearchDocsTool, mockQueryLogsTool],
    prompt: AGENT_PROMPT,
  });

  return agent.invoke({
    messages: [new HumanMessage(input)],
  });
}

describe('log request routing regression', () => {
  for (const item of cases) {
    it(item.name, async () => {
      const result = await runCase(item.input);

      // LangGraph preserves intermediate messages, extract real tool calls from AIMessage
      const toolCalls = result.messages.flatMap((message) =>
        message instanceof AIMessage ? (message.tool_calls ?? []) : [],
      );

      if (item.expectedTool === null) {
        // When information is insufficient, first ensure the Agent did not mistakenly call any tool
        expect(toolCalls).toHaveLength(0);
        // Note: you should still manually spot-check or add semantic evaluation to confirm
        // the final answer really asks for service, environment, and time range
        return;
      }

      // Don't just check that a tool was called, check the tool name and key parameters
      expect(toolCalls).toHaveLength(1);
      expect(toolCalls[0]).toMatchObject({
        name: item.expectedTool,
        args: item.expectedArgs,
      });
    });
  }
});

When comparing before and after, besides the Prompt being tested, keep the model, sampling parameters, tool set, context, and data source the same.

Run key cases multiple times: model output has fluctuation, and a single pass only shows this result is correct, not that it is stable. If the same problem appears again in production, add the corresponding input to this test case set.

Testing is not enough: versions must be rollbackable

If the Prompt is already in an independent file like agent-prompt.ts, Git is the minimal usable version management. Don't keep two full copies of V11 and V12 in code for version numbers; that creates new duplication.

What this change actually needs to commit is the Prompt, the regression cases, and a change note:

src/prompts/agent-prompt.ts        # modified Prompt
tests/log-intent.cases.ts          # new failing cases and protection cases
changes/YYYY-MM-DD-log-intent.md   # reason for change, risk, and test results

The two tool files did not change this time; don't modify them just to "complete a version." A Git commit already saves a full code snapshot at that time. When releasing, correlate the runtime configuration with that commit:

git_commit: a1b2c3d
model: model-v3
prompt: agent-prompt.ts@a1b2c3d
tools: tools-v5
eval_set: log-intent-v2

When you need to roll back, redeploy the previous Git commit or artifact that passed evaluation. If the team uses a Prompt Registry, the practice is also to save immutable versions and then switch the production label back to the previous version.

Summary

A Prompt modification truly delivers not a piece of "better-looking" text, but a set of behavior changes that can be verified and rolled back.

It can be summarized in four steps:

  1. Locate the problem first. When the wrong tool is selected, compare the main Prompt and tool descriptions; when parameters are wrong, check the schema; when there is an authorization issue, go back to the execution code.
  2. Separate responsibilities. Overall strategy and examples go in the main Prompt; each tool's purpose and boundaries go in the description; field constraints go in the schema; avoid writing different boundaries in two places.
  3. Replace conflicting rules and add examples with opposite conclusions. Use mutually exclusive positive conditions to show which path each type of request should take, instead of appending exceptions around the wrong principle.
  4. Test before and after together, and make versions rollbackable. The new problem must improve; the old problem must not worsen. Put the Prompt and tests in Git together, and release records must be able to restore the full runtime configuration.

The real difficulty of Prompt engineering is not writing the first version, but after the tenth modification, you still know which layer you changed, which old behaviors might be affected, and how to revert to the previous version.

Before your next Prompt change, first write the four categories of results you want to protect into test cases.

Comments

Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.

badhope

The line "replace conflicting rules first, never keep appending" is key. We also used to keep appending "don't..." at the end of the Prompt, which ended up suppressing old features. Later we changed to splitting routing by task type, and moved the tool parameter constraints to the schema, leaving only the judgment boundary in the Prompt. Are your regression test cases fixed at 4 types, or will you expand them based on tool call combinations?

Sailing

This article is relatively simple. In practice, what it comes down to is tool classification and tool combinations. The fixed 4 types basically won't change; it's simple to develop and not easy to get wrong.