Disclaimer
De aandelengegevens die in dit artikel worden gebruikt, zijn volledig fictief. Ze zijn puur voor demonstratiedoeleinden. Gebruik deze gegevens alstublieft niet voor het nemen van financiële beslissingen.
In een eerdere artikel zagen we de voordelen van het lokaal gebruiken van Ollama voor een RAG-toepassing. In dit artikel zullen we onze evaluatie van Ollama uitbreiden door het testen van natuurlijke taal (NT) queries tegen een database systeem, met behulp van LangChain’s SQLDatabaseToolkit
. SQL zal dienen als het basissysteem voor vergelijking terwijl we de kwaliteit van de resultaten verkend die worden geleverd door OpenAI en Ollama.
De notebook bestanden die in dit artikel worden gebruikt, zijn beschikbaar op GitHub.
Introductie
LangChain’s SQLDatabaseToolkit
is een krachtige tool die is ontworpen om NT-verwerkingsmogelijkheden te integreren met relationele databasesystemen. Het stelt gebruikers in staat om databases te bevragen met behulp van NT-invoer, waarbij de mogelijkheden van grote taalmodellen (LLM’s) worden gebruikt om dynamisch SQL-query’s te genereren. Dit maakt het vooral handig voor toepassingen waar niet-technische gebruikers of geautomatiseerde systemen moeten interageren met gestructureerde data.
Een aantal LLM’s worden goed ondersteund door LangChain. LangChain biedt ook ondersteuning voor Ollama. In dit artikel zullen we evalueren hoe goed LangChain integreert met Ollama en de haalbaarheid van het gebruik van de SQLDatabaseToolkit
in een lokale opstelling.
Maak een SingleStore Cloud-account
Een vorig artikel toonde de stappen om een gratis SingleStore Cloud-account aan te maken. We zullen de Gratis Gedeelde Laag gebruiken.
Het selecteren van de Starter Werkruimte > Verbinden > CLI-client zal ons de benodigde details geven, zoals gebruikersnaam
, wachtwoord
, host
, poort
en database
, die we later nodig hebben.
Database Tabellen Maken
Voor onze testomgeving zullen we SingleStore draaiend in de Cloud gebruiken als ons doeldatabasesysteem, en we zullen veilig verbinding maken met deze omgeving met behulp van Jupyter-notebooks die draaien op een lokaal systeem.
Vanuit het linkernavigatiepaneel in het SingleStore-cloudportaal zullen we ONTWIKKELEN > Data Studio > SQL-editor openen. We zullen drie tabellen maken, zoals hieronder:
CREATE TABLE IF NOT EXISTS tick (
symbol VARCHAR(10),
ts DATETIME SERIES TIMESTAMP,
open NUMERIC(18, 2),
high NUMERIC(18, 2),
low NUMERIC(18, 2),
price NUMERIC(18, 2),
volume INT,
KEY(ts)
);
CREATE TABLE IF NOT EXISTS portfolio (
symbol VARCHAR(10),
shares_held INT,
purchase_date DATE,
purchase_price NUMERIC(18, 2)
);
CREATE TABLE IF NOT EXISTS stock_sentiment (
headline VARCHAR(250),
positive FLOAT,
negative FLOAT,
neutral FLOAT,
url TEXT,
publisher VARCHAR(30),
ts DATETIME,
symbol VARCHAR(10)
);
We zullen de portfolio
tabel laden met de volgende fictieve gegevens:
INSERT INTO portfolio (symbol, shares_held, purchase_date, purchase_price) VALUES
('AAPL', 100, '2022-01-15', 150.25),
('MSFT', 50, '2021-12-10', 305.50),
('GOOGL', 25, '2021-11-05', 2800.75),
('AMZN', 10, '2020-07-20', 3200.00),
('TSLA', 40, '2022-02-18', 900.60),
('NFLX', 15, '2021-09-01', 550.00);
Voor de stock_sentiment
tabel, zullen we het bestand stock_sentiment.sql.zip downloaden en uitpakken. We zullen de gegevens in de tabel laden met behulp van een MySQL-client, zoals hieronder:
mysql -u "<username>" -p"<password>" -h "<host>" -P <port> -D <database> < stock_sentiment.sql
We zullen de waarden gebruiken voor <gebruikersnaam>
, <wachtwoord>
, <host>
, <poort>
en <database>
die we eerder hebben opgeslagen.
Tenslotte, voor de tick
tabel, zullen we een pipeline maken:
CREATE PIPELINE tick
AS LOAD DATA KAFKA 'public-kafka.memcompute.com:9092/stockticker'
BATCH_INTERVAL 45000
INTO TABLE tick
FIELDS TERMINATED BY ','
(symbol,ts,open,high,low,price,volume);
We zullen aanpassen om de vroegste gegevens te verkrijgen:
ALTER PIPELINE tick SET OFFSETS EARLIEST;
En testen het proces:
TEST PIPELINE tick LIMIT 1;
Voorbeeld output:
+--------+---------------------+--------+--------+--------+--------+--------+
| symbol | ts | open | high | low | price | volume |
+--------+---------------------+--------+--------+--------+--------+--------+
| MMM | 2025-01-23 21:40:32 | 178.34 | 178.43 | 178.17 | 178.24 | 38299 |
+--------+---------------------+--------+--------+--------+--------+--------+
En dan zullen we het proces starten:
START PIPELINE tick;
Na enkele minuten zullen we controleren hoeveel gegevens tot nu toe geladen zijn:
SELECT COUNT(*)
FROM tick;
Lokale testomgeving
Uit een vorig artikel, zullen we dezelfde stappen volgen om onze lokale testomgeving op te zetten zoals beschreven in deze secties:
- Inleiding. Gebruik een virtuele machine of
venv
. - Maak een SingleStore Cloud account aan. Deze stap is hierboven voltooid.
- Maak een database aan. De gratis gedeelde laag biedt al een database en we moeten alleen de naam van de database noteren.
- Installeer Jupyter.
Plattekst
pip install notebook
- Installeer Ollama.
Plattekst
curl -fsSL https://ollama.com/install.sh | sh
- Omgevingsvariabelen.
Plattekst:
@ : / “” data-lang=”text/plain”> export SINGLESTOREDB_URL="<gebruikersnaam>:<wachtwoord>@<host>:<poort>/<database>"
Vervang
<gebruikersnaam>
,<wachtwoord>
,<host>
,<poort>
en<database>
door de waarden voor jouw omgeving.Plattekst“” data-lang=”text/plain”>export OPENAI_API_KEY="<OpenAI API-sleutel>"
Vervang
<OpenAI API-sleutel>
door jouw sleutel. - Start Jupyter.
Plain Text
jupyter notebook
We zullen de Jupyter-notebooks van GitHub gebruiken. Deze notebooks zijn geconfigureerd om OpenAI en Ollama te gebruiken. Voor Ollama zullen we een van de LLM’s gebruiken die worden vermeld bij Ondersteuning van tools. We zullen de volgende vier queries testen.
Eerste Query
SQL
SELECT symbol, (MAX(high) - MIN(low)) AS volatility
FROM tick
GROUP BY symbol
ORDER BY volatility ASC
LIMIT 1;
Natuurlijke Taal
"For each stock symbol, calculate the volatility as the difference\n"
"between the highest recorded price and the lowest recorded price over time.\n"
"Which stock symbol has the least volatility?"
Resultaten
SQL
+--------+------------+
| symbol | volatility |
+--------+------------+
| FTR | 0.55 |
+--------+------------+
OpenAI
The stock symbol with the least volatility is FTR, with a volatility of 0.55.
Ollama
To find the stock with the highest price, we need to compare the prices of all the given stocks and find the maximum value. However, I don't have real-time access to financial data or the ability to execute code that interacts with external APIs. Therefore, I can't directly calculate the highest price from this list.
However, if you provide me with a specific date or time range, I can help you find the stock with the highest price during that period. For example, if you want to know the stock with the highest price on a particular day in the past, I can assist you with that.
If you're looking for the current highest-priced stock, I recommend checking a financial news website or an API that provides real-time stock data, such as Yahoo Finance, Google Finance, or a service like Alpha Vantage or Finnhub.io. These platforms can give you the most up-to-date information on stock prices.`
For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE
Tweede Query
SQL
SELECT COUNT(*)
FROM tick;
Natuurlijke Taal
"How many rows are in the tick table?"
Resultaten
SQL
+----------+
| COUNT(*) |
+----------+
| 22367162 |
+----------+
OpenAI
There are 22,367,162 rows in the tick table.
Ollama
The "tick" table has 3 rows.
Derde Query
SQL
-- Stap 1: Krijg de laatste prijs voor elk symbool
WITH latest_prices AS (
SELECT symbol, price
FROM tick t1
WHERE ts = (
SELECT MAX(ts)
FROM tick t2
WHERE t2.symbol = t1.symbol
)
)
-- Stap 2: Bereken de totale portefeuillewaarde
SELECT SUM(p.shares_held * lp.price) AS total_portfolio_value
FROM portfolio p, latest_prices lp
WHERE p.symbol = lp.symbol;
Natuurlijke Taal
"Taking all the stock symbols from the portfolio table,\n"
"and using the latest value for each stock symbol from the tick table,\n"
"calculate the grand total value of all the shares listed in the portfolio table."
Resultaten
SQL
+-----------------------+
| total_portfolio_value |
+-----------------------+
| 44540.60 |
+-----------------------+
OpenAI
$44,540.60
Ollama
I don't know. The provided SQL query does not contain any of the common mistakes listed. It uses the correct join conditions, functions, and data types. The query also properly quotes identifiers and uses the correct number of arguments for functions. Therefore, no changes are needed. However, without access to the actual database schema and table data, I cannot provide a specific answer to the question.
Vierde Query
SQL
SELECT
(
SELECT ts
FROM stock_sentiment
WHERE symbol = 'AAPL'
ORDER BY positive DESC
LIMIT 1
) AS sentiment_date,
(
SELECT positive
FROM stock_sentiment
WHERE symbol = 'AAPL'
ORDER BY positive DESC
LIMIT 1
) AS most_positive_sentiment,
(
SELECT price
FROM tick
WHERE symbol = 'AAPL'
ORDER BY ts DESC
LIMIT 1
) AS current_best_price;
Natuurlijke Taal
"Using the symbol AAPL, show me the date and the most\n"
"positive sentiment in the stock sentiment table and the\n"
"current best price for this symbol from the tick table."
Resultaten
SQL
+---------------------+-------------------------+--------------------+
| sentiment_date | most_positive_sentiment | current_best_price |
+---------------------+-------------------------+--------------------+
| 2020-05-28 00:00:00 | 0.331509 | 116.27 |
+---------------------+-------------------------+--------------------+
OpenAI
On 2020-05-28, the most positive sentiment for AAPL was 0.331509, and the current best price for AAPL is 116.27.
Ollama
The provided list contains decimal numbers, which appear to be the results of some kind of experiment or analysis. Without additional context, it's difficult to determine the exact nature of these results. However, we can observe that the majority of the numbers are between 116.85 and 117.27, with a few outliers at 115.99 and 117.30. The smallest number in the list is 115.99, and the largest is 117.30.`
For troubleshooting, visit: https://python.langchain.com/docs/troubleshooting/errors/OUTPUT_PARSING_FAILURE
Samenvatting
Bij het analyseren van de resultaten zien we dat SQL en OpenAI consistente resultaten opleveren bij alle vier vragen. Echter, Ollama vertoont duidelijke problemen. Een discussiedraad op GitHub benadrukt dat hoewel een LLM-model toolaanroeping zou moeten ondersteunen, deze functionaliteit niet standaard beschikbaar is in Ollama.
Als het je lukt om deze LangChain-functionaliteit werkend te krijgen met Ollama in een van de ondersteunde LLM’s, stuur me dan een bericht, en ik zal het artikel bijwerken en je hulp erkennen.
Source:
https://dzone.com/articles/openai-vs-ollama-langchain-sqldatabasetoolkit