> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# CSV Agent

> CSV file processing tools for AI agents.

<Note>
  **Prerequisites**

  * Python 3.10 or higher
  * PraisonAI Agents package installed
  * PraisonAI Tools package installed
  * `pandas` package installed
</Note>

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonai_tools import read_csv, write_csv

agent = Agent(name="Analyst", tools=[read_csv, write_csv])
agent.start("Summarise column totals in data/sales.csv")
```

The user points at a CSV; the agent reads, transforms, and writes results with CSV tools.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    U[Input] --> A[Agent]
    A --> T[Tool]
    T --> O[Output]

    classDef agent fill:#8B0000,color:#fff
    classDef tool fill:#189AB4,color:#fff

    class A agent
    class U,O tool
    class T tool
```

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Feature as CSV Agent

    User->>Agent: Request
    Agent->>Feature: Process request
    Feature-->>Agent: Result
    Agent-->>User: Response
```

## CSV Tools

Use CSV Tools to read, write, and manipulate CSV files with AI agents.

<Steps>
  <Step title="Install Dependencies">
    First, install the required packages:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    pip install praisonaiagents praisonai-tools pandas
    ```
  </Step>

  <Step title="Import Components">
    Import the necessary components:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, Task, AgentTeam
    from praisonai_tools import read_csv, write_csv, merge_csv
    ```
  </Step>

  <Step title="Create Agent">
    Create a CSV processing agent:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    csv_agent = Agent(
        name="CSVProcessor",
        role="CSV Processing Specialist",
        goal="Process CSV files efficiently and accurately.",
        backstory="Expert in CSV file manipulation and analysis.",
        tools=[read_csv, write_csv, merge_csv],
        reflection=False
    )
    ```
  </Step>

  <Step title="Define Task">
    Define the CSV processing task:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    csv_task = Task(
        description="Process and analyze CSV data files.",
        expected_output="Processed CSV data with analysis.",
        agent=csv_agent,
        name="csv_processing"
    )
    ```
  </Step>

  <Step title="Run Agent">
    Initialize and run the agent:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    agents = AgentTeam(
        agents=[csv_agent],
        tasks=[csv_task],
        process="sequential"
    )
    agents.start()
    ```
  </Step>
</Steps>

## Understanding CSV Tools

<Card title="What are CSV Tools?" icon="question">
  CSV Tools provide CSV processing capabilities for AI agents:

  * File reading and writing
  * Data parsing
  * Column manipulation
  * Data filtering
  * Format conversion
</Card>

## Key Components

<CardGroup cols={2}>
  <Card title="CSV Agent" icon="user-robot">
    Create specialized CSV agents:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    Agent(tools=[read_csv, write_csv, merge_csv])
    ```
  </Card>

  <Card title="CSV Task" icon="list-check">
    Define CSV tasks:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    Task(description="csv_operation")
    ```
  </Card>

  <Card title="Process Types" icon="arrows-split-up-and-left">
    Sequential or parallel processing:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    process="sequential"
    ```
  </Card>

  <Card title="CSV Options" icon="sliders">
    Customize CSV parameters:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    delimiter=",", header=True
    ```
  </Card>
</CardGroup>

## Available Functions

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai_tools import read_csv
from praisonai_tools import write_csv
from praisonai_tools import merge_csv
```

## Function Details

### read\_csv(filepath: str, encoding: str = 'utf-8', delimiter: str = ',', header: Union\[int, List\[int], None] = 0, usecols: Optional\[List\[str]] = None, dtype: Optional\[Dict\[str, str]] = None, parse\_dates: Optional\[List\[str]] = None, na\_values: Optional\[List\[str]] = None, nrows: Optional\[int] = None)

Reads a CSV file with advanced options:

* Supports multiple encodings (utf-8, ascii, etc.)
* Configurable column delimiter
* Flexible header row handling
* Column selection and data type specification
* Date parsing
* Custom NA/NaN value handling
* Row limit option

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai_tools import read_csv

# Basic usage
data = read_csv("data.csv")

# Advanced usage with options
data = read_csv(
    "data.csv",
    encoding='utf-8',
    delimiter=',',
    header=0,
    usecols=['name', 'age', 'city'],
    dtype={'age': 'int32'},
    parse_dates=['birth_date'],
    na_values=['N/A', 'missing'],
    nrows=1000
)
# Returns: List[Dict[str, Any]]
# Example: [{"name": "Alice", "age": 25, "city": "New York"}, ...]
```

### write\_csv(filepath: str, data: List\[Dict\[str, Any]], encoding: str = 'utf-8', delimiter: str = ',', index: bool = False, header: bool = True, float\_format: Optional\[str] = None, date\_format: Optional\[str] = None, mode: str = 'w')

Writes data to a CSV file with formatting options:

* Supports different encodings
* Configurable delimiter
* Optional row indices
* Optional headers
* Custom float and date formatting
* Append mode support

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai_tools import write_csv

# Basic usage
data = [
    {"name": "Alice", "age": 25, "city": "New York"},
    {"name": "Bob", "age": 30, "city": "San Francisco"}
]
success = write_csv("output.csv", data)

