Langchain Tools Api
# LangChain Tools API
* * *
## @tool Decorator
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| args_schema | BaseModel or None | None | Parameter validation model. If not passed, it is automatically generated from the function signature |
| return_direct | bool | False | Whether to return directly (skip model's re-thinking) |
| name | str or None | Function name | Tool name |
| description | str or None | Function docstring | Tool description |
* * *
## BaseTool Main Properties and Methods
| Property/Method | Description |
| --- | --- |
| name | Tool name (string) |
| description | Tool description (string) |
| args_schema | Parameter Pydantic model |
| return_direct | Whether to return directly (bool) |
| invoke(input) | Call the tool, input is the parameter dictionary |
| ainvoke(input) | Asynchronously call the tool |
* * *
## Dependency Injection Markers
| Marker | Usage | Usage Example |
| --- | --- | --- |
| InjectedState | Inject Agent state | Annotated[dict, InjectedState] |
| InjectedStore | Inject cross-session storage | Annotated[BaseStore, InjectedStore()] |
| InjectedToolCallId | Inject tool call ID | Annotated[str, InjectedToolCallId()] |
| InjectedConfig | Inject runtime configuration | Annotated[RunnableConfig, InjectedConfig()] |
* * *
## ToolCall
| Property | Type | Description |
| --- | --- | --- |
| name | str | Tool name |
| args | dict | Tool call parameters |
| id | str or None | Tool call ID |
| type | str | Fixed value: "tool_call" |
* * *
## create_tool() Function
```python
from langchain_core.tools import create_tool
@create_tool()
def my_tool(param: str) -> str:
"""Tool description"""
return param
**Parameters:**
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| func | Callable | Required | Tool function |
| name | str or None | None | Tool name, defaults to function name |
| description | str or None | None | Tool description, defaults to function docstring |
| args_schema | Type | None | Pydantic model for parameter validation |
| return_direct | bool | False | Whether to return directly |
* * *
## convert_to_openai_tool() Function
```python
from langchain_core.utils.openai import convert_to_openai_tool
# Convert tool to OpenAI format
tool_json = convert_to_openai_tool(your_tool)
**Parameters:**
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| tool | BaseTool | Required | Tool object |
**Return Value:** OpenAI tool format JSON object
* * *
## Structured Tool
```python
from langchain_core.tools import StructuredTool
def add(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
# Create structured tool
tool = StructuredTool.from_function(add)
**Creation Methods:**
| Method | Description |
| --- | --- |
| from_function(func) | Create from function |
| from_function(func, name, description) | Create with custom name and description |
* * *
## Tool Definition Example
```python
from langchain_core.tools import tool
@tool
def calculate(expression: str) -> str:
"""Perform mathematical calculations"""
try:
result = eval(expression)
return str(result)
except Exception as e:
return f"Error: {str(e)}"
# Use the tool
result = calculate.invoke({"expression": "2 + 3 * 4"})
print(result) # Output: 14
* * *
## Tool with Complex Parameters
```python
from langchain_core.tools import tool
from pydantic import BaseModel, Field
class SearchInput(BaseModel):
query: str = Field(description="Search query")
max_results: int = Field(default=10, description="Maximum number of results")
@tool(args_schema=SearchInput)
def search(input_data: SearchInput) -> str:
"""Search for information"""
return f"Searching for: {input_data.query}, max results: {input_data.max_results}"
# Use the tool
result = search.invoke({"query": "Python", "max_results": 5})
* * *
## Tool Return Value Processing
```python
from langchain_core.tools import tool
@tool
def get_weather(location: str) -> dict:
"""Get weather information"""
return {
"location": location,
"temperature": 25,
"condition": "Sunny"
}
# The tool automatically converts dict to string
result = get_weather.invoke({"location": "Beijing"})
# Returns: {"location": "Beijing", "temperature": 25, "condition": "Sunny"}
* * *
## Related Links
- (#)
- (#)
- (#)
- (#)
- (#)
YouTip