免責事項
この記事で使用されている株価データは完全に架空のものです。デモの目的だけに使用されています。このデータを金融上の意思決定に使用しないでください。
前回の記事では、RAGアプリケーションのローカルでの使用におけるOllamaの利点を見ました。この記事では、LangChainのSQLDatabaseToolkit
を使用して、自然言語(NL)クエリをデータベースシステムに対してテストし、SQLをベースラインシステムとして使用して、OpenAIとOllamaによって提供される結果の品質を探ります。
この記事で使用されているノートブックファイルはGitHubで入手できます。
はじめに
LangChainのSQLDatabaseToolkit
は、NL処理機能をリレーショナルデータベースシステムに統合するために設計された強力なツールです。これにより、非技術者や自動システムが構造化されたデータとやり取りする必要があるアプリケーションで特に便利です。
LangChainは複数のLLMをサポートしています。LangChainはまた、Ollamaをサポートしています。この記事では、LangChainがOllamaとどのように統合されるか、およびSQLDatabaseToolkit
をローカル環境で使用する可能性について評価します。
SingleStore Cloudアカウントを作成する
以前の記事では、無料のSingleStore Cloudアカウントを作成する手順を示しました。 Free Shared Tierを使用します。
Starter Workspace > Connect > CLI Clientを選択すると、後で必要となるusername
、password
、host
、port
、およびdatabase
などの詳細が得られます。
データベーステーブルの作成
テスト環境として、クラウドで実行されているSingleStoreを対象のデータベースシステムとして使用し、ローカルシステムで実行されているJupyterノートブックを使用してこの環境に安全に接続します。
SingleStoreクラウドポータルの左側のナビゲーションペインから、DEVELOP > Data Studio > Open SQL Editorを選択します。次のように3つのテーブルを作成します。
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
テーブルには、以下の架空のデータをロードします。
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クライアントを使用してデータをテーブルにロードします。
mysql -u "<username>" -p"<password>" -h "<host>" -P <port> -D <database> < stock_sentiment.sql
以前保存した<username>
、<password>
、<host>
、<port>
、および<database>
の値を使用します。
最後に、tick
テーブルについては、パイプラインを作成します。
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);
最も早いデータを取得するために調整します:
ALTER PIPELINE tick SET OFFSETS EARLIEST;
そして、パイプラインをテストします:
TEST PIPELINE tick LIMIT 1;
例の出力:
+--------+---------------------+--------+--------+--------+--------+--------+
| symbol | ts | open | high | low | price | volume |
+--------+---------------------+--------+--------+--------+--------+--------+
| MMM | 2025-01-23 21:40:32 | 178.34 | 178.43 | 178.17 | 178.24 | 38299 |
+--------+---------------------+--------+--------+--------+--------+--------+
そして、パイプラインを開始します:
START PIPELINE tick;
数分後に、現時点までに読み込まれたデータの量を確認します:
SELECT COUNT(*)
FROM tick;
ローカルテスト環境
以前の記事から、これらのセクションで説明されているとおり、ローカルテスト環境を設定するために同じ手順に従います:
- 導入。仮想マシンまたは
venv
を使用します。 - SingleStore Cloudアカウントを作成します。 この手順はすでに完了しています。
- データベースを作成します。 無料の共有ティアはすでにデータベースを提供しており、データベース名をメモするだけです。
- Jupyterをインストールします。
プレーンテキスト
pip install notebook
- Ollamaをインストールします。
プレーンテキスト
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
GitHubからJupyterノートブックを使用します。これらのノートブックはOpenAIとOllamaを使用するように構成されています。Ollamaでは、ツールサポートでリストされているLLMの1つを使用します。以下の4つのクエリをテストします。
最初のクエリ
SQL
SELECT symbol, (MAX(high) - MIN(low)) AS volatility
FROM tick
GROUP BY symbol
ORDER BY volatility ASC
LIMIT 1;
自然言語
"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
+--------+------------+
| 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
2番目のクエリ
SQL
SELECT COUNT(*)
FROM tick;
自然言語
"How many rows are in the tick table?"
結果
SQL
+----------+
| COUNT(*) |
+----------+
| 22367162 |
+----------+
OpenAI
There are 22,367,162 rows in the tick table.
Ollama
The "tick" table has 3 rows.
3番目のクエリ
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;
自然言語
"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
+-----------------------+
| 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.
4番目のクエリ
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;
自然言語
"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
+---------------------+-------------------------+--------------------+
| 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
要約
結果を分析すると、SQLとOpenAIは4つのクエリすべてで一貫した出力を生成していることがわかります。しかし、Ollamaには明らかな問題があります。GitHubのディスカッショントピックでは、LLMモデルがツール呼び出しをサポートすべきである一方で、この機能がOllamaにはネイティブに存在しないことが指摘されています。
もし、サポートされているLLMのいずれかでOllamaと一緒にこのLangChain機能を動作させることができるなら、メッセージを送ってください。記事を更新し、あなたの助けを認めます。
Source:
https://dzone.com/articles/openai-vs-ollama-langchain-sqldatabasetoolkit