autogen icon indicating copy to clipboard operation
autogen copied to clipboard

Please add a SQL agent for autogen .

Open mdfahad999 opened this issue 3 years ago • 18 comments

Add a Sql agent in autogen and if we can do it with the userproxyagent or Assistantagent , then do provide the walk through to connect an agent with the sql database and perform complex queries like joins and all.

### Tasks

mdfahad999 avatar Sep 27 '23 15:09 mdfahad999

mysql.connector can be implemented and further code and testing can be done by the autogen module. I am new to this autogen thingy so i might need some assistance, but i know how to work with mysql.connector, so if any experienced dev can guide me, please do so, i would like to take up this isssue

walker-null-byte avatar Sep 27 '23 22:09 walker-null-byte

Should be simple enough to add an extra function that an agent can use.

nengisuls avatar Oct 02 '23 18:10 nengisuls

I've seen some examples about Postgres Agents on Youtube. https://youtu.be/4o8tymMQ5GM

sonichi avatar Oct 22 '23 18:10 sonichi

if Autogen can incorporate pandasai, then it can use various SQL databases like PostgreSQL MySQL Generic SQL Snowflake DataBricks Yahoo Finance through connectors using the method in this documentation: https://docs.pandas-ai.com/en/latest/connectors/

danieltty avatar Nov 02 '23 04:11 danieltty

+1 To this.

tyler-suard-parker avatar Nov 16 '23 21:11 tyler-suard-parker

+1

Namec999 avatar Nov 30 '23 09:11 Namec999

Integrations are welcome.

sonichi avatar Dec 03 '23 16:12 sonichi

Here is the code I have implemented for the SQL Database (Sqlite) Agent in Autogen using GPT3.5/ GPT 4..

https://github.com/mdfahad999/Autogen_sqlite/blob/main/Autogen_sqlite.py

mdfahad999 avatar Dec 30 '23 15:12 mdfahad999

Here is the code I have implemented for the SQL Database (Sqlite) Agent in Autogen using GPT3.5/ GPT 4..

https://github.com/mdfahad999/Autogen_sqlite/blob/main/Autogen_sqlite.py

Is the repo still private? I get a 404. Thanks!

ChristianWeyer avatar Dec 30 '23 15:12 ChristianWeyer

Here is the code I have implemented for the SQL Database (Sqlite) Agent in Autogen using GPT3.5/ GPT 4.. https://github.com/mdfahad999/Autogen_sqlite/blob/main/Autogen_sqlite.py

Is the repo still private? I get a 404. Thanks!

Sorry my bad I made it public now.

mdfahad999 avatar Dec 30 '23 17:12 mdfahad999

#962 is experimenting with this direction.

ekzhu avatar Dec 30 '23 18:12 ekzhu

We are closing this issue due to inactivity; please reopen if the problem persists.

thinkall avatar Jun 18 '24 03:06 thinkall

Hi, I'm sorry, but I just found this, is there already official SQL agent? I couldn't find any except the spider_env notebook.

I made this for postgresql using psycopg. Others seems to use function calling to execute sql statements, but I think using code executor approach is more flexible.

# -*- coding: utf-8 -*-
import json
import re

import psycopg2 as pg2
from psycopg2.extras import RealDictCursor

from textwrap import dedent
from typing import Callable, Dict, List, Optional, Literal, Optional, Union

from autogen import ConversableAgent
from autogen.coding import CodeExecutor, CodeExtractor, MarkdownCodeExtractor, CodeBlock, CodeResult
from autogen.runtime_logging import log_new_agent, logging_enabled

