# 抽象的なQA

# はじめに

抽象的なQA(Question Answering)は、与えられた質問に対して事前に存在するテキストから回答を選択するのではなく、さまざまな情報源から情報を要約・統合して自然言語で回答を生成する自然言語処理(NLP)の技術の一種です。

抽出的なQAとは異なり、抽象的なQAシステムは、質問に答えるために必要な主要な情報と意味を捉えた新しいオリジナルの文を生成することができます。

このプロジェクトでは、MyScaleがopenai apiを使用して抽象的なQAアプリケーションを作成するのにどのように役立つかを学びます。質問応答システムを構築するためには、主に3つの主要なコンポーネントが必要です。

  1. セマンティックサーチのストレージと実行のためのベクトルインデックス。
  2. コンテキストパッセージを埋め込むためのリトリーバモデル。
  3. 回答抽出のためのOpenAI API。

bitcoin_articles dataset (opens new window)を使用します。このデータセットは、Newscatcher APIを使用してインターネット上のさまざまなソースからビットコインに関するニュース記事をウェブスクレイピングしたものです。リトリーバを使用してコンテキストパッセージの埋め込みを作成し、ベクトルデータベースにインデックスを作成し、セマンティックサーチを実行して、質問に対する回答の可能性があるトップkの関連コンテキストを取得します。その後、OpenAI APIを使用して返されたコンテキストに基づいて回答を生成します。

MyScaleの機能をさらに探索したい場合は、データセットの作成セクションをスキップして、MyScaleへのデータの追加セクションに直接進むこともできます。

このデータセットをMyScaleコンソールにインポートするには、Abstractive QAデータセットのImport dataセクションで提供される手順に従ってください。インポートが完了したら、MyScaleへのクエリセクションに直接進んで、このサンプルアプリケーションをお楽しみください。

# 前提条件

始める前に、clickhouse python client (opens new window)、openai、sentence-transformer、およびその他の依存関係などのツールをインストールする必要があります。

# 依存関係のインストール

pip install clickhouse-connect openai sentence-transformers torch requests pandas tqdm

# Openaiのセットアップ

import openai
openai.api_key = "YOUR_OPENAI_API_KEY"

# リトリーバのセットアップ

まず、リトリーバを初期化する必要があります。リトリーバは主に2つのタスクを実行します(1つ目はオプションです):

  1. 各コンテキストパッセージの埋め込みを生成する(コンテキストベクトル/埋め込み)
  2. クエリの埋め込みを生成する(クエリベクトル/埋め込み)
import torch
from sentence_transformers import SentenceTransformer
# GPUが利用可能な場合はデバイスをGPUに設定します
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# リトリーバモデルをhuggingfaceモデルハブからロードします
retriever = SentenceTransformer('multi-qa-MiniLM-L6-cos-v1', device=device)

# データセットの作成

# データのダウンロードと処理

データセットには、Newscatcher APIを使用してインターネット上のさまざまなソースからウェブスクレイピングされたビットコインに関するニュース記事のコレクションが含まれています。

情報はCSVファイルで提供され、記事ID、タイトル、著者、公開日、リンク、要約、トピック、国、言語などの詳細が含まれています。まず、データの取得を容易にするために、Kaggleのデータセットbitcoin-news-articles-text-corpora (opens new window)の完全なコピーをS3に保持し、KaggleのPublic API (opens new window)の資格情報の設定に時間をかけることを避けます。

したがって、以下のコマンドでデータセットをダウンロードできます。

wget https://myscale-saas-assets.s3.ap-southeast-1.amazonaws.com/testcases/clickhouse/bitcoin-news-articles-text-corpora.zip
# ダウンロードしたファイルを解凍します
unzip -o bitcoin-news-articles-text-corpora.zip 
import pandas as pd
data_raw = pd.read_csv('bitcoin_articles.csv')
data_raw.drop_duplicates(subset=['summary'], keep='first', inplace=True)
data_raw.dropna(subset=['summary'], inplace=True)
data_raw.dropna(subset=['author'], inplace=True)
print(data_raw.info())

