OpenAI vs Ollama mit LangChain’s SQLDatabaseToolkit

Haftungsausschluss

Die in diesem Artikel verwendeten Aktiendaten sind vollständig fiktiv. Sie dienen ausschließlich zu Demonstrationszwecken. Bitte verwenden Sie diese Daten nicht für finanzielle Entscheidungen.

In einem vorherigen Artikel haben wir die Vorteile der Verwendung von Ollama lokal für eine RAG-Anwendung gesehen. In diesem Artikel werden wir unsere Bewertung von Ollama erweitern, indem wir natürliche Sprach (NL)-Abfragen gegen ein Datenbanksystem testen, unter Verwendung von LangChain’s SQLDatabaseToolkit. SQL wird als Basissystem für den Vergleich dienen, während wir die Qualität der Ergebnisse untersuchen, die von OpenAI und Ollama bereitgestellt werden.

Die in diesem Artikel verwendeten Notebook-Dateien sind auf GitHub verfügbar.

Einführung

LangChain’s SQLDatabaseToolkit ist ein leistungsstarkes Werkzeug, das entwickelt wurde, um NL-Verarbeitungsfunktionen mit relationalen Datenbanksystemen zu integrieren. Es ermöglicht Benutzern, Datenbanken mithilfe von NL-Eingaben abzufragen, wobei die Fähigkeiten großer Sprachmodelle (LLMs) genutzt werden, um SQL-Abfragen dynamisch zu generieren. Dies macht es besonders nützlich für Anwendungen, in denen nicht-technische Benutzer oder automatisierte Systeme mit strukturierten Daten interagieren müssen. 

Eine Reihe von LLMs werden von LangChain gut unterstützt. LangChain bietet auch Unterstützung für Ollama. In diesem Artikel werden wir bewerten, wie gut LangChain mit Ollama integriert ist und die Machbarkeit der Verwendung des SQLDatabaseToolkit in einer lokalen Umgebung prüfen.

Erstellen Sie ein SingleStore Cloud-Konto

Ein früherer Artikel zeigte die Schritte zur Erstellung eines kostenlosen SingleStore Cloud-Kontos. Wir werden die Free Shared Tier verwenden.

Die Auswahl von Starter Workspace > Connect > CLI Client gibt uns später die benötigten Details wie Benutzername, Passwort, Host, Port und Datenbank.

Datenbanktabellen erstellen

Für unsere Testumgebung verwenden wir SingleStore, das in der Cloud läuft, als unser Zielsystem für die Datenbank, und wir stellen eine sichere Verbindung zu dieser Umgebung her, indem wir Jupyter-Notebooks verwenden, die auf einem lokalen System ausgeführt werden.

Von der linken Navigationsleiste im SingleStore-Cloud-Portal wählen wir DEVELOP > Data Studio > Open SQL Editor aus. Wir erstellen drei Tabellen, wie folgt:

SQL

 

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)
);

Wir laden die Tabelle portfolio mit den folgenden fiktiven Daten:

SQL

 

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);

Für die Tabelle stock_sentiment laden wir die Datei stock_sentiment.sql.zip herunter und entpacken sie. Wir laden die Daten in die Tabelle mithilfe eines MySQL-Clients, wie folgt:

Shell

 

mysql -u "<username>" -p"<password>" -h "<host>" -P <port> -D <database> < stock_sentiment.sql

Wir verwenden die Werte für <Benutzername>, <Passwort>, <Host>, <Port> und <Datenbank>, die wir zuvor gespeichert haben.

Zuletzt erstellen wir für die Tabelle tick einen Pipeline:

SQL

 

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);

Wir werden anpassen, um die frühesten Daten zu erhalten:

SQL

 

ALTER PIPELINE tick SET OFFSETS EARLIEST;

Und testen Sie die Pipeline:

SQL

 

TEST PIPELINE tick LIMIT 1;

Beispiel-Ausgabe:

Plain Text

 

+--------+---------------------+--------+--------+--------+--------+--------+
| symbol | ts                  | open   | high   | low    | price  | volume |
+--------+---------------------+--------+--------+--------+--------+--------+
| MMM    | 2025-01-23 21:40:32 | 178.34 | 178.43 | 178.17 | 178.24 |  38299 |
+--------+---------------------+--------+--------+--------+--------+--------+

Und dann starten wir die Pipeline:

SQL

 

START PIPELINE tick;

Nach ein paar Minuten werden wir die bisher geladene Datenmenge überprüfen:

SQL

 

SELECT COUNT(*)
FROM tick;

Lokale Testumgebung

