AI AgentsLangChain
How do tool names and docstrings shape model tool selection?
Question 292 of 324 · Updated
On this page
- Direct answer
- 1. Where metadata enters the decision process
- 2. Name tools for the task, not the implementation
- Separate the Python symbol from the public contract
- 3. Describe intent and distinguish overlapping capabilities
- Use positive conditions and concise exclusions
- 4. Argument descriptions help the model choose the right values
- A unit mismatch example
- 5. Metadata optimization is a controlled behavioral experiment
- 6. Build a small metadata-specific evaluation dataset
- Metrics that reveal different problems
- 7. Tested Python implementation: compare recorded metadata experiments
- 8. Collect actual LangChain model proposals for evaluation
- 9. Production release and regression practices
- 10. Common mistakes and corrective patterns
- Interview-ready answer
- Official documentation research leads and verification status
Direct answer#
In LangChain, a tool's name, description and argument schema form the model-facing contract used to decide which capability to request and how to supply its inputs. For a typical decorated Python function, the name comes from the function name unless explicitly overridden, the description comes from its docstring unless another description is configured, and typed parameters contribute to its argument schema. An adapter converts those definitions into the selected model provider's supported tool format.
Specific, distinguishable metadata helps the model tell apart similar operations. For example, a tool that retrieves an invoice by exact ID should be distinguishable from one that searches invoices by customer and date. A tool that estimates a credit must be distinguishable from a tool that actually issues one. These descriptions influence probabilistic model decisions; they do not enforce authorization or guarantee accuracy.
The generic tool-description lesson (#87) explains why clear descriptions are important. The decorator lesson (#291) explains how to construct a tool object. This lesson focuses on the LangChain metadata contract and a controlled method for measuring whether changes to that contract improve model tool selection. Detailed Pydantic validation, runtime injection, dynamic tool filtering and broader trajectory evaluation are addressed in separate lessons.
1. Where metadata enters the decision process#
A Python function is an executable capability. The model normally does not inspect its implementation or run its source code. It receives a provider-compatible specification of the tool, including the tool name, description and supported argument schema. A chat model generates a proposed tool request, and the runtime resolves it against the approved tool registry.
A useful conceptual distinction is between three contracts:
| Contract | Consumer | Example |
|---|---|---|
| Semantic contract | Model and developers | Retrieve one invoice when its exact ID is known |
| Structural contract | Provider adapter and argument validator | invoice_id is a required string |
| Execution contract | Trusted application and external service | Read only invoices authorized for the caller |
The name and description primarily express semantics. The schema constrains the structure, subject to supported provider behavior. The implementation and its surrounding policy enforce the execution contract. A sentence in a docstring does not acquire the authority of a backend access-control rule.
Tool selection is context-dependent. The model considers user instructions, previous observations, available tools, tool schemas and its learned associations. There is no universal deterministic similarity score by which every provider selects a tool. A provider may also support options that require a tool call, forbid tool calls, or request a specific tool. Those options change the decision problem and must be held constant when evaluating metadata.
2. Name tools for the task, not the implementation#
Names should be stable, descriptive and sufficiently distinct within the registered tool set. Use provider-compatible characters and lengths; snake_case with short verb-object identifiers is a reasonable convention for many Python tool integrations, not a universal provider requirement.
| Weak model-facing name | Better name | Reason |
|---|---|---|
| fetch | get_invoice | Identifies the object and exact retrieval action |
| search | find_invoices | Identifies the searchable entity |
| process | estimate_credit | States that the operation produces an estimate |
| credit | issue_credit | Signals an actual state-changing action |
| data_v2 | get_shipping_status | Describes the capability rather than an implementation revision |
A name should not exaggerate the tool's behavior. Do not name an estimate function refund_payment if it does not perform a refund. Conversely, do not call a refunding operation check_payment if it actually modifies financial state.
Stable naming also matters outside model inference. Tool identifiers appear in traces, regression fixtures, approvals, dispatch maps and sometimes persisted execution state. A rename may improve semantics while introducing compatibility risk. Review the effect on active workflows before changing a published identifier.
Separate the Python symbol from the public contract#
Modern LangChain releases support custom names with the decorator. For example:
PYTHONfrom langchain.tools import tool @tool("get_invoice") def retrieve_invoice_record(invoice_id: str) -> str: """Read one synthetic invoice using its exact invoice ID.""" return {"INV-17": "USD 25.00"}.get(invoice_id, "not available") print(retrieve_invoice_record.name) print(retrieve_invoice_record.description)
The intended model-facing name is get_invoice even though the implementation function is named retrieve_invoice_record. This lets a team refactor internal code without unnecessarily changing the public tool contract.
SDK verification: The local environment lacks LangChain, langchain_core and LangGraph. SDK examples in this article are illustrative and unexecuted. Check the actual installed version and provider constraints before use. The dependency-free evaluator in section 7 was executed locally.
3. Describe intent and distinguish overlapping capabilities#
Good descriptions answer the selection questions that the model must resolve: what the tool does, when it is suitable, which information is required, what it returns, and what meaningful limitations or side effects it has. Avoid merely restating the name.
Consider a fictional billing agent with four available operations.
| Tool | Ambiguous description | Discriminative description |
|---|---|---|
| get_invoice | Get billing data | Read one authorized invoice by exact invoice ID; use when that ID is known |
| find_invoices | Get billing information | Search authorized invoices using customer and date filters when exact invoice ID is unknown |
| estimate_credit | Handle credits | Calculate a proposed credit amount without changing any invoice or payment |
| issue_credit | Handle customer credits | Apply an approved credit to an existing invoice; changes the billing ledger |
The improved descriptions communicate the decision boundary. If a customer asks to inspect invoice INV-17, an exact lookup is a natural candidate. If the customer asks to find invoices from a certain date but lacks an invoice ID, a search is more appropriate. If the user asks only how much credit might be available, the estimate is appropriate rather than an actual ledger mutation.
These examples are intended choices, not observed outcomes from a real model. The improvement must be measured.
Use positive conditions and concise exclusions#
A description that includes a specific positive condition and a useful exclusion can resolve confusion between neighbors:
- get_invoice: use when an exact invoice ID is known; do not use for discovering an unknown invoice.
- find_invoices: use to discover matching invoices when the exact ID is unavailable.
- estimate_credit: return a hypothetical estimate only; does not apply credit.
- issue_credit: apply a credit only through the authorized approval workflow; never use for a quote.
Negative instructions should be narrow and actionable. Long lists of irrelevant prohibited operations can make metadata harder to read and consume context. A useful exclusion clarifies a genuine decision boundary. It is not a security mechanism: the application must prevent an unapproved ledger mutation regardless of the model's interpretation.
This is an intended selection map for test design, not a claim that the model internally follows these branches or that LangChain automatically enforces them.
4. Argument descriptions help the model choose the right values#
Two fields can share the same Python type yet have different meanings. An invoice identifier and a customer identifier may both be strings. An amount could represent cents, dollars, rupees, a percentage or an approved maximum. Type inference alone does not communicate these distinctions.
| Field | Insufficient description | More useful description |
|---|---|---|
| invoice_id | ID | Exact invoice identifier, such as INV-17; not a customer ID |
| customer_id | Customer | Authorized customer identifier used to search invoices |
| start_date | Date | Inclusive start of the date range, ISO YYYY-MM-DD |
| amount_cents | Amount | Proposed credit in integer cents, not dollars |
| limit | Count | Maximum number of results requested; service enforces its cap |
A docstring can contain both a summary and argument-level documentation. In supported LangChain versions, the decorator can parse an appropriate Google-style docstring into schema descriptions using parse_docstring=True. Confirm exact behavior and parser requirements in the installed version.
PYTHONfrom langchain.tools import tool @tool(parse_docstring=True) def estimate_credit(invoice_id: str, amount_cents: int) -> dict: """Estimate a possible invoice credit without modifying any record. Args: invoice_id: Exact synthetic invoice ID, such as INV-17. amount_cents: Requested credit in integer USD cents, not dollars. """ if invoice_id != "INV-17": return {"status": "unavailable"} if not 0 < amount_cents <= 2500: raise ValueError("amount outside synthetic invoice limit") return {"status": "estimate_only", "amount_cents": amount_cents}
The intended contract is a read-only fictional estimate. It is not a real billing policy implementation. A real credit estimator must consult authorized records, validate currency and refundable balance, and avoid exposing another customer's data. An actual credit operation requires separate approval and commit controls.
Inspect the metadata rather than guessing whether the decorator parsed the arguments:
PYTHONprint(estimate_credit.name) print(estimate_credit.description) print(estimate_credit.get_input_schema().model_json_schema())
These SDK snippets were not executed. In a compatible Pydantic-backed release, schema inspection can expose property descriptions, required fields and types. The actual model-facing tool schema may differ from the local validation schema, especially for injected parameters. Inspect the provider-converted tool definition as well. The next lesson examines explicit Pydantic schemas and strict argument validation.
A unit mismatch example#
If a user requests a USD 15.00 credit, a model might generate amount_cents=15 rather than 1500 when the metadata is ambiguous. Both are integers. Even a perfectly valid integer schema does not establish the correct business meaning.
Use a descriptive field name, clarify the unit, test representative cases, and validate the amount against the user's explicit request and trusted business policy before a sensitive action. Never let the model decide the unit of a monetary transaction implicitly.
5. Metadata optimization is a controlled behavioral experiment#
When an agent chooses a wrong tool, first classify the failure. It may arise from ambiguous metadata, insufficient task evidence, unavailable capability, provider limitations, a schema mismatch, excessive tool exposure or the model itself. Rewriting descriptions without diagnosing the cause can improve one case while harming another.
A practical optimization workflow is:
- Capture the actual model-facing tool specifications and the baseline configuration.
- Identify confused tool pairs and the missing semantic distinction.
- Create a small, reviewed metadata revision.
- Hold the model revision, user prompts, system instructions, tool implementations, permissions and schemas constant where feasible.
- Run the baseline and candidate on identical test cases, with repeated model trials when variability matters.
- Inspect selection and argument failures, then validate end-to-end outcomes.
- Approve, reject or refine the revision using predefined release gates.
For a strict name-only experiment, keep descriptions and argument definitions unchanged; when the tool name changes, map both identifiers to the same underlying capability in the evaluator. For a description-only experiment, preserve names and schemas. A field-description experiment should preserve argument types and validation constraints. If several components change together, record that combined treatment rather than attributing any effect solely to one field.
Some providers may transform or reorder tool specifications. Keep the ordering controlled for the main experiment, then optionally randomize it in a separate robustness test. Record the actual exposure set: a tool cannot be selected if it was not available for that invocation. Avoid exposing dangerous tools to a live environment merely to test a negative scenario; use harmless stand-ins or scripted requests.
6. Build a small metadata-specific evaluation dataset#
The dataset should distinguish action intent, missing prerequisites and situations where no tool call is appropriate. Label the acceptable first tool rather than always imposing a single exact trace. For complex tasks, multiple first actions may be equally acceptable. A no-call label may mean the agent should clarify or answer without an external operation; a separate outcome test must distinguish those two cases.
| Case ID | Request or condition | Acceptable first tool | Important check |
|---|---|---|---|
| known | Read INV-17 | get_invoice | Correct invoice ID |
| unknown | Find matching authorized invoices with valid filters | find_invoices | Proper search filters |
| preview | Estimate a credit; do not apply it | estimate_credit | Correct unit; no ledger mutation |
| missing | Check an invoice without an ID or usable search information | No call; clarify | Do not invent identifiers |
| policy | Explain general credit policy using supplied policy text | No billing action | Do not issue a credit |
Include paraphrases, terse requests, ambiguous terminology, different date and currency representations, overlapping tool descriptions and unsupported tasks. Also include examples where the model is tempted to request a forbidden operation. The forbidden label should represent a real workload restriction; actual production authorization remains outside the evaluator.
Split optimization examples from held-out evaluation examples. Repeatedly editing a description to pass a handful of known prompts can overfit those phrases and fail on real customer language.
Metrics that reveal different problems#
Let N be the number of labeled cases and C the number whose first decision is acceptable.
- Selection accuracy = C / N.
- Joint selection-and-argument accuracy = number of acceptable first decisions with valid required arguments (or an acceptable no-call) / N.
- Argument validity among calls = number of calls passing the defined argument checks / number of proposed calls.
- Forbidden proposal rate = number of cases with a forbidden proposed action / N.
A forbidden proposal is not an executed unauthorized action. Track the latter separately at the action boundary. Zero forbidden proposals in a small dataset is not proof of safety. Similarly, high selection accuracy can conceal wrong units, resource IDs or unsupported assumptions.
The broader evaluation lesson (#79 in the LangChain source sequence) will cover more comprehensive tool argument accuracy and trajectories. Here we use first-decision metrics specifically to isolate changes in metadata.
7. Tested Python implementation: compare recorded metadata experiments#
The following dependency-free evaluator accepts labeled cases and predictions. It deliberately uses scripted predictions instead of calling a model. The two result sets illustrate how a metadata comparison would be scored, not actual performance measurements of LangChain or any provider.
PYTHONfrom dataclasses import dataclass from collections import Counter @dataclass(frozen=True) class Case: id: str acceptable: frozenset[str | None] forbidden: frozenset[str] = frozenset() @dataclass(frozen=True) class Prediction: tool: str | None args_valid: bool = True def score(cases, predictions): ids = {c.id for c in cases} if not ids or len(ids) != len(cases) or ids != predictions.keys(): raise ValueError('cases and predictions must match uniquely') counts = Counter() confusion = Counter() for case in cases: pred = predictions[case.id] correct = pred.tool in case.acceptable counts['selection'] += correct counts['joint'] += correct and (pred.tool is None or pred.args_valid) counts['forbidden'] += pred.tool in case.forbidden counts['calls'] += pred.tool is not None counts['valid_calls'] += pred.tool is not None and pred.args_valid confusion[(tuple(sorted(str(x) for x in case.acceptable)), str(pred.tool))] += 1 return dict(counts), confusion cases = [Case('known', frozenset({'get_invoice'})), Case('unknown', frozenset({'find_invoices'})), Case('preview', frozenset({'estimate_credit'}), frozenset({'issue_credit'})), Case('missing', frozenset({None})), Case('policy', frozenset({None}), frozenset({'issue_credit'}))] old = dict(zip([c.id for c in cases], [Prediction('find_invoices'), Prediction('find_invoices', False), Prediction('issue_credit'), Prediction(None), Prediction('issue_credit')])) new = dict(zip([c.id for c in cases], [Prediction('get_invoice'), Prediction('find_invoices'), Prediction('estimate_credit'), Prediction(None), Prediction(None)])) a, matrix = score(cases, old) b, _ = score(cases, new) assert a['selection'] == 2 assert a['joint'] == 1 assert a['forbidden'] == 2 assert a['calls'] == 4 and a['valid_calls'] == 3 assert b['selection'] == b['joint'] == 5 assert b['forbidden'] == 0 assert b['calls'] == b['valid_calls'] == 3 assert sum(matrix.values()) == 5 for invalid_cases, invalid_preds in [ (cases, {}), (cases + [cases[0]], new) ]: try: score(invalid_cases, invalid_preds) except ValueError: pass else: raise AssertionError('invalid fixture accepted') print('10 checks passed') print(a, b)
Actual local execution on Python 3.13.5:
10 checks passed
{'selection': 2, 'joint': 1, 'forbidden': 2, 'calls': 4, 'valid_calls': 3} {'selection': 5, 'joint': 5, 'forbidden': 0, 'calls': 3, 'valid_calls': 3}The tests verify the baseline and candidate counts, the confusion-summary count, and rejection of missing prediction sets and duplicate case identifiers.
| Metric | Scripted baseline | Scripted candidate |
|---|---|---|
| First-decision selection accuracy | 2/5 = 40% | 5/5 = 100% |
| Joint selection and argument accuracy | 1/5 = 20% | 5/5 = 100% |
| Argument validity among proposed calls | 3/4 = 75% | 3/3 = 100% |
| Forbidden proposal rate | 2/5 = 40% | 0/5 = 0% |
The distinction between selection and joint correctness is important: the baseline predicts find_invoices correctly for the unknown-invoice case, but its arguments are marked invalid. It receives selection credit but no joint credit.
The confusion summary groups acceptable label sets against predicted names. It is not a conventional single-label confusion matrix when more than one tool is acceptable. The evaluator assumes labels and argument validity have already been reviewed. It does not parse actual tool payloads, execute tools, grade clarifying questions, establish authorization or infer factual correctness. Production code should independently compute args_valid from validated fixture expectations and reject malformed or inconsistent labels. If no calls are proposed, report the call-conditional validity metric as undefined rather than dividing by zero.
These limitations are deliberate. The example tests measurement logic rather than claiming that better descriptions caused the scripted differences.
8. Collect actual LangChain model proposals for evaluation#
For a compatible chat model, binding a fixed tool set and calling the model directly can isolate the first tool proposal without running the complete agent execution loop.
PYTHONfrom langchain.chat_models import init_chat_model from langchain_core.messages import SystemMessage, HumanMessage model = init_chat_model("openai:gpt-4o-mini") bound = model.bind_tools([retrieve_invoice_record, estimate_credit]) message = bound.invoke([ SystemMessage(content="Select an appropriate read-only billing tool " "or request clarification when needed."), HumanMessage(content="Read invoice INV-17."), ]) for call in message.tool_calls: print(call["name"], call["args"])
This illustrative SDK snippet reuses the two fictional read-only tools defined above. It does not expose issue_credit and does not execute the proposed calls. A complete experiment would define the same approved tools for each metadata variant, capture the actual provider-converted definitions and include all relevant harmless stand-ins. The model identifier is illustrative; package and provider support must be checked. No model call was performed locally.
Distinguish no tool calls from invalid or truncated tool calls. Inspect supported error fields and finish metadata before labeling the response. If the model emits multiple calls at once, establish a scoring policy for the complete first batch and dependencies. Do not silently discard an unsafe additional call just because the first call was correct.
For reproducibility, retain sanitized proposal records, fixture IDs, actual exposed tool names, argument-validation results, model and metadata revisions, generation configuration and error classifications. Never log raw customer data or credentials merely to evaluate a description.
Then run agent-level regression tests to determine whether better first-call selection improves actual outcomes. First-call correctness can be insufficient when the task requires later calls, tool-result interpretation or human approval.
9. Production release and regression practices#
A description change is a behavioral change even if the Python implementation stays identical. Pin a reviewed metadata revision with the tool registry. Include tool names, effective descriptions, provider-facing input schemas, tool implementation versions, policy revision, model configuration and evaluation dataset version in the release manifest.
A helpful release decision uses both average metrics and safety-critical slices:
| Release criterion | Example policy, not a universal threshold |
|---|---|
| Held-out joint accuracy | No material degradation against baseline |
| Confused neighbor tools | No new regressions in critical read-versus-write cases |
| No-call behavior | Missing prerequisites still trigger clarification |
| Sensitive operations | No unauthorized execution in integration tests |
| Tool-name compatibility | Existing dispatch and active workflow contracts remain valid |
| Operational performance | Acceptable context size, latency and cost |
Use paired evaluations on the same tasks. For a stochastic model, repeat calls and estimate uncertainty rather than declaring victory from a small percentage difference. Preserve the baseline configuration, review errors by scenario, and canary the new metadata on approved workloads. Shadow testing must not duplicate write operations or send private data to unauthorized services.
Long descriptions also impose an input-context cost. Suppose 30 exposed tools each gain an unnecessary 60 tokens, and those definitions are sent in four model requests. The added logical input is 30 × 60 × 4 = 7,200 tokens per run. At an illustrative uncached input rate of USD 2 per million tokens, that would be USD 0.0144 per run. Actual tokenization, caching and billing differ. These are hypothetical figures, not provider prices or measured overhead.
Prefer short, discriminative descriptions. Do not remove essential preconditions or side-effect warnings to save tokens. If the catalog is large, consider approved tool filtering in the application; the dedicated dynamic tool-selection lesson addresses that mechanism. Never expose unauthorized tools merely because their descriptions discourage use.
10. Common mistakes and corrective patterns#
| Mistake | Correction |
|---|---|
| Every tool has a generic name such as process | Choose stable verb-object identifiers |
| Neighbor descriptions repeat the same wording | Specify the differentiating intent, input and result |
| A quote tool and a mutation tool sound identical | Explicitly state whether an operation changes external state |
| Monetary argument is named amount with no unit | Use a precise field name and description; verify business value |
| Negative instructions are treated as permission checks | Enforce authorization in trusted application code |
| Docstrings are assumed to reach the provider unchanged | Inspect actual converted tool metadata |
| A model is forced to call a tool during a no-call test | Preserve the intended tool-choice configuration |
| Metadata experiments change model, schemas and permissions at once | Isolate changes or document the combined treatment |
| Only exact first-call matches are measured | Include acceptable alternatives, argument validity and outcomes |
| Descriptions are optimized against every test prompt | Preserve held-out cases and monitor regressions |
Descriptions from external or dynamically discovered tools are also a trust surface. Treat them as untrusted until the host has approved the capability and metadata. Do not allow an external description to grant itself authority, expand permissions or instruct the application to disclose credentials. This lesson does not replace the dedicated prompt-injection and MCP security material.
Interview-ready answer#
LangChain presents a tool's name, description and argument schema to the model through a provider adapter. Clear names and discriminative docstrings help a model choose between overlapping capabilities and supply semantically appropriate arguments. I use stable action-oriented identifiers, document when a tool is appropriate and whether it has side effects, and inspect the actual model-facing schema. I measure metadata changes on paired held-out cases with selection accuracy, joint argument correctness, no-call behavior and forbidden proposals. I then test the full agent and enforce authorization independently. Good metadata improves guidance; it does not guarantee a correct or permitted action.
Official documentation research leads and verification status#
- LangChain tools
- LangChain models
- LangChain agents
- LangChain messages
- LangChain API reference
- LangSmith evaluation
- Python dataclasses
Authorized offline research exception applied. These official documentation URLs are research leads rather than live-accessed citations. Current API signatures and provider behavior were not independently verified. The standalone evaluation code was executed on Python 3.13.5 and all 10 checks passed. LangChain, langchain_core and LangGraph were absent, so actual SDK examples and live model experiments were not executed. The comparative predictions are scripted and numerical costs hypothetical. Mermaid diagrams use standard triple-backtick fences; live rendering and website display were not verified.
References
- 1.LangChain toolsdocs.langchain.com
- 2.LangChain modelsdocs.langchain.com
- 3.LangChain agentsdocs.langchain.com
- 4.LangChain messagesdocs.langchain.com
- 5.LangChain API referencereference.langchain.com
- 6.LangSmith evaluationdocs.langchain.com
- 7.Python dataclassesdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps