llm-task-agents


Namellm-task-agents JSON
Version 0.1.5 PyPI version JSON
download
home_pagehttps://github.com/alfredwallace7/llm-task-agents
SummaryA collection of preset efficient prompts packaged into LLM agents.
upload_time2024-10-25 22:39:22
maintainerNone
docs_urlNone
authorAlfred Wallace
requires_python>=3.6
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # LLM Task Agents

A collection of preset efficient prompts packaged into LLM agents.
LLM Task Agents is a Python package for creating and managing different agents that can handle tasks like image and text classification, SQL query generation, and JSON structure management. The agents are built on top of large language models (LLMs) and are designed to be modular and easy to integrate.

## Features

- **Text Classification Agent**: Classifies text into predefined categories using LLM-based prompts.
- **SQL Agent**: Runs SQL queries on databases and returns structured results.
- **JSON Agent**: Handles JSON validation and generation based on predefined schemas.
- **Image Classification Agent**: Classifies images into predefined categories using LLM models.
- **Graph Agent**: Generates graphs using LLM models for a given pandas DataFrame.

## Installation

### From PyPI

You can install the package via pip once it is uploaded to PyPI:

```bash
pip install llm-task-agents
```

## Usage

Below are examples of how to use the different agents provided by the package.

### Text Classification Agent

```python
from llm_task_agents.agent_factory import AgentFactory
import os
from rich.console import Console
from rich.table import Table
from rich.syntax import Syntax

# Initialize the console
console = Console()

# Text classification agent
text = "Je vois la vie en rose."

labels = ["Positive", "Negative"]

agent = AgentFactory.get_agent(
	 agent_type="text", 
	 llm_api_url=os.getenv("OLLAMA_API_BASE"), 
	 model="llama3.2:3b"
)

# Run the agent to classify text
result = agent.run(text=text, labels=labels)

# Display results
console.print("TEXT CLASSIFICATION AGENT")
console.print(f"[bold]Text:[/bold]\n{text}")
console.print(f"[bold]Labels:[/bold]\n{labels}")
console.print(f"[bold]Result:[/bold]\n{result}")
```

### SQL Agent

```python
from llm_task_agents.agent_factory import AgentFactory
import os
from rich.console import Console
from rich.table import Table
from rich.syntax import Syntax

# Initialize the console
console = Console()

# SQL Agent
user_request = "Show total sales per month"

agent = AgentFactory.get_agent(
    agent_type="sql",
    llm_api_url=os.getenv("OLLAMA_API_BASE"),
    model="llama3.2:3b",
    database_driver="mysql",
    database_username=os.getenv("MYSQL_USER", "root"),
    database_password=os.getenv("MYSQL_PASSWORD", "password"),
    database_host=os.getenv("MYSQL_HOST", "localhost"),
    database_port="3306",
    database_name="chinook",
    # debug=True,
)

# Get the list of tables
tables = agent.list_tables()

# Generate the SQL query
sql_query = agent.run(
    user_request=user_request,
    tables=tables,
    allowed_statements=["SELECT"]
)

# Function to display tables using rich Table
def display_tables(tables):
    table = Table(title="Database Tables")
    table.add_column("Table Name", justify="left", style="cyan", no_wrap=True)

    for table_name in tables:
        table.add_row(table_name)

    console.print(table)

# Display results
console.print("SQL AGENT")
display_tables(tables)
console.print(f"[bold]User Request:[/bold] {user_request}")

if sql_query:
    console.print("[bold green]Valid SQL Query:[/bold green]")
    syntax = Syntax(sql_query, "sql", theme="monokai", line_numbers=True)
    console.print(syntax)
else:
    console.print("[red]Failed to generate a valid SQL query.[/red]")
```

### JSON Agent

```python
from llm_task_agents.agent_factory import AgentFactory
import os
from rich.console import Console
import json

# Initialize the console
console = Console()

# JSON Agent
task = "Create 3 detailed, realistic character personas for a fantasy adventure game."

structure = {
    "personas": [
        {
            "first_name": "string", 
            "last_name": "string", 
            "age": "int", 
            "gender": "string", 
            "job": "string", 
            "description": "string"
        }
    ]
}

agent = AgentFactory.get_agent(
     agent_type="json", 
     llm_api_url=os.getenv("OLLAMA_API_BASE"), 
     model="llama3.2:3b"
)

# Run the agent to generate JSON
personas = agent.run(
    task=task,
    structure=structure
)

# Display results
console.print("JSON AGENT")
console.print(f"[bold]Task:[/bold]\n{task}")
console.print(f"[bold]Structure:[/bold]\n{json.dumps(structure, indent=4)}")
console.print(f"[bold]JSON:[/bold]\n{json.dumps(personas, indent=4)}")
```

### Image Classification Agent

```python
from llm_task_agents.agent_factory import AgentFactory
import os
from rich.console import Console
from PIL import Image
import requests
import tempfile

# Initialize the console
console = Console()

# Image classification agent
image_url = "https://image.pollinations.ai/prompt/Grape"
image = Image.open(requests.get(image_url, stream=True).raw)

# Create a temporary file
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp_file:
    image.save(tmp_file.name)
    image_path = tmp_file.name

labels = ["Apple", "Lemon", "Cherry", "Orange", "Banana", "Pineapple", "Melon", "Watermelon", "Peach", "Grape"]

agent = AgentFactory.get_agent(
     agent_type="image", 
     llm_api_url=os.getenv("OLLAMA_API_BASE"), 
     model="minicpm-v:8b-2.6-fp16"
)

# Run the agent to classify image
label = agent.run(image_path=image_path, labels=labels)

# Display results
console.print("IMAGE CLASSIFICATION AGENT")
console.print(f"[bold]Image:[/bold]\n{image_path}")
console.print(f"[bold]Labels:[/bold]\n{labels}")
console.print(f"[bold]Result:[/bold]\n{label}")
```

### Graph Agent

```python
from llm_task_agents.agent_factory import AgentFactory
import os
from rich.console import Console
from rich.table import Table
from rich.syntax import Syntax
import pandas as pd
import numpy as np
from PIL import Image
import io
import base64

# Initialize the console
console = Console()

# Generating a fake sales dataframe
np.random.seed(42)

# Creating a fake DataFrame with sales data
df_sales = pd.DataFrame({
	'Date': pd.date_range(start='2023-01-01', periods=100, freq='D'),
	'Product': np.random.choice(['Product A', 'Product B', 'Product C'], size=100),
	'Region': np.random.choice(['North', 'South', 'East', 'West'], size=100),
	'Units Sold': np.random.randint(1, 100, size=100),
	'Price per Unit': np.random.uniform(5.0, 50.0, size=100),
	'Total Sales': lambda x: df_sales['Units Sold'] * df_sales['Price per Unit']
})

# Calculating total sales
df_sales['Total Sales'] = df_sales['Units Sold'] * df_sales['Price per Unit']

agent = AgentFactory.get_agent(
	 agent_type="graph", 
	 llm_api_url=os.getenv("OLLAMA_API_BASE"), 
	 model="llama3.2:3b"
)

# Run the agent to classify text
user_request = "Average Units Sold per Product",
img_base64, graph_title = agent.run(user_request=user_request, df=df)

# Display results
console.print("GRAPH AGENT")
console.print(f"[bold]User Request:[/bold]\n{user_request}")
console.print(f"[bold]Graph title:[/bold]\n{graph_title}")

# convert base64 to image
image = Image.open(io.BytesIO(base64.b64decode(img_base64)))

# display image
image.show()
```

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Acknowledgments

- Built using the `ollama` LLM API.
- SQL query management with SQLAlchemy.
- Graphs with plotly.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/alfredwallace7/llm-task-agents",
    "name": "llm-task-agents",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": null,
    "keywords": null,
    "author": "Alfred Wallace",
    "author_email": "alfred.wallace@netcraft.fr",
    "download_url": "https://files.pythonhosted.org/packages/c7/68/46a2a7485a8d25c819d5728c0c70eb78439901b7d81ad1a196f7876397d0/llm-task-agents-0.1.5.tar.gz",
    "platform": null,
    "description": "# LLM Task Agents\r\n\r\nA collection of preset efficient prompts packaged into LLM agents.\r\nLLM Task Agents is a Python package for creating and managing different agents that can handle tasks like image and text classification, SQL query generation, and JSON structure management. The agents are built on top of large language models (LLMs) and are designed to be modular and easy to integrate.\r\n\r\n## Features\r\n\r\n- **Text Classification Agent**: Classifies text into predefined categories using LLM-based prompts.\r\n- **SQL Agent**: Runs SQL queries on databases and returns structured results.\r\n- **JSON Agent**: Handles JSON validation and generation based on predefined schemas.\r\n- **Image Classification Agent**: Classifies images into predefined categories using LLM models.\r\n- **Graph Agent**: Generates graphs using LLM models for a given pandas DataFrame.\r\n\r\n## Installation\r\n\r\n### From PyPI\r\n\r\nYou can install the package via pip once it is uploaded to PyPI:\r\n\r\n```bash\r\npip install llm-task-agents\r\n```\r\n\r\n## Usage\r\n\r\nBelow are examples of how to use the different agents provided by the package.\r\n\r\n### Text Classification Agent\r\n\r\n```python\r\nfrom llm_task_agents.agent_factory import AgentFactory\r\nimport os\r\nfrom rich.console import Console\r\nfrom rich.table import Table\r\nfrom rich.syntax import Syntax\r\n\r\n# Initialize the console\r\nconsole = Console()\r\n\r\n# Text classification agent\r\ntext = \"Je vois la vie en rose.\"\r\n\r\nlabels = [\"Positive\", \"Negative\"]\r\n\r\nagent = AgentFactory.get_agent(\r\n\t agent_type=\"text\", \r\n\t llm_api_url=os.getenv(\"OLLAMA_API_BASE\"), \r\n\t model=\"llama3.2:3b\"\r\n)\r\n\r\n# Run the agent to classify text\r\nresult = agent.run(text=text, labels=labels)\r\n\r\n# Display results\r\nconsole.print(\"TEXT CLASSIFICATION AGENT\")\r\nconsole.print(f\"[bold]Text:[/bold]\\n{text}\")\r\nconsole.print(f\"[bold]Labels:[/bold]\\n{labels}\")\r\nconsole.print(f\"[bold]Result:[/bold]\\n{result}\")\r\n```\r\n\r\n### SQL Agent\r\n\r\n```python\r\nfrom llm_task_agents.agent_factory import AgentFactory\r\nimport os\r\nfrom rich.console import Console\r\nfrom rich.table import Table\r\nfrom rich.syntax import Syntax\r\n\r\n# Initialize the console\r\nconsole = Console()\r\n\r\n# SQL Agent\r\nuser_request = \"Show total sales per month\"\r\n\r\nagent = AgentFactory.get_agent(\r\n    agent_type=\"sql\",\r\n    llm_api_url=os.getenv(\"OLLAMA_API_BASE\"),\r\n    model=\"llama3.2:3b\",\r\n    database_driver=\"mysql\",\r\n    database_username=os.getenv(\"MYSQL_USER\", \"root\"),\r\n    database_password=os.getenv(\"MYSQL_PASSWORD\", \"password\"),\r\n    database_host=os.getenv(\"MYSQL_HOST\", \"localhost\"),\r\n    database_port=\"3306\",\r\n    database_name=\"chinook\",\r\n    # debug=True,\r\n)\r\n\r\n# Get the list of tables\r\ntables = agent.list_tables()\r\n\r\n# Generate the SQL query\r\nsql_query = agent.run(\r\n    user_request=user_request,\r\n    tables=tables,\r\n    allowed_statements=[\"SELECT\"]\r\n)\r\n\r\n# Function to display tables using rich Table\r\ndef display_tables(tables):\r\n    table = Table(title=\"Database Tables\")\r\n    table.add_column(\"Table Name\", justify=\"left\", style=\"cyan\", no_wrap=True)\r\n\r\n    for table_name in tables:\r\n        table.add_row(table_name)\r\n\r\n    console.print(table)\r\n\r\n# Display results\r\nconsole.print(\"SQL AGENT\")\r\ndisplay_tables(tables)\r\nconsole.print(f\"[bold]User Request:[/bold] {user_request}\")\r\n\r\nif sql_query:\r\n    console.print(\"[bold green]Valid SQL Query:[/bold green]\")\r\n    syntax = Syntax(sql_query, \"sql\", theme=\"monokai\", line_numbers=True)\r\n    console.print(syntax)\r\nelse:\r\n    console.print(\"[red]Failed to generate a valid SQL query.[/red]\")\r\n```\r\n\r\n### JSON Agent\r\n\r\n```python\r\nfrom llm_task_agents.agent_factory import AgentFactory\r\nimport os\r\nfrom rich.console import Console\r\nimport json\r\n\r\n# Initialize the console\r\nconsole = Console()\r\n\r\n# JSON Agent\r\ntask = \"Create 3 detailed, realistic character personas for a fantasy adventure game.\"\r\n\r\nstructure = {\r\n    \"personas\": [\r\n        {\r\n            \"first_name\": \"string\", \r\n            \"last_name\": \"string\", \r\n            \"age\": \"int\", \r\n            \"gender\": \"string\", \r\n            \"job\": \"string\", \r\n            \"description\": \"string\"\r\n        }\r\n    ]\r\n}\r\n\r\nagent = AgentFactory.get_agent(\r\n     agent_type=\"json\", \r\n     llm_api_url=os.getenv(\"OLLAMA_API_BASE\"), \r\n     model=\"llama3.2:3b\"\r\n)\r\n\r\n# Run the agent to generate JSON\r\npersonas = agent.run(\r\n    task=task,\r\n    structure=structure\r\n)\r\n\r\n# Display results\r\nconsole.print(\"JSON AGENT\")\r\nconsole.print(f\"[bold]Task:[/bold]\\n{task}\")\r\nconsole.print(f\"[bold]Structure:[/bold]\\n{json.dumps(structure, indent=4)}\")\r\nconsole.print(f\"[bold]JSON:[/bold]\\n{json.dumps(personas, indent=4)}\")\r\n```\r\n\r\n### Image Classification Agent\r\n\r\n```python\r\nfrom llm_task_agents.agent_factory import AgentFactory\r\nimport os\r\nfrom rich.console import Console\r\nfrom PIL import Image\r\nimport requests\r\nimport tempfile\r\n\r\n# Initialize the console\r\nconsole = Console()\r\n\r\n# Image classification agent\r\nimage_url = \"https://image.pollinations.ai/prompt/Grape\"\r\nimage = Image.open(requests.get(image_url, stream=True).raw)\r\n\r\n# Create a temporary file\r\nwith tempfile.NamedTemporaryFile(suffix=\".png\", delete=False) as tmp_file:\r\n    image.save(tmp_file.name)\r\n    image_path = tmp_file.name\r\n\r\nlabels = [\"Apple\", \"Lemon\", \"Cherry\", \"Orange\", \"Banana\", \"Pineapple\", \"Melon\", \"Watermelon\", \"Peach\", \"Grape\"]\r\n\r\nagent = AgentFactory.get_agent(\r\n     agent_type=\"image\", \r\n     llm_api_url=os.getenv(\"OLLAMA_API_BASE\"), \r\n     model=\"minicpm-v:8b-2.6-fp16\"\r\n)\r\n\r\n# Run the agent to classify image\r\nlabel = agent.run(image_path=image_path, labels=labels)\r\n\r\n# Display results\r\nconsole.print(\"IMAGE CLASSIFICATION AGENT\")\r\nconsole.print(f\"[bold]Image:[/bold]\\n{image_path}\")\r\nconsole.print(f\"[bold]Labels:[/bold]\\n{labels}\")\r\nconsole.print(f\"[bold]Result:[/bold]\\n{label}\")\r\n```\r\n\r\n### Graph Agent\r\n\r\n```python\r\nfrom llm_task_agents.agent_factory import AgentFactory\r\nimport os\r\nfrom rich.console import Console\r\nfrom rich.table import Table\r\nfrom rich.syntax import Syntax\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport io\r\nimport base64\r\n\r\n# Initialize the console\r\nconsole = Console()\r\n\r\n# Generating a fake sales dataframe\r\nnp.random.seed(42)\r\n\r\n# Creating a fake DataFrame with sales data\r\ndf_sales = pd.DataFrame({\r\n\t'Date': pd.date_range(start='2023-01-01', periods=100, freq='D'),\r\n\t'Product': np.random.choice(['Product A', 'Product B', 'Product C'], size=100),\r\n\t'Region': np.random.choice(['North', 'South', 'East', 'West'], size=100),\r\n\t'Units Sold': np.random.randint(1, 100, size=100),\r\n\t'Price per Unit': np.random.uniform(5.0, 50.0, size=100),\r\n\t'Total Sales': lambda x: df_sales['Units Sold'] * df_sales['Price per Unit']\r\n})\r\n\r\n# Calculating total sales\r\ndf_sales['Total Sales'] = df_sales['Units Sold'] * df_sales['Price per Unit']\r\n\r\nagent = AgentFactory.get_agent(\r\n\t agent_type=\"graph\", \r\n\t llm_api_url=os.getenv(\"OLLAMA_API_BASE\"), \r\n\t model=\"llama3.2:3b\"\r\n)\r\n\r\n# Run the agent to classify text\r\nuser_request = \"Average Units Sold per Product\",\r\nimg_base64, graph_title = agent.run(user_request=user_request, df=df)\r\n\r\n# Display results\r\nconsole.print(\"GRAPH AGENT\")\r\nconsole.print(f\"[bold]User Request:[/bold]\\n{user_request}\")\r\nconsole.print(f\"[bold]Graph title:[/bold]\\n{graph_title}\")\r\n\r\n# convert base64 to image\r\nimage = Image.open(io.BytesIO(base64.b64decode(img_base64)))\r\n\r\n# display image\r\nimage.show()\r\n```\r\n\r\n## License\r\n\r\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\r\n\r\n## Acknowledgments\r\n\r\n- Built using the `ollama` LLM API.\r\n- SQL query management with SQLAlchemy.\r\n- Graphs with plotly.\r\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A collection of preset efficient prompts packaged into LLM agents.",
    "version": "0.1.5",
    "project_urls": {
        "Homepage": "https://github.com/alfredwallace7/llm-task-agents"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "bae27b51a3a7d31dc8d18b382191c8a8b2f06603552f97c54be77d8868c6de68",
                "md5": "17c75f765737aef463b9bcd7ccf76018",
                "sha256": "ea21aa001cd4b9969260e2d1701e7f2082cedbf466ba83c22bfb7cfd11d3296f"
            },
            "downloads": -1,
            "filename": "llm_task_agents-0.1.5-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "17c75f765737aef463b9bcd7ccf76018",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 25464,
            "upload_time": "2024-10-25T22:39:20",
            "upload_time_iso_8601": "2024-10-25T22:39:20.858467Z",
            "url": "https://files.pythonhosted.org/packages/ba/e2/7b51a3a7d31dc8d18b382191c8a8b2f06603552f97c54be77d8868c6de68/llm_task_agents-0.1.5-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c76846a2a7485a8d25c819d5728c0c70eb78439901b7d81ad1a196f7876397d0",
                "md5": "66643e1f092757d9282f60e6193a39c9",
                "sha256": "7ee8f694684e0ddd228b225cc8c926df3ab2296ffeddbff2ce5f59608cb557c5"
            },
            "downloads": -1,
            "filename": "llm-task-agents-0.1.5.tar.gz",
            "has_sig": false,
            "md5_digest": "66643e1f092757d9282f60e6193a39c9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 19104,
            "upload_time": "2024-10-25T22:39:22",
            "upload_time_iso_8601": "2024-10-25T22:39:22.289435Z",
            "url": "https://files.pythonhosted.org/packages/c7/68/46a2a7485a8d25c819d5728c0c70eb78439901b7d81ad1a196f7876397d0/llm-task-agents-0.1.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-25 22:39:22",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "alfredwallace7",
    "github_project": "llm-task-agents",
    "github_not_found": true,
    "lcname": "llm-task-agents"
}
        
Elapsed time: 0.34782s