class SqlQueryCodeExecutor(CodeExecutor):
    def __init__(self, env, **kwargs):
        self.dsn = env.cr._cnx.info.dsn_parameters

    @property
    def code_extractor(self) -> CodeExtractor:
        return MarkdownCodeExtractor()

    @staticmethod
    def sanitize_command(code: str) -> None:
        dangerous_patterns = [
            (r"\bdrop\b", "Use of 'drop' query is not allowed."),
            (r"\binsert\b", "Use of 'insert' query is not allowed."),
            (r"\bupdate\b", "Use of 'update' query is not allowed."),
        ]
        for pattern, message in dangerous_patterns:
            if re.search(pattern, code, re.IGNORECASE):
                raise ValueError(f"Potentially dangerous command detected: {message}")

    def execute_code_blocks(self, code_blocks: List[CodeBlock]) -> CodeResult:
        logs_all = ""
        for idx, code_block in enumerate(code_blocks, start=1):
            lang, code = code_block.language, code_block.code
            lang = lang.lower()

            SqlQueryCodeExecutor.sanitize_command(code)

            if lang != "sql":
                logs_all += "\n" + f"Skipping execution: language not specified (code block #{idx})."
                continue

            try:
                with pg2.connect(**self.dsn) as cnn:
                    with cnn.cursor(cursor_factory=RealDictCursor) as cr:
                        cr.execute(code)
                        cres = cr.fetchall()
                        res_json = json.dumps(cres, default=str)
            except Exception as e:
                exitcode = -1
                logs_all += f"\nError: {str(e)}"
                break
            exitcode = 0
            logs_all += res_json
        return CodeResult(exit_code=exitcode, output=logs_all)

    def restart(self) -> None:
        self.engine.dispose()

class UserProxyAgentForSql(ConversableAgent):
    DEFAULT_USER_PROXY_AGENT_DESCRIPTIONS = {
        "ALWAYS": dedent(\
            """An attentive HUMAN user who can answer questions about the task, and can perform tasks such as running sql query
               or inputting command line commands at a Linux terminal and reporting back the execution results."""),
        "TERMINATE": dedent(\
            """A user that can run sql query or input command line commands at a Linux terminal and report back the execution results."""),
        "NEVER": dedent(\
            """An sql bot that performs no other action than running sql query (provided to it's quoted in sql query blocks)."""),
    }

    def __init__(
        self,
        name: str,
        env: object,
        is_termination_msg: Optional[Callable[[Dict], bool]] = None,
        max_consecutive_auto_reply: Optional[int] = None,
        human_input_mode: Literal["ALWAYS", "NEVER", "TERMINATE"] = "NEVER",
        default_auto_reply: Union[str, Dict] = "",
        description: Optional[str] = None,
    ):
        sql_executor = SqlQueryCodeExecutor(env=env)
        super().__init__(
            name=name,
            is_termination_msg=is_termination_msg,
            max_consecutive_auto_reply=max_consecutive_auto_reply,
            human_input_mode=human_input_mode,
            code_execution_config={"executor": sql_executor},
            default_auto_reply=default_auto_reply,
            description=(
                description if description is not None else self.DEFAULT_USER_PROXY_AGENT_DESCRIPTIONS[human_input_mode]
            ),
        )

        if logging_enabled():
            log_new_agent(self, locals())

    def run_code(self, code, **kwargs):
        return -1, "Not supported", None

    def execute_code_blocks(self, code_blocks):
        return -1, "Not supported"

yonitjio avatar Jun 19 '24 18:06 yonitjio

Hi @yonitjio , thank you! Would you like to raise a PR?

thinkall avatar Jun 20 '24 03:06 thinkall

Sure, but I'm gonna need sometime to adjust it and create some example on how to use it.

I just remember the code I posted are specific for Odoo, that's why you see env.cr._cnx.info.dsn_parameters there. I apologize.

I think the naming needs to be changed too, since it's specific for postgresql.

yonitjio avatar Jun 20 '24 18:06 yonitjio

Regarding the postgresql, the pgvector retrieve agent uses psycopg3, so I'll be using that too.

yonitjio avatar Jun 21 '24 16:06 yonitjio

As discussed in PR #3001, we should implement SQL agent with the proper one inside coding module. If anyone has suggestion I think it's better to have it here.

yonitjio avatar Jul 08 '24 01:07 yonitjio

As discussed in PR #3001, we should implement SQL agent with the proper one inside coding module. If anyone has suggestion I think it's better to have it here.

Hi @yonitjio , I think you've already implemented almost everything needed for adding it to coding module. Would you like to have a quick chat in Discord? My username is li_jiang.

thinkall avatar Jul 08 '24 02:07 thinkall