出力:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1731 entries, 0 to 2499
Data columns (total 18 columns):
    #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
    0   article_id       1731 non-null   object 
    1   title            1731 non-null   object 
    2   author           1731 non-null   object 
    3   published_date   1731 non-null   object 
    4   link             1731 non-null   object 
    5   clean_url        1731 non-null   object 
    6   excerpt          1730 non-null   object 
    7   summary          1731 non-null   object 
    8   rights           1730 non-null   object 
    9   article_rank     1731 non-null   int64  
    10  topic            1731 non-null   object 
    11  country          1731 non-null   object 
    12  language         1731 non-null   object 
    13  authors          1731 non-null   object 
    14  media            1725 non-null   object 
    15  twitter_account  1368 non-null   object 
    16  article_score    1731 non-null   float64
    17  summary_feature  1731 non-null   object 
dtypes: float64(1), int64(1), object(16)
memory usage: 256.9+ KB

# 記事の要約の埋め込みの生成

データの処理が完了したら、以前定義したリトリーバを使用して記事の要約の埋め込みを生成します。

from tqdm.auto import tqdm
summary_raw = data_raw['summary'].values.tolist()
summary_feature = []
for i in tqdm(range(0, len(summary_raw), 1)):
    i_end = min(i+1, len(summary_raw))
    # 要約の埋め込みを生成します
    emb = retriever.encode(summary_raw[i:i_end]).tolist()[0]
    summary_feature.append(emb)
data_raw['summary_feature'] = summary_feature

# データセットの作成

最後に、データフレームをcsvファイルに変換し、zipに圧縮して後で使用するためにs3にアップロードします。

data = data_raw[['article_id', 'title', 'author', 'link', 'summary', 'article_rank', 'summary_feature']]
data = data.reset_index().rename(columns={'index': 'id'})
data.to_csv('bitcoin_articles_embd.csv', index=False)
zip abstractive-qa-examples.zip bitcoin_articles_embd.csv

# MyScaleへのデータの追加

# データのロード

MyScaleにデータを追加するためには、まず、前のセクションで作成したデータセットをダウンロードする必要があります。以下のコードスニペットは、データをダウンロードしてpanda DataFramesに変換する方法を示しています。

注意:summary_featureは、multi-qa-MiniLM-L6-cos-v1モデルを使用して記事の要約から抽出したテキスト特徴を表す384次元の浮動小数点ベクトルです。

wget https://myscale-saas-assets.s3.ap-southeast-1.amazonaws.com/testcases/clickhouse/abstractive-qa-examples.zip
unzip -o abstractive-qa-examples.zip
import pandas as pd
import ast
data = pd.read_csv('bitcoin_articles_embd.csv')
data['summary_feature'] = data['summary_feature'].apply(ast.literal_eval)
print(data.info())

出力:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1731 entries, 0 to 1730
Data columns (total 8 columns):
    #   Column           Non-Null Count  Dtype 
---  ------           --------------  ----- 
    0   id               1731 non-null   int64 
    1   article_id       1731 non-null   object
    2   title            1731 non-null   object
    3   author           1731 non-null   object
    4   link             1731 non-null   object
    5   summary          1731 non-null   object
    6   article_rank     1731 non-null   int64 
    7   summary_feature  1731 non-null   object
dtypes: int64(2), object(6)
memory usage: 108.3+ KB

# テーブルの作成

次に、MyScaleでテーブルを作成します。始める前に、MyScaleコンソールからクラスタホスト、ユーザー名、パスワード情報を取得する必要があります。

以下のコードスニペットは、ビットコインの記事情報テーブルを作成します。

import clickhouse_connect
client = clickhouse_connect.get_client(
    host='YOUR_CLUSTER_HOST',
    port=443,
    username='YOUR_USERNAME',
    password='YOUR_CLUSTER_PASSWORD'
)
# ビットコインのテキストのためのテーブルを作成します
client.command("DROP TABLE IF EXISTS default.myscale_llm_bitcoin_qa")
client.command("""
CREATE TABLE default.myscale_llm_bitcoin_qa
(
    id UInt64,
    article_id String,
    title String,
    author String,
    link String,
    summary String,
    article_rank UInt64,
    summary_feature Array(Float32),
    CONSTRAINT vector_len CHECK length(summary_feature) = 384
)
ORDER BY id
""")

# データのアップロード