# Advanced usage with formatting
success = write_csv(
    "output.csv",
    data,
    encoding='utf-8',
    delimiter=',',
    index=False,
    header=True,
    float_format='%.2f',
    date_format='%Y-%m-%d',
    mode='w'
)
# Returns: bool (True if successful)
```

### merge\_csv(files: List\[str], output\_file: str, how: str = 'inner', on: Optional\[Union\[str, List\[str]]] = None, suffixes: Optional\[tuple] = None)

Merges multiple CSV files with flexible join options:

* Supports different join types (inner, outer, left, right)
* Merge on single or multiple columns
* Custom suffixes for overlapping columns
* Automatic handling of column name conflicts

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai_tools import merge_csv

# Merge two files on a common column
success = merge_csv(
    files=["employees.csv", "salaries.csv"],
    output_file="merged.csv",
    how='inner',
    on='employee_id'
)

# Advanced merge with multiple columns and custom suffixes
success = merge_csv(
    files=["data1.csv", "data2.csv", "data3.csv"],
    output_file="merged.csv",
    how='outer',
    on=['id', 'department'],
    suffixes=('_2022', '_2023')
)
# Returns: bool (True if successful)
```

## Dependencies

The CSV tools require the following Python packages:

* pandas: For advanced CSV operations and data manipulation

These will be automatically installed when needed.

## Example Agent Configuration

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent
from praisonai_tools import read_csv, write_csv, merge_csv

agent = Agent(
    name="CSVProcessor",
    description="An agent that processes CSV files",
    tools=[read_csv, write_csv, merge_csv]
)
```

## Error Handling

All functions include comprehensive error handling:

* File not found errors
* Permission errors
* Encoding errors
* Data format errors
* Missing dependency errors

Errors are logged and returned in a consistent format:

* Success cases return the expected data type
* Error cases return a dict with an "error" key containing the error message

## Examples

### Basic CSV Processing Agent

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Task, AgentTeam
from praisonai_tools import read_csv, write_csv, merge_csv

# Create CSV agent
csv_agent = Agent(
    name="CSVExpert",
    role="CSV Processing Specialist",
    goal="Process CSV files efficiently and accurately.",
    backstory="Expert in data processing and analysis.",
    tools=[read_csv, write_csv, merge_csv],
    reflection=False
)

# Define CSV task
csv_task = Task(
    description="Process and analyze customer data.",
    expected_output="Customer analysis report.",
    agent=csv_agent,
    name="customer_analysis"
)

# Run agent
agents = AgentTeam(
    agents=[csv_agent],
    tasks=[csv_task],
    process="sequential"
)
agents.start()
```

### Advanced CSV Processing with Multiple Agents

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Task, AgentTeam
from praisonai_tools import read_csv, write_csv, merge_csv

# Create data processing agent
processor_agent = Agent(
    name="Processor",
    role="Data Processor",
    goal="Process CSV data systematically.",
    tools=[read_csv, write_csv, merge_csv],
    reflection=False
)

# Create analysis agent
analysis_agent = Agent(
    name="Analyzer",
    role="Data Analyst",
    goal="Analyze processed CSV data.",
    backstory="Expert in data analysis and reporting.",
    reflection=False
)

# Define tasks
processing_task = Task(
    description="Process customer data files.",
    agent=processor_agent,
    name="data_processing"
)

analysis_task = Task(
    description="Analyze customer trends and patterns.",
    agent=analysis_agent,
    name="data_analysis"
)

# Run agents
agents = AgentTeam(
    agents=[processor_agent, analysis_agent],
    tasks=[processing_task, analysis_task],
    process="sequential"
)
agents.start()
```

## Best Practices

<AccordionGroup>
  <Accordion title="Agent Configuration">
    Configure agents with clear CSV focus:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai_tools import read_csv, write_csv, merge_csv

    Agent(
        name="CSVProcessor",
        role="CSV Processing Specialist",
        goal="Process CSV files accurately and efficiently",
        tools=[read_csv, write_csv, merge_csv]
    )
    ```
  </Accordion>

  <Accordion title="Task Definition">
    Define specific CSV operations:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    Task(
        description="Process customer data and generate reports",
        expected_output="Customer analysis report"
    )
    ```
  </Accordion>
</AccordionGroup>

## Common Patterns

### CSV Processing Pipeline

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Task, AgentTeam
from praisonai_tools import read_csv, write_csv, merge_csv

# Processing agent
processor = Agent(
    name="Processor",
    role="CSV Processor",
    tools=[read_csv, write_csv, merge_csv]
)

# Analysis agent
analyzer = Agent(
    name="Analyzer",
    role="Data Analyst"
)

# Define tasks
process_task = Task(
    description="Process CSV files",
    agent=processor
)

analyze_task = Task(
    description="Analyze processed data",
    agent=analyzer
)

# Run workflow
agents = AgentTeam(
    agents=[processor, analyzer],
    tasks=[process_task, analyze_task]
)
```

## Related

<CardGroup cols={2}>
  <Card title="Custom Tools" icon="wrench" href="/docs/tools/custom">
    Build your own agent tools
  </Card>

  <Card title="Tools Overview" icon="toolbox" href="/docs/tools/tools">
    Browse PraisonAI tool documentation
  </Card>
</CardGroup>
