|
| 1 | +from dataclasses import dataclass, field |
| 2 | + |
| 3 | +import datasets |
| 4 | +import duckdb |
| 5 | +import pandas as pd |
| 6 | + |
| 7 | +from pydantic_ai import Agent, ModelRetry, RunContext |
| 8 | + |
| 9 | + |
| 10 | +@dataclass |
| 11 | +class AnalystAgentDeps: |
| 12 | + output: dict[str, pd.DataFrame] = field(default_factory=dict) |
| 13 | + |
| 14 | + def store(self, value: pd.DataFrame) -> str: |
| 15 | + """Store the output in deps and return the reference such as Out[1] to be used by the LLM.""" |
| 16 | + ref = f'Out[{len(self.output) + 1}]' |
| 17 | + self.output[ref] = value |
| 18 | + return ref |
| 19 | + |
| 20 | + def get(self, ref: str) -> pd.DataFrame: |
| 21 | + if ref not in self.output: |
| 22 | + raise ModelRetry( |
| 23 | + f'Error: {ref} is not a valid variable reference. Check the previous messages and try again.' |
| 24 | + ) |
| 25 | + return self.output[ref] |
| 26 | + |
| 27 | + |
| 28 | +analyst_agent = Agent( |
| 29 | + 'openai:gpt-4o', |
| 30 | + deps_type=AnalystAgentDeps, |
| 31 | + instructions='You are a data analyst and your job is to analyze the data according to the user request.', |
| 32 | +) |
| 33 | + |
| 34 | + |
| 35 | +@analyst_agent.tool |
| 36 | +def load_dataset( |
| 37 | + ctx: RunContext[AnalystAgentDeps], |
| 38 | + path: str, |
| 39 | + split: str = 'train', |
| 40 | +) -> str: |
| 41 | + """Load the `split` of dataset `dataset_name` from huggingface. |
| 42 | +
|
| 43 | + Args: |
| 44 | + ctx: Pydantic AI agent RunContext |
| 45 | + path: name of the dataset in the form of `<user_name>/<dataset_name>` |
| 46 | + split: load the split of the dataset (default: "train") |
| 47 | + """ |
| 48 | + # begin load data from hf |
| 49 | + builder = datasets.load_dataset_builder(path) # pyright: ignore[reportUnknownMemberType] |
| 50 | + splits: dict[str, datasets.SplitInfo] = builder.info.splits or {} # pyright: ignore[reportUnknownMemberType] |
| 51 | + if split not in splits: |
| 52 | + raise ModelRetry( |
| 53 | + f'{split} is not valid for dataset {path}. Valid splits are {",".join(splits.keys())}' |
| 54 | + ) |
| 55 | + |
| 56 | + builder.download_and_prepare() # pyright: ignore[reportUnknownMemberType] |
| 57 | + dataset = builder.as_dataset(split=split) |
| 58 | + assert isinstance(dataset, datasets.Dataset) |
| 59 | + dataframe = dataset.to_pandas() |
| 60 | + assert isinstance(dataframe, pd.DataFrame) |
| 61 | + # end load data from hf |
| 62 | + |
| 63 | + # store the dataframe in the deps and get a ref like "Out[1]" |
| 64 | + ref = ctx.deps.store(dataframe) |
| 65 | + # construct a summary of the loaded dataset |
| 66 | + output = [ |
| 67 | + f'Loaded the dataset as `{ref}`.', |
| 68 | + f'Description: {dataset.info.description}' |
| 69 | + if dataset.info.description |
| 70 | + else None, |
| 71 | + f'Features: {dataset.info.features!r}' if dataset.info.features else None, |
| 72 | + ] |
| 73 | + return '\n'.join(filter(None, output)) |
| 74 | + |
| 75 | + |
| 76 | +@analyst_agent.tool |
| 77 | +def run_duckdb(ctx: RunContext[AnalystAgentDeps], dataset: str, sql: str) -> str: |
| 78 | + """Run DuckDB SQL query on the DataFrame. |
| 79 | +
|
| 80 | + Note that the virtual table name used in DuckDB SQL must be `dataset`. |
| 81 | +
|
| 82 | + Args: |
| 83 | + ctx: Pydantic AI agent RunContext |
| 84 | + dataset: reference string to the DataFrame |
| 85 | + sql: the query to be executed using DuckDB |
| 86 | + """ |
| 87 | + data = ctx.deps.get(dataset) |
| 88 | + result = duckdb.query_df(df=data, virtual_table_name='dataset', sql_query=sql) |
| 89 | + # pass the result as ref (because DuckDB SQL can select many rows, creating another huge dataframe) |
| 90 | + ref = ctx.deps.store(result.df()) # pyright: ignore[reportUnknownMemberType] |
| 91 | + return f'Executed SQL, result is `{ref}`' |
| 92 | + |
| 93 | + |
| 94 | +@analyst_agent.tool |
| 95 | +def display(ctx: RunContext[AnalystAgentDeps], name: str) -> str: |
| 96 | + """Display at most 5 rows of the dataframe.""" |
| 97 | + dataset = ctx.deps.get(name) |
| 98 | + return dataset.head().to_string() # pyright: ignore[reportUnknownMemberType] |
| 99 | + |
| 100 | + |
| 101 | +if __name__ == '__main__': |
| 102 | + deps = AnalystAgentDeps() |
| 103 | + result = analyst_agent.run_sync( |
| 104 | + user_prompt='Count how many negative comments are there in the dataset `cornell-movie-review-data/rotten_tomatoes`', |
| 105 | + deps=deps, |
| 106 | + ) |
| 107 | + print(result.output) |
0 commit comments