OpenAI נגד Ollama בשימוש ב־LangChain's SQLDatabaseToolkit

כתב ויתור

הנתונים המניירים המשמשים במאמר זה הם בדיוניים לחלוטין. הם מיועדים למטרות דמו בלבד. אנא אל תשתמשו בנתונים אלו לקבלת החלטות פיננסיות.

במאמר קודם, ראינו את היתרונות של שימוש ב-Ollama מקומית עבור אפליקציית RAG. במאמר זה, נמשיך את ההערכה שלנו על Ollama על ידי בדיקת שאילתות בשפת טבע (NL) נגד מערכת מסד נתונים, באמצעות כלי ה-SQLDatabaseToolkit של LangChain. SQL ישמש כמערכת הבסיס להשוואה בזמן שנחקור את איכות התוצאות שסופקות על ידי OpenAI ו-Ollama.

קבצי המחברת שנמצאו במאמר זה זמינים ב-GitHub.

הקדמה

כלי ה-SQLDatabaseToolkit של LangChain הוא כלי עוצמתי המיועד לשלב יכולות עיבוד שפה טבעית עם מערכות מסד נתונים רציונליות. הוא מאפשר למשתמשים לשאול שאילתות במסדי נתונים באמצעות קלטים בשפת ה- NL, באמצעות יכולות של מודלי שפה גדולים (LLMs) ליצירת שאילתות SQL באופן דינמי. זה עושה אותו שימושי במיוחד עבור אפליקציות בהן משתמשים לא טכניים או מערכות אוטומטיות צריכים להתקשר עם נתונים מובנים.

מספר LLMs נתמכים היטב על ידי LangChain. LangChain מספקת גם תמיכה ב-Ollama. במאמר זה, נערוך הערכה כמה טוב LangChain משלבת עם Ollama והאפשרות להשתמש ב-SQLDatabaseToolkit בהגדרה מקומית.

צור חשבון ענן של SingleStore

מאמר קודם הציג את השלבים ליצירת חשבון SingleStore Cloud חינמי. נשתמש ב- שכבת שיתוף חינמית.

בחירת סביבת עבודה המתחילה > התחברות > לקוח CLI יעניק לנו את הפרטים שנזקק מאוחר יותר, כגון שם משתמש, סיסמה, מארח, פורט ו־בסיס נתונים.

יצירת טבלאות בבסיס נתונים

למערכת הבדיקה שלנו, נשתמש ב-SingleStore הפועל בענן כמערכת בסיס נתונים שלנו, ונתחבר בצורה מאובטחת לסביבה זו באמצעות מחברות Jupyter הפועלות במערכת מקומית.

מפריט הניווט השמאלי בפורטל הענן של SingleStore, נבחר פיתוח > Data Studio > פתיחת עורך SQL. ניצור שלוש טבלאות, כך:

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

נטען את טבלת portfolio עם הנתונים הדמייניים הבאים:

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

לטבלת stock_sentiment, נוריד את הקובץ stock_sentiment.sql.zip ונפרוק אותו. נטען את הנתונים לתוך הטבלה באמצעות לקוח MySQL, כך:

Shell

 

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

נשתמש בערכים של <שם משתמש>, <סיסמה>, <מארח>, <פורט> ו־<בסיס נתונים> ששמרנו מראש.

לבסוף, לטבלת tick, ניצור צינור:

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

נתאים את הנתונים המוקדמים:

SQL

 

ALTER PIPELINE tick SET OFFSETS EARLIEST;

ונבדוק את הצינור:

SQL

 

TEST PIPELINE tick LIMIT 1;

פלט הדוגמה:

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 |
+--------+---------------------+--------+--------+--------+--------+--------+

ואז נתחיל את הצינור:

SQL

 

START PIPELINE tick;

לאחר מספר דקות, נבדוק את כמות הנתונים שנטענו עד כה:

SQL

 

SELECT COUNT(*)
FROM tick;

סביבת מבחן מקומית

ממאמר קודם, נעקוב אחר אותן צעדים כדי להגדיר את סביבת הבדיקות המקומית שלנו כפי שמתואר בחלקים הבאים:

  • הקדמה. השתמש במכונה וירטואלית או ב־venv.
  • צור חשבון במערכת של SingleStore Cloud. שלב זה הושלם למעלה.
  • צור בסיס נתונים. הרמת השיתוף החינמי כבר מספקת בסיס נתונים ואנו רק צריכים לרשום את שם מסד הנתונים.
  • התקן את Jupyter.
    טקסט פשוט

     

    pip install notebook
  • התקן את אולאמה.
    טקסט פשוט

     

    curl -fsSL https://ollama.com/install.sh | sh
  • משתני סביבה.
    טקסט פשוט

     

    :@:/"" data-lang="text/plain">

    export SINGLESTOREDB_URL="<username>:<password>@<host>:<port>/<database>"

    החלפו את <username>, <password>, <host>, <port> ו־<database> עם הערכים שלכם בסביבת העבודה שלכם.

    טקסט פשוט

     

    "" data-lang="text/plain">

    export OPENAI_API_KEY="<OpenAI API Key>"

    החלפו את <OpenAI API Key> עם המפתח שלכם.

  • הפעל את Jupyter.
    טקסט פשוט

     

    jupyter notebook

נשתמש במחברות Jupyter מ־GitHub. מחברות אלו מוגדרות לשימוש ב־OpenAI ו־Ollama. עבור Ollama, נשתמש באחד מה־LLMs המופיעים תחת תמיכת כלים. נבדוק ארבע שאילתות הבאות.

שאילתה ראשונה

SQL

SQL

 

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

שפת טבעית

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

תוצאות

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

שאילתה שנייה

SQL

SQL

 

SELECT COUNT(*)
FROM tick;

שפת טבעית

Plain Text

 

"How many rows are in the tick table?"

תוצאות

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.

שאילתה שלישית

SQL

SQL

 

-- שלב 1: קבל את מחיר האחרון עבור כל סמל
WITH latest_prices AS (
    SELECT symbol, price
    FROM tick t1
    WHERE ts = (
        SELECT MAX(ts)
        FROM tick t2
        WHERE t2.symbol = t1.symbol
    )
)

-- שלב 2: חשב את ערך התיק הכולל
SELECT SUM(p.shares_held * lp.price) AS total_portfolio_value
FROM portfolio p, latest_prices lp
WHERE p.symbol = lp.symbol;

שפת טבעית

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

תוצאות

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.

שאילתה רביעית

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;

שפת טבעית

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

תוצאות

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

סיכום

בנית התוצאות, אנו רואים כי SQL ו-OpenAI מפיקים פלטים עקביים בכל ארבעת השאילתות. אך, Ollama מציג בעיות ברורות. פוסט בגיטהאב מבהיר כי בעוד מודל LLM צריך לתמוך בקריאת כלי, פונקציונליות זו לא זמינה באופן טבעי ב-Ollama.

אם תצליח לקבל את פונקציונליות השפה הזו עובדת עם Ollama באחד ממודלי ה-LLM הנתמכים, אנא שלח לי הודעה, ואעדכן את המאמר ואודה לעזרתך.

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