Notebooks
G
Groq
Json Mode Function Calling For Sql

Json Mode Function Calling For Sql

function-calling-sqlmanaged-by-terraformtutorials02-tool-usegroq-api-cookbook

Using JSON Mode and Function Calling for SQL Querying

With the rise of Large Language Models (LLMs), one of the first practical applications has been the "chat with X" app. In this notebook we will explore methods for building "chat with my database" tools with Groq API, exploring benefits and drawbacks of each and leveraging Groq API's JSON mode and tool use feature for function calling.

We will show two methods for using Groq API to query a database, and how leveraging tool use for function calling can improve the predictability and reliability of our outputs. We will use the DuckDB query language on local CSV files in this example, but the general framework could also work against standard data warehouse platforms like BigQuery.

Setup

[1]
[4]

We will use the llama-3.3-70b-versatile model in this demo. Note that you will need a Groq API Key to proceed and can create an account here to generate one for free.

[2]

Text-To-SQL

The first method is a standard Text-To-SQL implementation. With Text-To-SQL, we describe the database schema to the LLM, ask it to answer a question, and let it write an on-the-fly SQL query against the database to answer that question. Let's see how we can use the Groq API to build a Text-To-SQL pipeline:

First, we have our system prompt. A system prompt is an initial input or instruction given to the model, setting the context or specifying the task it needs to perform, essentially guiding the model's response generation. In our case, our system prompt will serve 3 purposes:

  1. Provide the metadata schemas for our database tables
  2. Indicate any relevant context or tips for querying the DuckDB language or our database schema specifically
  3. Define our desired JSON output (note that to use JSON mode, we must include 'JSON' in the prompt)
[3]

Now we will define a text_to_sql function which takes in the system prompt and the user's question and outputs the LLM-generated DuckDB SQL query. Note that since we are using Groq API's JSON mode to format our output, we must indicate our expected JSON output format in either the system or user prompt.

[4]

...and a function for executing the DuckDB query that was generated:

[5]

Now, we can query our database just by asking a question about the data. Here, the LLM generates a valid SQL query that reasonably answers the question:

[6]

Note, however, that due to the non-deterministic nature of LLMs, we cannot guarantee a reliable or consistent result every time. I might get a different result than you, and I might get a totally different query tomorrow. How should "most recent purchases" be defined? Which fields should be returned?

Obviously, this is not ideal for making any kind of data-driven decisions. It's hard enough to land on a reliable source-of-truth data model, and even harder when your AI analyst cannot give you a consistent result. While text-to-SQL can be great for generating ad-hoc insights, the non-determinism feature of LLMs makes raw text-to-SQL an impractical solution for a production environment.

Function Calling for Verified Queries

A different approach is to leverage the LLM to call on pre-vetted queries that can answer a set of questions. Since you wouldn't trust a traditional business intelligence tool without rigorously developed and validated SQL, a "chat with your data" app should be no different. For this example, we will use the verified queries stored here.

[7]
{'most-recent-purchases': {'description': 'Five most recent purchases',
,  'sql': 'SELECT \n       purchases.purchase_date,\n       purchases.product_name,\n       purchases.amount,\n       employees.name\nFROM purchases.csv AS purchases\nJOIN employees.csv AS employees ON purchases.employee_id = employees.employee_id\nORDER BY purchases.purchase_date DESC\nLIMIT 5;\n'},
, 'most-expensive-purchase': {'description': 'Employee with the most expensive purchase',
,  'sql': 'SELECT employees.name AS employee_name,\n      MAX(amount) AS max_purchase_amount\nFROM purchases.csv AS purchases\nJOIN employees.csv AS employees ON purchases.employee_id = employees.employee_id\nGROUP BY employees.name\nORDER BY max_purchase_amount DESC\nLIMIT 1\n'},
, 'number-of-teslas': {'description': 'Number of Teslas purchased',
,  'sql': "SELECT COUNT(*) as number_of_teslas\nFROM purchases.csv AS p\nJOIN employees.csv AS e ON e.employee_id = p.employee_id\nWHERE p.product_name = 'Tesla'\n"},
, 'employees-without-purchases': {'description': 'Employees without a purchase since Feb 1, 2024',
,  'sql': "SELECT employees.name as employees_without_purchases\nFROM employees.csv AS employees\nLEFT JOIN purchases.csv AS purchases ON employees.employee_id = purchases.employee_id\nAND purchases.purchase_date > '2024-02-01'\nWHERE purchases.purchase_id IS NULL\n"}}

Note that each of these queries are stored in yaml files with some additional metadata, like a description. This metadata is important for when the LLM needs to select the most appropriate query for the question at hand.

Now, let's define a new function for executing SQL - this one is tweaked slightly to extract the SQL query from verified_queries_dict inside the function, given a query name:

[8]

Finally, we will write a function to utilize Groq API's Tool Use functionality to call the execute_duckdb_query_function_calling with the appropriate query name. We will provide the query/description mappings from verified_queries_dict in the system prompt so that the LLM can determine which query most appropriately answers the user's question:

[9]

Now, when we ask the LLM "What were the most recent purchases?", we will get the same logic every time:

[10]
Query found:  most-recent-purchases

The downside with using verified queries, of course, is having to write and verify them, which takes away from the magic of watching an LLM generate a SQL query on the fly. But in an environment where reliability is critical, function calling against verified queries is a much more consistent way to chat with your data than Text-To-SQL.

This is a simple example, but you could even take it a step further by defining parameters for each query (that you might find in a WHERE clause), and doing another function call once the verified query is found to find the parameter(s) to inject in the query from the user prompt. Go ahead and try it out!

Conclusion

In this notebook we've explored two techniques for writing and executing SQL with LLMs using Groq API: Text-to-SQL (where the LLM generates SQL in the moment) and Verified Queries (where the LLM determines which verified query is most appropriate for your question and executes it). But perhaps the best approach is a blend - for ad-hoc reporting, there is still a lot of power in Text-to-SQL for quick answers. For user questions where there is no good verified query, you could default to using Text-To-SQL and then add that query to your dictionary of verified queries if it looks good. Either way, using LLMs on top of your data will lead to better and faster insights - just be sure to follow good data governance practices.