Skip to content

Commit

Permalink
docs: update docs
Browse files Browse the repository at this point in the history
  • Loading branch information
edwardzjl committed Nov 12, 2024
1 parent 98d4a33 commit 20f8472
Show file tree
Hide file tree
Showing 12 changed files with 59 additions and 203 deletions.
199 changes: 1 addition & 198 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,204 +9,7 @@

`tablegpt-agent` is a pre-built agent for TableGPT2 ([huggingface](https://huggingface.co/collections/tablegpt/tablegpt2-67265071d6e695218a7e0376)), a series of LLMs for table-based question answering. This agent is built on top of the [Langgraph](https://github.com/langchain-ai/langgraph) library and provides a user-friendly interface for interacting with TableGPT2.

## Installation

To install `tablegpt-agent`, use the following command:

```sh
pip install tablegpt-agent
```

This package depends on [pybox](https://github.com/edwardzjl/pybox), a Python code sandbox delegator. By default, `pybox` operates in an in-cluster mode. If you wish to run `tablegpt-agent` in a local environment, you need to install an optional dependency:

```sh
pip install pppybox[local]
```

## Quick Start

Before using `tablegpt-agent`, ensure that you have an OpenAI-compatible server set up to host TableGPT2. We recommend using [vllm](https://github.com/vllm-project/vllm) for this:

```sh
python -m vllm.entrypoints.openai.api_server --served-model-name TableGPT2-7B --model path/to/weights
```

> **Note:** For production environments, it’s important to optimize the vllm server configuration. For details, refer to the [vllm documentation on server configuration](https://docs.vllm.ai/en/v0.6.0/serving/openai_compatible_server.html#command-line-arguments-for-the-server).
Once the server is set up, you can use the following code to interact with the TableGPT model:

```python
import asyncio
from datetime import date

from langchain_core.messages import HumanMessage
from langchain_openai import ChatOpenAI
from pybox import LocalPyBoxManager
from tablegpt.agent import create_tablegpt_graph


# tablegpt-agent fully supports async invocation
async def main() -> None:
llm = ChatOpenAI(openai_api_base="YOUR_VLLM_URL", openai_api_key="whatever", model_name="TableGPT2-7B")

# Use local pybox manager for development and testing
pybox_manager = LocalPyBoxManager()

agent = create_tablegpt_graph(
llm=llm,
pybox_manager=pybox_manager,
)

message = HumanMessage(content="Hi")
_input = {
"messages": [message],
"parent_id": "some-parent-id",
"date": date.today(), # noqa: DTZ011
}

async for event in agent.astream_events(
input=_input,
version="v2",
):
print(event) # noqa: T201


asyncio.run(main())
```

In addition to the basic interaction with the agent, you can use `tablegpt-agent` to analyze and process table data. Below is an example where the agent reads a dataset (e.g., a CSV file), performs some analysis, and generates code to answer questions related to the table.

```python
import asyncio
from datetime import date
from typing import TypedDict

from langchain_core.messages import HumanMessage
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.memory import MemorySaver
from pybox import LocalPyBoxManager
from tablegpt.agent import create_tablegpt_graph
from tablegpt.agent.file_reading import Stage


class Attachment(TypedDict):
"""Contains at least one dictionary with the key filename."""

filename: str
"""The dataset uploaded in this session can be a filename, file path, or object storage address."""


# tablegpt-agent fully supports async invocation
async def main() -> None:
llm = ChatOpenAI(openai_api_base="YOUR_VLLM_URL", openai_api_key="whatever", model_name="TableGPT2-7B")

# Use local pybox manager for development and testing
pybox_manager = LocalPyBoxManager()

agent = create_tablegpt_graph(
llm=llm,
pybox_manager=pybox_manager,
# We use MemorySaver as a checkpointer to record memory automatically.
# See <https://langchain-ai.github.io/langgraph/concepts/persistence>
checkpointer=MemorySaver(),
# All code generated in this run will be executed in the kernel with kernel_id 'some-session-id'.
session_id="some-session-id",
)

attachment_msg = HumanMessage(
content="",
# The dataset can be viewed in examples/datasets/titanic.csv.
additional_kwargs={"attachments": [Attachment(filename="titanic.csv")]},
)
await agent.ainvoke(
input={
"entry_message": attachment_msg,
"processing_stage": Stage.UPLOADED,
"messages": [attachment_msg],
"parent_id": "some-parent-id1",
"date": date.today(), # noqa: DTZ011
},
config={
"configurable": {"thread_id": "some-thread-id"},
},
)

human_message = HumanMessage(content="How many men survived?")

async for event in agent.astream_events(
input={
# After using checkpoint, you only need to add new messages here.
"messages": [human_message],
"parent_id": "some-parent-id2",
"date": date.today(), # noqa: DTZ011
},
version="v2",
# We configure the same thread_id to use checkpoints to retrieve the memory of the last run.
config={"configurable": {"thread_id": "some-thread-id"}},
):
print(event) # noqa: T201


asyncio.run(main())
```

<!-- TODO: Add API reference -->

## Components

### Data Analysis Workflow

The Data Analysis workflow is the core functionality of the `tablegpt-agent`. It processes user input and generates appropriate responses. This workflow is similar to those found in most single-agent systems and consists of an agent and various tools. Specifically, the data analysis workflow includes:

- **An Agent Powered by TableGPT2**: This agent performs data analysis tasks.
- **An IPython tool**: This tool executes the generated code within a sandbox environment.

Additionally, the data analysis workflow offers several optional plugins that extend the agent's functionality:

- [VLM](#vlm): A Visual Language Model that can be used to enhance summarization for data visualization tasks.
- [Dataset Retriever](#dataset-retriever): A retriever that fetches information about the dataset, improving the quality and relevance of the generated code.
- [Safaty Guard](#safaty-guard): A safety mechanism that protects the system from toxic inputs.

### File Reading Workflow

We separate the file reading workflow from the data analysis workflow to maintain greater control over how the LLM inspects the dataset files. Typically, if you let the LLM inspect the dataset itself, it uses the `df.head()` function to preview the data. While this is sufficient for basic cases, we have implemented a more structured approach by hard-coding the file reading workflow into several steps:

- `normalization` (optional): For some Excel files, the content may not be 'pandas-friendly'. We include an optional normalization step to transform the Excel content into a more suitable format for pandas.
- `df.info()`: Unlike `df.head()`, `df.info()` provides insights into the dataset's structure, such as the data types of each column and the number of non-null values, which also indicates whether a column contains NaN. This insight helps the LLM understand the structure and quality of the data.
- `df.head()`: The final step displays the first n rows of the dataset, where n is configurable. A larger value for n allows the LLM to glean more information from the dataset; however, too much detail may divert its attention from the primary task.

### Code Execution

The `tablegpt-agent` directs `tablegpt` to generate Python code for data analysis. This code is then executed within a sandbox environment to ensure system security. The execution is managed by the [pybox](https://github.com/edwardzjl/pybox) library, which provides a simple way to run Python code outside the main process.

### Plugins

`tablegpt-agent` provides several plugin interfaces for extending its functionality. These plugins are designed to be easily integrated into the agent and can be used to add new features or modify existing ones. The following plugins are available:

#### VLM

While TableGPT2 excels in data analysis tasks, it currently lacks built-in support for visual modalities. Many data analysis tasks involve visualization, so to address this limitation, we provide an interface for integrating your own Visual Language Model (VLM) plugin.

When the agent performs a visualization task—typically using `matplotlib.pyplot.show`—the VLM will take over from the LLM, offering a more nuanced summarization of the visualization. This approach avoids the common pitfalls of LLMs in visualization tasks, which often either state, "I have plotted the data," or hallucinating the content of the plot.

#### Dataset Retriever

While the [File Reading Workflow](file-reading-workflow) is adequate for most scenarios, it may not always provide the information necessary for the LLM to generate accurate code. Consider the following examples:

- A categorical column in the dataset contains 'foo', 'bar', and 'baz', but 'baz' only appears after approximately 100 rows. In this case, the LLM may not encounter the 'baz' value through `df.head()`.
- The user's query may not align with the dataset's content for several reasons:
- The dataset lacks proper governance. For instance, a cell value might be misspelled from 'foo' to 'fou'.
- There could be a typo in the user's query. For example, if the user queries, "Show me the data for 'fou'," but the dataset contains 'foo' instead.

In such situations, the Dataset Retriever plugin can be utilized to fetch additional information about the dataset from external sources, thereby providing the LLM with more context and improving its ability to generate accurate responses.

#### Safaty Guard

#### Dataset Normalizer

The `Dataset Normalizer` plugin is used to transform 'pandas-unfriendly' datasets (e.g., Excel files that do not follow a standard tabular structure) into a more suitable format for pandas. It is backed by an LLM that generates Python code to convert the original datasets into new ones.

In `tablegpt-agent`, this plugin is used to better format 'pandas-unfriendly' datasets, making them more understandable for the subsequent steps. This plugin is optional; if used, it serves as the very first step in the [File Reading workflow](#file-reading-workflow), easing the difficulity of data analysis in the subsequent workflow.
You can find the full document at <https://tablegpt.github.io/tablegpt-agent/>

## Evaluation

Expand Down
Empty file removed docs/explanation.md
Empty file.
12 changes: 12 additions & 0 deletions docs/explanation/agent-workflow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Agent Workflow

The Agent Workflow is the core functionality of the `tablegpt-agent`. It processes user input and generates appropriate responses. This workflow is similar to those found in most single-agent systems and consists of an agent and various tools. Specifically, the data analysis workflow includes:

- **An Agent Powered by TableGPT2**: This agent performs data analysis tasks.
- **An IPython tool**: This tool executes the generated code within a sandbox environment.

Additionally, TableGPT Agent offers several optional plugins that extend the agent's functionality:

- A Visual Language Model that can be used to enhance summarization for data visualization tasks.
- A retriever that fetches information about the dataset, improving the quality and relevance of the generated code.
- A safety mechanism that protects the system from toxic inputs.
9 changes: 9 additions & 0 deletions docs/explanation/file-reading.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# File Reading

TableGPT Agent separates the file reading workflow from the data analysis workflow to maintain greater control over how the LLM inspects the dataset files. Typically, if you let the LLM inspect the dataset itself, it uses the `df.head()` function to preview the data. While this is sufficient for basic cases, we have implemented a more structured approach by hard-coding the file reading workflow into several steps:

- `normalization` (optional): For some Excel files, the content may not be 'pandas-friendly'. We include an optional normalization step to transform the Excel content into a more suitable format for pandas.
- `df.info()`: Unlike `df.head()`, `df.info()` provides insights into the dataset's structure, such as the data types of each column and the number of non-null values, which also indicates whether a column contains NaN. This insight helps the LLM understand the structure and quality of the data.
- `df.head()`: The final step displays the first n rows of the dataset, where n is configurable. A larger value for n allows the LLM to glean more information from the dataset; however, too much detail may divert its attention from the primary task.

<!-- Need a picture -->
3 changes: 3 additions & 0 deletions docs/howto/incluster-code-execution.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Incluster Code Execution

The `tablegpt-agent` directs `tablegpt` to generate Python code for data analysis. This code is then executed within a sandbox environment to ensure system security. The execution is managed by the [pybox](https://github.com/edwardzjl/pybox) library, which provides a simple way to run Python code outside the main process.
5 changes: 5 additions & 0 deletions docs/howto/normalize-datasets.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Normalize Datasets

The `Dataset Normalizer` plugin is used to transform 'pandas-unfriendly' datasets (e.g., Excel files that do not follow a standard tabular structure) into a more suitable format for pandas. It is backed by an LLM that generates Python code to convert the original datasets into new ones.

In `tablegpt-agent`, this plugin is used to better format 'pandas-unfriendly' datasets, making them more understandable for the subsequent steps. This plugin is optional; if used, it serves as the very first step in the [File Reading workflow](#file-reading-workflow), easing the difficulity of data analysis in the subsequent workflow.
9 changes: 9 additions & 0 deletions docs/howto/retrieval.md
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
# Enhance TableGPT Agent with RAG

While the [File Reading Workflow](file-reading-workflow) is adequate for most scenarios, it may not always provide the information necessary for the LLM to generate accurate code. Consider the following examples:

- A categorical column in the dataset contains 'foo', 'bar', and 'baz', but 'baz' only appears after approximately 100 rows. In this case, the LLM may not encounter the 'baz' value through `df.head()`.
- The user's query may not align with the dataset's content for several reasons:
- The dataset lacks proper governance. For instance, a cell value might be misspelled from 'foo' to 'fou'.
- There could be a typo in the user's query. For example, if the user queries, "Show me the data for 'fou'," but the dataset contains 'foo' instead.

In such situations, the Dataset Retriever plugin can be utilized to fetch additional information about the dataset from external sources, thereby providing the LLM with more context and improving its ability to generate accurate responses.
9 changes: 7 additions & 2 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,17 @@ tablegpt-agent is a pre-built agent for [TableGPT2 (huggingface)](https://huggin
<!-- mkdocs requires 4 space to intent the list -->
- Tutorials
- [Quickstart](tutorials/quickstart.md)
- [Chat on Tabular Data](tutorials/table-chat.md)
- [Chat on Tabular Data](tutorials/chat-on-tabular-data.md)
- [Continue Analysis on Generated Charts](tutorials/continue-analysis-on-generated-charts.md)
- How-To Guides
- [Enhance TableGPT Agent with RAG](howto/retrieval.md)
- [Persist Messages](howto/persist-messages.md)
- [Incluster Code Execution](howto/incluster-code-execution.md)
- [Normalize Datasets](howto/normalize-datasets.md)
- Explanation
- [Agent Workflow](explanation/agent-workflow.md)
- [File Reading](explanation/file-reading.md)
- [Reference](reference.md)
- [Explanation](explanation.md)

## Contributing

Expand Down
File renamed without changes.
5 changes: 5 additions & 0 deletions docs/tutorials/continue-analysis-on-generated-charts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Continue Analysis on Generated Charts

While TableGPT2 excels in data analysis tasks, it currently lacks built-in support for visual modalities. Many data analysis tasks involve visualization, so to address this limitation, we provide an interface for integrating your own Visual Language Model (VLM) plugin.

When the agent performs a visualization task—typically using `matplotlib.pyplot.show`—the VLM will take over from the LLM, offering a more nuanced summarization of the visualization. This approach avoids the common pitfalls of LLMs in visualization tasks, which often either state, "I have plotted the data," or hallucinating the content of the plot.
2 changes: 1 addition & 1 deletion docs/tutorials/quickstart.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ python -m vllm.entrypoints.openai.api_server --served-model-name TableGPT2-7B --
## Chat with TableGPT Agent

To create a `TablegptAgent`, you'll need both `LLM` and `PyBoxManager` components:
To create a `TablegptAgent`, you'll need both an `LLM` and a `PyBoxManager` instance:

```pycon
>>> from langchain_openai import ChatOpenAI
Expand Down
9 changes: 7 additions & 2 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,17 @@ nav:
- Home: index.md
- Tutorials:
- 'Quick Start': tutorials/quickstart.md
- 'Chat on tablular data': tutorials/table-chat.md
- 'Chat on tablular data': tutorials/chat-on-tabular-data.md
- 'Continue Analysis on Generated Charts': tutorials/continue-analysis-on-generated-charts.md
- 'How-To Guides':
- 'Enhance TableGPT Agent with RAG': howto/retrieval.md
- 'Persist Messages': howto/persist-messages.md
- 'Incluster Code Execution': howto/incluster-code-execution.md
- 'Normalize Datasets': howto/normalize-datasets.md
- Reference: reference.md
- Explanation: explanation.md
- Explanation:
- 'Agent Workflow': explanation/agent-workflow.md
- 'File Reading': explanation/file-reading.md

repo_name: tablegpt/tablegpt-agent
repo_url: https://github.com/tablegpt/tablegpt-agent

0 comments on commit 20f8472

Please sign in to comment.