テーブルを作成した後、データセットからロードしたデータをテーブルに挿入し、後でベクトル検索クエリを高速化するためのベクトルインデックスを作成します。以下のコードスニペットは、データをテーブルに挿入し、コサイン距離メトリックを使用してベクトルインデックスを作成する方法を示しています。

# データセットからデータをアップロードする
client.insert("default.myscale_llm_bitcoin_qa", 
              data.to_records(index=False).tolist(), 
              column_names=data.columns.tolist())
# 挿入されたデータの数を確認する
print(f"article count: {client.command('SELECT count(*) FROM default.myscale_llm_bitcoin_qa')}")
# article count: 1731
# コサイン距離メトリックを使用してベクトルインデックスを作成する
client.command("""
ALTER TABLE default.myscale_llm_bitcoin_qa 
ADD VECTOR INDEX summary_feature_index summary_feature
TYPE MSTG
('metric_type=Cosine')
""")
# ベクトルインデックスのステータスを確認し、ベクトルインデックスが 'Built' のステータスで準備完了であることを確認します
get_index_status="SELECT status FROM system.vector_indices WHERE name='summary_feature_index'"
print(f"index build status: {client.command(get_index_status)}")

# MyScaleへのクエリ

# 検索とフィルタリング

リトリーバを使用してクエリの質問埋め込みを生成します。

question = 'what is the difference between bitcoin and traditional money?'
emb_query = retriever.encode(question).tolist()

次に、ベクトル検索を使用して、質問に最も類似しているトップKの候補を特定し、結果をarticle_rank < 500でフィルタリングします。

top_k = 10
results = client.query(f"""
SELECT summary, distance(summary_feature, {emb_query}) as dist
FROM default.myscale_llm_bitcoin_qa
WHERE article_rank < 500
ORDER BY dist LIMIT {top_k}
""")
summaries = []
for res in results.named_results():
    summaries.append(res["summary"])

# GPT-3.5のためのCoTの取得

MyScaleから検索された要約を有効なプロンプトに組み合わせます。

CoT = ''
for summary in summaries:
    CoT += summary
CoT += '\n' +'Based on the context above '+'\n' +' Q: '+ question + '\n' +' A: The answer is'
print(CoT)

出力:

Some even see a digital payment revolution unfolding on the horizon. Despite rising inflation, the interest in crypto is still growing, and adoption continues to expand. One of the industries that are bridging the gap between crypto and ordinary people is retail Forex trading. In the midst of global economic and political uncertainties and disturbances, people increasingly seek out the cryptocurrency market to probe its inner workings, principles and financial potential. Investors use crypto to diversify their portfolios, whereas the mother of all cryptocurrencies—bitcoin—even established itself as a ‘store of value'.Bitcoin prices have stayed relatively stable lately amid contractionary Fed policies. getty
Bitcoin prices have continued to trade within a relatively tight range recently, retaining their value even as Federal Reserve policies threaten the values of risk assets. The world's best-known digital currency, which has a total market value of close to $375 billion at the time of this writing, has been trading reasonably close to the $20,000 level since last month, CoinDesk data shows. The cryptocurrency has experienced some price fluctuations lately, but these movements have been modest.: Representations of Bitcoin and pound banknotes - Dado Ruvic/ REUTERS
Bitcoin is the 'child of the great quantitative easing' by the likes of the Bank of England, the former Conservative Party Treasurer has claimed.
Lord Michael Spence blamed the vast programme of bond buying carried out by central banks for creating a price bubble for cryptocurrencies such as bitcoin, saying the Bank of England 'printed too much money' and caused a 'very rapid growth in the money supply'.
Cheap money inflated the cryptocurrency market into the 'modern day equivalent of the Dutch tulip bubble', said Lord Spencer, the founder of trading firm ICAP.Analysts speak to key considerations as we start a new month. getty
As the new month begins, investors have been closely watching macroeconomic developments and central bank policy decisions at a time when bitcoin continues to trade within a relatively modest range. The world's most well-known digital currency has been fluctuating between roughly $18,950 and $19,650.00 since the start of October, TradingView figures reveal. Around 3:00 p.m. ET today, it reached the upper end of this range, additional TradingView data shows.Some luxury hotels are now offering a new perk: the ability to pay in cryptocurrencies. From Dubai to the Swiss Alps, several high-end hotels enable guests to swap their credit cards for their digital assets.
The Future of Finances: Gen Z & How They Relate to Money
Looking To Diversify in a Bear Market? Consider These 6 Alternative Investments
The Chedi Andermatt, a 5-star hotel in Andermatt, Switzerland, is one of them.
General Manager Jean-Yves Blatt said the hotel, which started offering such payments in August 2021, is currently accepting Bitcoin and ETH, an option that is a continuation of the personalized services it offers its guests.Bitcoin BTC is not just a decentralized peer-to-peer electronic cash system. There's more. It is a new way of thinking about economics, philosophy, politics, human rights, and society.
Hungarian sculptors and creators Reka Gergely (L) and Tamas Gilly (R) pose next to the statue of ... [+] Satoshi Nakamoto, the mysterious inventor of the virtual currency bitcoin, after its unveiling at the Graphisoft Park in Budapest, on September 16, 2021. - Hungarian bitcoin enthusiasts unveiled a statue on September 16 in Budapest that they say is the first in the world to honour Satoshi Nakamoto, the mysterious inventor of the virtual currency.The invention of cryptocurrency is attributed to Satoshi Nakamoto , the pseudonym for the creator or group of creators of Bitcoin. The exact identity of Satoshi Nakamoto remains unknown.
Cryptocurrency can be stored in online exchanges, such as Coinbase and PayPal , or cryptocurrency owners can store their crypto cash on hardware wallets. Trezor and Ledger are examples of companies that sell these small devices to securely store crypto tokens. These wallets can be 'hot,' meaning users are connected to the Internet and have easier access to their crypto tokens, or 'cold,' meaning that the crypto tokens are encrypted in wallets with private keys whose passwords are not stored on Internet-connected computers.A strong dollar and rising Treasury yields have given bitcoin and gold something in common price-wise: both assets have tumbled this year. Gold GC00, +2.23%, traditionally seen as a safe haven asset, has lost almost 7% year-to-date, according to Dow Jones Market Data. Bitcoin BTCUSD, +1.59% declined almost 60% year-to-date, according to CoinDesk data.  Though some bitcoin supporters have touted the cryptocurrency as a hedge against inflation and as 'digital gold,' the two assets have been largely uncorrelated, with their correlation mostly swinging between negative 0.Bitcoin, Ethereum and other cryptocurrencies, have been described as offering a store of value, but ... [+] that hasn't happened yet in 2022 (Photo illustration by Jakub Porzycki/NurPhoto via Getty Images)NurPhoto via Getty Images
In 2022, Bitcoin BTC and Ethereum ETH have both lost around two thirds of their value for the year so far. That's at a time when U.S. inflation is running at around 8% and market risk is elevated. What happened to Bitcoin and Ethereum as a store of value? It's worth noting that this level of volatility is nothing new.A strong dollar and rising Treasury yields have given bitcoin and gold something in common price-wise: both assets have tumbled this year.Gold GC00, +2.30%, traditionally seen as a safe haven asset, has lost almost 7% year-to-date, according to Dow Jones Market Data. Bitcoin BTCUSD, +1.47% declined almost 60% year-to-date, according to CoinDesk data.
Based on the context above 
    Q: what is the difference between bitcoin and traditional money?
    A: The answer is

# GPT-3.5からの結果の取得

生成されたCoTを使用してgpt-3.5-turboにクエリを実行します。

response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": CoT}
    ],
    temperature=0,
)
print("Example: Retrieval with MyScale")
print('Q: ', question)
print('A: ', response.choices[0].message.content)

出力:

Example: Retrieval with MyScale
Q:  what is the difference between bitcoin and traditional money?
A:  Bitcoin is a decentralized digital currency that operates independently of traditional banking systems and is not backed by any government. It is based on blockchain technology and allows for peer-to-peer transactions without the need for intermediaries. Traditional money, on the other hand, is issued and regulated by central banks and governments, and its value is backed by the trust and stability of those institutions.

完全で詳細な回答が返されました。素晴らしい結果を得ました。

Last Updated: Thu Apr 11 2024 02:40:52 GMT+0000