Aus einem vorherigen Artikel werden wir die gleichen Schritte befolgen, um unsere lokale Testumgebung gemäß diesen Abschnitten einzurichten:

  • Einführung. Verwenden Sie eine virtuelle Maschine oder venv.
  • Erstellen Sie ein SingleStore Cloud-Konto. Dieser Schritt wurde oben abgeschlossen.
  • Erstellen Sie eine Datenbank. Der kostenlose Shared-Tarif bietet bereits eine Datenbank, und wir müssen nur den Datenbanknamen notieren.
  • Installieren Sie Jupyter.
    Klartext

     

    pip install notebook
  • Ollama installieren.
    Klartext

     

    curl -fsSL https://ollama.com/install.sh | sh
  • Umgebungsvariablen.
    Nur-Text

     

    :@:/„“ data-lang=“text/plain“>

    export SINGLESTOREDB_URL="<Benutzername>:<Passwort>@<Host>:<Port>/<Datenbank>"

    Ersetzen Sie <Benutzername>, <Passwort>, <Host>, <Port> und <Datenbank> durch die Werte Ihrer Umgebung.

    Nur-Text

     

    „“ data-lang=“text/plain“>

    export OPENAI_API_KEY="<OpenAI-API-Schlüssel>"

    Ersetzen Sie <OpenAI-API-Schlüssel> durch Ihren Schlüssel.

  • Starten Sie Jupyter.
    Klartext

    jupyter notebook

Wir werden die Jupyter-Notebooks von GitHub verwenden. Diese Notebooks sind konfiguriert, um OpenAI und Ollama zu verwenden. Für Ollama werden wir eine der in Tools support aufgeführten LLMs verwenden. Wir werden die folgenden vier Abfragen testen.

Erste Abfrage

SQL

SQL

 

SELECT symbol, (MAX(high) - MIN(low)) AS volatility
FROM tick
GROUP BY symbol
ORDER BY volatility ASC
LIMIT 1;

Natürliche Sprache

Plain Text

 

"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?"

Ergebnisse

SQL

Plain Text

 

+--------+------------+
| symbol | volatility |
+--------+------------+
| FTR    |       0.55 |
+--------+------------+

OpenAI

Plain Text

 

The stock symbol with the least volatility is FTR, with a volatility of 0.55.

Ollama

Plain Text

 

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

Zweite Abfrage

SQL

SQL

 

SELECT COUNT(*)
FROM tick;

Natürliche Sprache

Plain Text

 

"How many rows are in the tick table?"

Ergebnisse

SQL

Plain Text

 

+----------+
| COUNT(*) |
+----------+
| 22367162 |
+----------+

OpenAI

Plain Text

 

There are 22,367,162 rows in the tick table.

Ollama

Plain Text

 

The "tick" table has 3 rows.

Dritte Abfrage

SQL

SQL

 

-- Schritt 1: Holen Sie sich den neuesten Preis für jedes Symbol
WITH latest_prices AS (
    SELECT symbol, price
    FROM tick t1
    WHERE ts = (
        SELECT MAX(ts)
        FROM tick t2
        WHERE t2.symbol = t1.symbol
    )
)

-- Schritt 2: Berechnen Sie den Gesamtwert des Portfolios
SELECT SUM(p.shares_held * lp.price) AS total_portfolio_value
FROM portfolio p, latest_prices lp
WHERE p.symbol = lp.symbol;

Natürliche Sprache

Plain Text

 

"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."

Ergebnisse

SQL

Plain Text

 

+-----------------------+
| total_portfolio_value |
+-----------------------+
|              44540.60 |
+-----------------------+

OpenAI

Plain Text

 

$44,540.60

Ollama

Plain Text

 

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.

Vierte Abfrage

SQL

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;

Natürliche Sprache

Plain Text

 

"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."

Ergebnisse

SQL

Plain Text

 

+---------------------+-------------------------+--------------------+
| sentiment_date      | most_positive_sentiment | current_best_price |
+---------------------+-------------------------+--------------------+
| 2020-05-28 00:00:00 |                0.331509 |             116.27 |
+---------------------+-------------------------+--------------------+

OpenAI

Plain Text

 

On 2020-05-28, the most positive sentiment for AAPL was 0.331509, and the current best price for AAPL is 116.27.

Ollama

Plain Text

 

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

Zusammenfassung

Bei der Analyse der Ergebnisse sehen wir, dass SQL und OpenAI konsistente Ausgaben über alle vier Abfragen hinweg erzeugen. Allerdings weist Ollama klare Probleme auf. Ein Diskussionsstrang auf GitHub hebt hervor, dass während ein LLM-Modell Tool-Calling unterstützen sollte, diese Funktionalität in Ollama nicht nativ verfügbar ist.

Wenn Sie in der Lage sind, diese LangChain-Funktionalität mit Ollama in einem der unterstützten LLMs zum Laufen zu bringen, senden Sie mir bitte eine Nachricht, und ich werde den Artikel aktualisieren und Ihre Hilfe anerkennen.

Source:
https://dzone.com/articles/openai-vs-ollama-langchain-sqldatabasetoolkit