Release of HiveSQL Discord Bot with AI Capabilities

in HiveDevs2 months ago

GM HiveDevs!

In my last post, I introduced the HiveSQL AI Bot, a tool that combines Discord, HiveSQL database querying, and AI capabilities to help users interact with the database through natural language.

This post is to officially release the source code for the community.

I want to focus this post on the code review, to help you navigate in the code and contribute to the project. Fell free to fork it, update and create a PR.

Core Features

  • Natural Language to HiveSQL: Users can ask questions, and the bot converts them to SQL queries
  • Direct SQL Queries: Execute SQL queries directly through Discord commands
  • Database Schema Exploration: View available tables and their structure
  • AI-Powered Help: Get assistance and explanations about queries and errors
  • Rate Limiting: Prevents abuse through cool downs and daily query limits

Architecture Overview

The bot is written in Python, forked from @mengao HiveSQL Discord bot, updated and structured into new components:

Let's build!

Configuration (config.py)

config.py

Well, this is where the code start. After configure the .env file.

Copy the env.sample to .env and input your API Keys and Hive SQL credentials.

This file manages all configuration settings:

  • Discord bot settings
  • Database connection details
  • AI model configuration
  • Query limitations

Discord Bot (HiveSQLBot.py)

HiveSQLBot.py

The main bot class handles Discord interactions, user inputs, command processing and error handling.

It includes the features:

  • Command aliases for user convenience
  • Cool down system for rate limiting
  • Admin privileges with no cool down period
  • Error handling and user feedback

Database Management (database.py)

database.py

Yes, that's right, this file Handles the database interactions.

To avoid consulting the database, we created a cache for the available tables and tables scheme.

The Table scheme has 2 versions, one version with only fields names, and another with full fields types. Made that to do not send to many tokens to LLM, but then figured out another solution to send only the suggestion tables for the query.

  • Connection management
  • Query execution
  • Schema information retrieval
  • Table metadata caching

Command Handler (commands.py)

commands.py

Here is where all bot commands are processed. Also, the AI prompts are here.

Maybe move the prompts to a new file is a good practice to do, but I'll leave it for later.

  • Natural language query processing. Tested in Portuguese and English so far
  • SQL query execution
  • Table information retrieval
  • Help system integration
  • Result formatting

AI Integration

The bot uses AI models, ready to use OpenAI or Groq. Check the .env file and config.py for tweeks.

  • Converting natural language to SQL queries
  • Explaining errors and providing suggestions
  • Helping users understand the database schema
  • Evaluating query complexity and safety

User Interface

The bot uses Discord as interface. Also you can check console for logs and if developing will be useful turn DEBUG_MODE flag on.

Use this commands to interact with the bot.

!aiquery - Generate SQL from natural language
!hivesql - Execute SQL queries directly
!tablelist - List available tables
!tableinfo - Show table schema
!help - Get assistance

Security

Always good to care about security, any suggestions for improvements are welcome. So far we implemented some safety features:

  • Rate limiting for non admin users
  • Daily query limits
  • Error handling
  • Ask AI to not create DELETE, INSERT, UPDATE queries
  • Credential management through environment variables

Future Improvements

Potential enhancements could include:

  • Query result caching
  • More AI provides options
  • Advanced query validation
  • Interactive query building
  • Query history and analytics
  • Plot graphics

Hope this project can be an example in how to combine AI capabilities with database operations in a user friendly interface, making database querying more accessible to users of all skill levels.

Know the HiveSQL database and how hive works help to create the questions for the model.

Final considerations

I noticed that sometimes the AI get confused about tables names, like transfers and transactions or use escrow transfers instead TxTransfer table. Maybe that can be solved with prompt engineering enhancements.

To not use all database scheme that has more than 15k tokens, first we ask model to suggest tables for the query.

Then it try to execute the query 3 times, asking model to fix according to the errors returning from HiveSQL.

Any doubt in about the code or how to install, or even during the setup, feel free to contact me. Open an issue on github can be a good call or find us Discord #hivebr channel.

The Source code available at GitHub: https://github.com/rferrari/hivesql_aibot

Want to test it out in our test server? Let us know.

See you soon.
Let's build!


Sort:  
**Finding posts**: use 'comments' table where 'depth=0'
**Finding comments**: use 'comments' table where 'depth>0'

Much more efficient! 😉

tks man! work like a charm!

muito bom!!

Interesting! So, this script should be added/attached to Discord servers in specific channels by admins to work? You can see I'm not a Discord expert, lol.

Ok. Good question.

You have a simple process to create a discord API key for bot. It's not too difficult.

After getting a discord app token, you add it to project .env

Then you add this app to your server.

Get the channel id and update.end and you should be good to go.

https://discord.com/developers/docs/intro

Sounds interesting. I have written a fair few HiveSQL queries myself and I've not really got into using 'AI' to write code for me yet. It could at least give me the basis of a query. I think it would be good if more people shared queries they found useful.

!BEER

Yeah, you can use !help to help you building up your query.

For more complex ones, better stick with SQL instead AI. It can help you out with some ideas ou fix wrong worries of not executed.

It will explain the error and give you some feedback




Stuck on Hive? Include ! help (without a space) in a post or comment. ⚠️



@HelpHive picked up the ! help command. Some ideas if you need help...

  1. Get help from others: (1) The HelpHive team has been signaled. Wait for a reply from a team member. The team is made of volunteers who will try to answer questions or direct you toward an answer. Please be patient though, they are real people who work, eat, sleep, and lead real lives too! 🙂 The goal is to get back within 24 hours. (2) Join "The Terminal" server in Discord and ask there. The Terminal has friendly people whose top mission is to help Hive users every day.
  2. Help yourself: (1) Do a regular internet search. Be sure to include "Hive" in the query. (2) Let the HiveDesk AI tool by finguru do the heavy work for you. See an example. (3) Check the resources such as HiveWiki.
your help! ⚠️ If you'd consider helping, contact crrdlx in a reply or at one of these contact methods.
HelpHive volunteers: @crrdlx, @stayten, @wesphilbin, @balikis95, @kenechukwu97, @palomap3, @cocacolaron, @fjworld, @funshee - The HelpHive team could use

I like that idea, create a hive sql query collaborative repository

I have some in my Github

thats awesome!

one of my next ideas was to search an plot using pandas!

My #Britlist script is pretty quick using HiveSQL. I used beem before and it took a lot longer.

I can imagine, sql much faster then searching Blockchain

Loading...

It might be worth enforcing the no use of delete/insert/update operations at the database level rather than relying on the AI to not do it, seems like an invite to try and break that guardrail.

Good catch!

more security on that part would be good.

Meanwhile the user don't have those privileges, so, we already have security barrier in that.

I include that cause in case of user try, the AI will not try and will not get an error from database.

Bzzzrrr! "Parabéns @vaipraonde por essa nova liberação! O uso de linguagem natural e inteligência artificial para a HiveSQL é um passo importante para tornar a interação com a blockchain mais atraente e prática. Estou ansiosa para explorar o código e contribuir para o projeto!

#hivebr

AI generated content
Commands: !pixbee stop | !pixbee start | !pixbee price

Obrigado por promover a comunidade Hive-BR em suas postagens.

Vamos seguir fortalecendo a Hive

Metade das recompensas dessa resposta serão destinadas ao autor do post.

Vote no @perfilbrasil para Testemunha Hive.

Congratulations @vaipraonde! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You distributed more than 45000 upvotes.
Your next target is to reach 46000 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP