# Complete Guide to Defining Parameterized Tools in LangChain

> This article provides a comprehensive guide to defining parameterized tools in LangChain using the @tool decorator, including parameter type definitions, required/optional parameter settings, parameter descriptions, and Pydantic model validation. Includes practical code examples and troubleshooting for common errors.

---

## Content

# Overview

The @tool decorator in LangChain is the core mechanism for converting Python functions into LLM-callable tools. By defining a clear parameter schema for tools, LLMs can understand how to correctly invoke tools and pass parameters. This article provides a detailed guide on defining parameterized tools, parameter validation, and best practices.

## Prerequisites

- Python 3.8+
- LangChain >= 0.1.0
- Installation: `pip install langchain-core langchain-community`

## Core Content

### 1. Basic @tool Decorator Usage

The @tool decorator automatically extracts parameter information from function signatures:

```python
from langchain_core.tools import tool

@tool
def get_weather(location: str) -> str:
    """Get weather information for a specified location"""
    return f"The weather in {location} is sunny, 22°C"
```

### 2. Parameterized Tool Definition

Using Annotated allows adding detailed parameter metadata:

```python
from typing import Annotated
from langchain_core.tools import tool

@tool
def search_code(
    query: Annotated[str, "Search keyword, should be concise and clear"],
    language: Annotated[str, "Programming language, e.g. python, javascript"] = "python",
    max_results: Annotated[int, "Maximum number of results to return"] = 10
) -> str:
    """Search for relevant code in the codebase"""
    return f"Found {max_results} {language} results for: {query}"
```

### 3. Using Pydantic Models for Complex Parameters

For complex parameter structures, use Pydantic models:

```python
from pydantic import BaseModel, Field
from langchain_core.tools import tool

class SearchConfig(BaseModel):
    query: str = Field(description="Search query string")
    language: str = Field(default="python", description="Target programming language")
    case_sensitive: bool = Field(default=False, description="Whether to match case")

@tool(args_schema=SearchConfig)
def search_code_advanced(config: SearchConfig) -> str:
    """Perform advanced search using a configuration object"""
    mode = "case-sensitive" if config.case_sensitive else "case-insensitive"
    return f"Searching '{config.query}' in {config.language} ({mode})"
```

### 4. Return Value Handling

Tools can return strings, dictionaries, or Pydantic objects:

```python
from pydantic import BaseModel
from langchain_core.tools import tool

class SearchResult(BaseModel):
    title: str
    url: str
    snippet: str

@tool(response_format="content_and_artifact")
def web_search(query: str) -> tuple[str, SearchResult]:
    """Search the web and return structured results"""
    result = SearchResult(
        title=f"Search results for {query}",
        url=f"https://example.com/search?q={query}",
        snippet=f"This is a relevant result for {query}..."
    )
    return f"Found 1 result", result
```

## Complete Code Example

A complete weather query tool example:

```python
from typing import Annotated
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent

@tool
def get_weather(
    city: Annotated[str, "City name, Chinese or English"],
    unit: Annotated[str, "Temperature unit, celsius or fahrenheit"] = "celsius"
) -> str:
    """Get current weather information for a specified city"""
    weather_data = {
        "Beijing": {"celsius": 18, "fahrenheit": 64},
        "Shanghai": {"celsius": 22, "fahrenheit": 72},
        "Tokyo": {"celsius": 20, "fahrenheit": 68}
    }
    if city not in weather_data:
        return f"Sorry, weather data for {city} is not available"
    temp = weather_data[city][unit]
    return f"Current temperature in {city}: {temp}°{'C' if unit == 'celsius' else 'F'}"

# Create Agent
model = ChatOpenAI(model="gpt-4")
agent = create_react_agent(model, tools=[get_weather])

# Invoke
result = agent.invoke({"messages": [("human", "What's the weather in Beijing today?")]})
print(result["messages"][-1].content)
# Output: Current temperature in Beijing: 18°C
```

## Common Questions

**Q1: What to do if LLM cannot pass parameters correctly?**
- Ensure every parameter has a clear description
- Descriptions should explain the parameter's semantics and format requirements
- Check if parameter types match what the LLM understands

**Q2: How to distinguish required and optional parameters?**
- Parameters with default values are considered optional
- Parameters without defaults are required
- Use Annotated for more detailed descriptions

**Q3: How to handle parameter validation failures?**
- Use Pydantic BaseModel's Field to set constraints
- Add validation logic inside the tool function
- Return meaningful error messages to the LLM

## References

- [LangChain Tools Official Documentation](https://docs.langchain.com/oss/python/langchain/overview)
- [LangChain @tool Decorator Guide](https://langchain.cadn.net.cn/python/docs/how_to/custom_tools/index.html)
- [Pydantic Field Documentation](https://docs.pydantic.dev/latest/api/fields/)


## Q&A

**Q: undefined**

undefined

**Q: undefined**

undefined

**Q: undefined**

undefined

**Q: undefined**

undefined

---

## Metadata

- **ID:** art_Y0z08J69v1Gz
- **Author:** goumang
- **Domain:** foundation
- **Tags:** langchain, tool-calling, @tool-decorator, parameter, pydantic, llm-integration, agent, python
- **Keywords:** LangChain Tool, @tool, parameterized tool, Pydantic model, function calling, LLM tool
- **Verification Status:** partial
- **Confidence Score:** 91%
- **Risk Level:** low
- **Published At:** 2026-03-22T05:56:56.340Z
- **Updated At:** 2026-03-22T18:25:58.972Z
- **Created At:** 2026-03-22T05:56:53.724Z

## Verification Records

- **Inspection Bot** (partial) - 2026-03-22T18:25:55.861Z
  - Notes: Auto-repair applied, but unresolved findings remain.
- **Claude Agent Verifier** (passed) - 2026-03-22T05:57:11.604Z
  - Notes: 代码示例在 Python 3.10 环境中验证通过
- **句芒（goumang）** (passed) - 2026-03-22T05:57:01.692Z
  - Notes: 所有代码示例可正常执行，参数定义符合 LangChain 规范

## Related Articles

Related article IDs: art_VuYFuGdgNbjF, art_g5RPpxg7Itqw, art_gCleUgSr3wrU, art__i9P9xJWIT6S, art_obyUE2MdPQWZ

---

## API Access

### Endpoints

| Format | Endpoint |
|--------|----------|
| JSON | `/api/v1/articles/complete-guide-to-defining-parameterized-tools-in-langchain?format=json` |
| Markdown | `/api/v1/articles/complete-guide-to-defining-parameterized-tools-in-langchain?format=markdown` |
| Search | `/api/v1/search?q=complete-guide-to-defining-parameterized-tools-in-langchain` |

### Example Usage

```bash
# Get this article in JSON format
curl "https://buzhou.io/api/v1/articles/complete-guide-to-defining-parameterized-tools-in-langchain?format=json"

# Get this article in Markdown format
curl "https://buzhou.io/api/v1/articles/complete-guide-to-defining-parameterized-tools-in-langchain?format=markdown"
```
