Tool Parameter Types
Use Optional, Union, Literal, Enum, containers, Pydantic models, dataclasses and TypedDict in tool signatures and the agent sees the right schema
Use expressive Python type annotations in tool signatures and agents understand exactly what parameters they can pass.
from typing import Literal
from praisonaiagents import Agent, tool
@tool
def analyse(text: str, mode: Literal["fast", "deep"] = "fast") -> str:
"""Analyse text with a fast or deep mode."""
return f"{mode} analysis of: {text}"
agent = Agent(name="Analyst", tools=[analyse])
agent.start("Analyse this document in deep mode")The user asks the agent to call a typed tool; annotations become JSON Schema so the model passes valid parameters.
graph LR
subgraph "Tool Parameter Type System"
A[Python Annotation] --> B[annotation_to_json_schema]
B --> C[JSON Schema]
C --> D[LLM Tool Schema]
end
classDef annotation fill:#6366F1,stroke:#7C90A0,color:#fff
classDef process fill:#F59E0B,stroke:#7C90A0,color:#fff
classDef schema fill:#189AB4,stroke:#7C90A0,color:#fff
classDef output fill:#10B981,stroke:#7C90A0,color:#fff
class A annotation
class B process
class C schema
class D outputQuick Start
- Optional Parameter
Create a tool where parameters can be omitted by the agent:
python from typing import Optional from praisonaiagents import Agent, tool @tool def search(query: str, max_results: Optional[int] = None) -> str: """Search the web. Leave max_results blank to use the default.""" limit = max_results or 10 return f"Searched '{query}' (limit={limit})" agent = Agent( instructions="You search the web for information", tools=[search] ) agent.start("Find AI news") - Literal for Fixed Choices
Restrict parameter values to specific literal options:
python from typing import Literal from praisonaiagents import Agent, tool @tool def analyze(text: str, mode: Literal["fast", "deep"] = "fast") -> str: """Analyze text with different modes.""" if mode == "deep": return f"Deep analysis of: {text}" return f"Quick analysis of: {text}" agent = Agent( instructions="You analyze text content", tools=[analyze] ) agent.start("Analyze this document in deep mode") - Enum for Choices
Use Enum classes for reusable choice sets across tools:
python from enum import Enum from praisonaiagents import Agent, tool class Priority(str, Enum): LOW = "low" MEDIUM = "medium" HIGH = "high" @tool def create_task(title: str, priority: Priority = Priority.MEDIUM) -> str: """Create a new task with specified priority.""" return f"Created task '{title}' with priority: {priority.value}" agent = Agent( instructions="You manage tasks", tools=[create_task] ) agent.start("Create a high priority task for the meeting") - Pydantic Model Parameter
Pass a structured object with named fields:
python from pydantic import BaseModel from praisonaiagents import Agent, tool class Point(BaseModel): x: float y: float @tool def place_marker(label: str, position: Point) -> str: """Place a marker at a map position.""" return f"Placed '{label}' at {position}" agent = Agent(instructions="You plot markers on a map", tools=[place_marker]) agent.start("Place a marker called 'home' at (12.5, -4.2)") - Dataclass Parameter
Plain
@dataclassclasses work the same way:python from dataclasses import dataclass from praisonaiagents import Agent, tool @dataclass class Address: street: str city: str zip: str @tool def ship_order(order_id: str, address: Address) -> str: """Ship an order to the given address.""" return f"Shipped {order_id} to {address}" agent = Agent(instructions="You ship orders", tools=[ship_order]) agent.start("Ship order A-17 to 10 Main St, Springfield, 12345") - Sequence, Set and Tuple
Ask for lists of items, unique tags, or fixed-length pairs:
python from typing import Sequence, Set, Tuple from praisonaiagents import Agent, tool @tool def plan_trip(origin: Tuple[float, float], stops: Sequence[str], tags: Set[str]) -> str: """Plan a trip from a (lat, lon) origin across a list of stops.""" return f"Trip from {origin} via {len(stops)} stops; tags={tags}" agent = Agent(instructions="You plan trips", tools=[plan_trip]) agent.start("Plan a trip from (51.5, -0.1) through Paris, Rome and Lyon; tag it scenic and food")
How It Works
The agent converts your Python type annotations into JSON Schema before the LLM sees the tool definition.
| Python Annotation | JSON Schema Output |
|---|---|
str, int, float, bool | {"type": "string"} and related primitives |
Optional[int] | {"anyOf": [{"type": "integer"}, {"type": "null"}]} |
Union[str, int] | {"anyOf": [{"type": "string"}, {"type": "integer"}]} |
Literal["fast", "deep"] | {"type": "string", "enum": ["fast", "deep"]} |
| Enum subclass (str-valued) | {"type": "string", "enum": ["low", "medium", "high"]} |
List[int] | {"type": "array", "items": {"type": "integer"}} |
Dict[str, int] | {"type": "object", "additionalProperties": {"type": "integer"}} |
tuple, Sequence[str], Iterable[int] | {"type": "array", "items": {...}} |
Set[str], FrozenSet[int] | {"type": "array", "items": {...}, "uniqueItems": true} |
Tuple[int, str] (fixed-length) | {"type": "array", "items": {"anyOf": [...]}, "minItems": 2, "maxItems": 2} |
Tuple[int, ...] (variadic) | {"type": "array", "items": {"type": "integer"}} |
Tuple[()] | {"type": "array", "maxItems": 0} |
Mapping[str, int] | {"type": "object", "additionalProperties": {"type": "integer"}} |
Pydantic BaseModel subclass | {"type": "object", "properties": {...}} (from model_json_schema()) |
@dataclass | {"type": "object", "properties": {...}, "required": [...]} |
TypedDict | {"type": "object", "properties": {...}, "required": [...]} |
Common Patterns
Mode Flags with Defaults
@tool
def process_data(data: str, mode: Literal["fast", "thorough"] = "fast") -> str:
"""Process data with different thoroughness levels."""
if mode == "thorough":
return f"Thoroughly processed: {data}"
return f"Quick processing: {data}"Shared Choice Sets
class Format(str, Enum):
JSON = "json"
CSV = "csv"
XML = "xml"
@tool
def export_data(data: str, format: Format) -> str:
"""Export data in specified format."""
return f"Exported as {format.value}: {data}"
@tool
def import_data(file_path: str, format: Format) -> str:
"""Import data from specified format."""
return f"Imported {format.value} file: {file_path}"Structured Collections
from typing import List, Dict
@tool
def batch_process(items: List[str], config: Dict[str, str]) -> str:
"""Process multiple items with configuration."""
return f"Processed {len(items)} items with config: {config}"Container & Model Types
Pick the annotation that matches the shape of the input you want from the agent.
graph TB
Start[Need a structured input?] --> Many{What shape?}
Many -->|Many of one type| Seq[Sequence or List]
Many -->|No duplicates| SetT[Set]
Many -->|Fixed positions| Tup[Tuple]
Many -->|Key-value pairs| Map[Mapping or Dict]
Many -->|Named fields| Named{Already a class?}
Named -->|Pydantic| Pyd[BaseModel]
Named -->|Dataclass| DC[dataclass]
Named -->|No, just a shape| TD[TypedDict]
classDef start fill:#6366F1,stroke:#7C90A0,color:#fff
classDef decision fill:#F59E0B,stroke:#7C90A0,color:#fff
classDef leaf fill:#10B981,stroke:#7C90A0,color:#fff
class Start start
class Many,Named decision
class Seq,SetT,Tup,Map,Pyd,DC,TD leaffrom typing import TypedDict
from typing_extensions import NotRequired
from praisonaiagents import Agent, tool
class Contact(TypedDict):
name: str
email: str
phone: NotRequired[str]
@tool
def add_contact(contact: Contact) -> str:
"""Add a contact to the address book."""
return f"Added {contact}"
agent = Agent(instructions="You manage contacts", tools=[add_contact])
agent.start("Add Ada Lovelace, ada@example.com")For dataclasses, the schema only includes fields you pass to the constructor. ClassVar and field(init=False) fields are left out. For a TypedDict, the required list follows its Required[...] and NotRequired[...] markers.
Best Practices
Prefer Optional types over bare parameters
Use Optional[int] with a default of None instead of leaving parameters untyped. This tells the agent the parameter can be omitted and what type to use when provided.
# Good
def search(query: str, limit: Optional[int] = None) -> str:
pass
# Avoid
def search(query: str, limit=None) -> str:
passUse Literal for small fixed sets, Enum for reusable choices
Choose Literal[...] when values are unique to one tool. Use Enum when the same choices appear across multiple tools.
# Literal for one-off choices
def analyze(text: str, depth: Literal["surface", "deep"] = "surface"):
pass
# Enum for shared choices
class Priority(str, Enum):
LOW = "low"
HIGH = "high"
def create_task(title: str, priority: Priority):
pass
def update_task(id: str, priority: Priority):
passAvoid Union for unrelated types
Don’t use Union[str, dict] for “either a string or a dict” – the LLM struggles with such choices. Create separate tools instead. This still applies now that object schemas are supported: a union of a dataclass and a string is just as confusing.
# Avoid
def process(input: Union[str, Dict[str, str]]):
pass
# Prefer
def process_text(text: str):
pass
def process_data(data: Dict[str, str]):
passParameterize your collections
Write List[str] instead of bare list so the agent knows what elements to include.
# Good - agent knows to pass strings
def process_items(items: List[str]) -> str:
pass
# Avoid - agent doesn't know element type
def process_items(items: list) -> str:
passPrefer a Pydantic model or dataclass over a wide Dict
Named fields produce properties and required in the schema, so the agent knows exactly what to send. A free-form Dict[str, Any] tells it nothing.
# Good
@dataclass
class Address:
street: str
city: str
def ship(order_id: str, address: Address) -> str:
pass
# Avoid
def ship(order_id: str, address: Dict[str, Any]) -> str:
passWatch for recursive models
A self-referencing class, such as a Node with children: List["Node"], becomes a plain {"type": "object"} where it refers to itself. A Pydantic model with nested $defs also becomes a plain {"type": "object"}. Keep tool inputs flat when you need the agent to see every field.