# Abstraktive QA

# Einführung

Abstraktive QA (Question Answering) ist eine Art von Natural Language Processing (NLP)-Technik, bei der eine Antwort auf eine gegebene Frage in natürlicher Sprache generiert wird, indem Informationen aus verschiedenen Quellen zusammengefasst und synthetisiert werden, anstatt nur eine Antwort aus vorhandenem Text auszuwählen.

Im Gegensatz zu extraktiver QA, bei der relevante Textpassagen aus einem Korpus von Dokumenten identifiziert und extrahiert werden, um eine Frage zu beantworten, sind abstraktive QA-Systeme in der Lage, neue, originale Sätze zu generieren, die die Schlüsselinformationen und Bedeutung erfassen, um die Frage zu beantworten.

In diesem Projekt lernen Sie, wie MyScale Ihnen bei der Erstellung einer abstraktiven QA-Anwendung mit der OpenAI API helfen kann. Es gibt drei Hauptkomponenten, die für den Aufbau eines Frage-Antwort-Systems erforderlich sind:

  1. Ein Vektorindex für die semantische Suchspeicherung und -ausführung.
  2. Ein Retrieval-Modell zur Einbettung von Kontextpassagen.
  3. OpenAI API zur Extraktion von Antworten.

Wir werden den bitcoin_articles-Datensatz (opens new window) verwenden, der eine Sammlung von Nachrichtenartikeln über Bitcoin enthält, die durch Web-Scraping von verschiedenen Quellen im Internet unter Verwendung der Newscatcher API erhalten wurden. Wir werden den Retrieval verwenden, um Einbettungen für die Kontextpassagen zu erstellen, sie in der Vektordatenbank zu indizieren und eine semantische Suche durchzuführen, um die k relevantesten Kontexte mit potenziellen Antworten auf unsere Frage abzurufen. Die OpenAI API wird dann verwendet, um Antworten basierend auf den zurückgegebenen Kontexten zu generieren.

Wenn Sie mehr daran interessiert sind, die Möglichkeiten von MyScale zu erkunden, können Sie den Abschnitt Erstellung des Datensatzes überspringen und direkt zum Abschnitt Daten in MyScale einfügen gehen.

Sie können diesen Datensatz in der MyScale-Konsole importieren, indem Sie den Anweisungen im Abschnitt Import data für den Datensatz Abstraktive QA folgen. Sobald der Import abgeschlossen ist, können Sie direkt zum Abschnitt Abfragen von MyScale gehen, um diese Beispielanwendung zu nutzen.

# Voraussetzungen

Bevor wir beginnen, müssen wir Tools wie den ClickHouse Python-Client (opens new window), OpenAI, Sentence-Transformer und andere Abhängigkeiten installieren.

# Abhängigkeiten installieren

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

# OpenAI einrichten

import openai
openai.api_key = "YOUR_OPENAI_API_KEY"

# Retrieval einrichten

Wir müssen unseren Retrieval initialisieren, der hauptsächlich zwei Aufgaben erfüllt, wobei die erste optional ist:

  1. Erzeugung von Einbettungen für jeden Kontextabschnitt (Kontextvektoren/Einbettungen)
  2. Erzeugung einer Einbettung für unsere Anfragen (Abfragevektor/Einbettung)
import torch
from sentence_transformers import SentenceTransformer
# Gerät auf GPU setzen, falls verfügbar
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Das Retrieval-Modell aus dem Huggingface Model Hub laden
retriever = SentenceTransformer('multi-qa-MiniLM-L6-cos-v1', device=device)

# Erstellung des Datensatzes

# Daten herunterladen und verarbeiten

Der Datensatz enthält Nachrichtenartikel über Bitcoin, die mithilfe der Newscatcher API von verschiedenen Quellen im Internet gescraped wurden.

Die Informationen werden in CSV-Dateien bereitgestellt und enthalten Details wie Artikel-ID, Titel, Autor, Veröffentlichungsdatum, Link, Zusammenfassung, Thema, Land, Sprache und mehr. Zunächst erstellen wir eine kompakte Datenbank zur Abrufung von Daten.

Um dieses Notebook zu vereinfachen, halten wir eine vollständige Kopie des Kaggle-Datensatzes bitcoin-news-articles-text-corpora (opens new window) auf S3 vor, um Zeit bei der Konfiguration von Kaggle's Public API (opens new window)-Anmeldeinformationen zu sparen.

Daher können wir den Datensatz mit dem folgenden Befehl herunterladen:

wget https://myscale-saas-assets.s3.ap-southeast-1.amazonaws.com/testcases/clickhouse/bitcoin-news-articles-text-corpora.zip
# Die heruntergeladene Datei entpacken
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())

Ausgabe:

<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

# Generierung von Einbettungen für Artikelzusammenfassungen

Nach der Verarbeitung der Daten verwenden wir den zuvor definierten Retrieval, um Einbettungen für die Artikelzusammenfassungen zu generieren.

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))
    # Einbettungen für Zusammenfassung generieren
    emb = retriever.encode(summary_raw[i:i_end]).tolist()[0]
    summary_feature.append(emb)
data_raw['summary_feature'] = summary_feature

# Erstellung des Datensatzes

Schließlich konvertieren wir die Dataframes in eine CSV-Datei und komprimieren sie zu einer Zip-Datei, die wir später hochladen werden.

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

# Daten in MyScale einfügen

# Daten laden

Um Daten in MyScale einzufügen, laden wir zunächst den Datensatz herunter, der im vorherigen Abschnitt erstellt wurde. Der folgende Codeausschnitt zeigt, wie die Daten heruntergeladen und in Panda DataFrames transformiert werden.

Hinweis: summary_feature ist ein 384-dimensionaler Gleitkommavektor, der die Textmerkmale aus einer Artikelzusammenfassung darstellt, die mit dem Modell multi-qa-MiniLM-L6-cos-v1 extrahiert wurden.

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

Ausgabe:

<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

# Tabelle erstellen

Als nächstes erstellen wir Tabellen in MyScale. Bevor Sie beginnen, müssen Sie Ihre Cluster-Host-, Benutzername- und Passwortinformationen aus der MyScale-Konsole abrufen.

Der folgende Codeausschnitt erstellt die Tabelle für die Bitcoin-Artikeldaten.

import clickhouse_connect
client = clickhouse_connect.get_client(
    host='YOUR_CLUSTER_HOST',
    port=443,
    username='YOUR_USERNAME',
    password='YOUR_CLUSTER_PASSWORD'
)
# Tabelle für Bitcoin-Texte erstellen
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
""")

# Daten hochladen

Nachdem die Tabelle erstellt wurde, fügen wir die aus den Datensätzen geladenen Daten in die Tabellen ein und erstellen einen Vektorindex, um spätere Vektor-Suchabfragen zu beschleunigen. Der folgende Codeausschnitt zeigt, wie Daten in die Tabelle eingefügt und ein Vektorindex mit Kosinus-Abstandsmetrik erstellt wird.

# Daten aus den Datensätzen hochladen
client.insert("default.myscale_llm_bitcoin_qa", 
              data.to_records(index=False).tolist(), 
              column_names=data.columns.tolist())
# Anzahl der eingefügten Daten überprüfen
print(f"article count: {client.command('SELECT count(*) FROM default.myscale_llm_bitcoin_qa')}")
# Anzahl der Artikel: 1731
# Vektorindex mit Kosinus erstellen
client.command("""
ALTER TABLE default.myscale_llm_bitcoin_qa 
ADD VECTOR INDEX summary_feature_index summary_feature
TYPE MSTG
('metric_type=Cosine')
""")
# Den Status des Vektorindex überprüfen, stellen Sie sicher, dass der Vektorindex mit dem Status 'Built' bereit ist
get_index_status="SELECT status FROM system.vector_indices WHERE name='summary_feature_index'"
print(f"index build status: {client.command(get_index_status)}")

# Abfragen von MyScale

# Suchen und Filtern

Verwenden Sie den Retrieval, um die Einbettung der Abfragefrage zu generieren.

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

Verwenden Sie dann die Vektorsuche, um die Top-K-Kandidaten zu identifizieren, die der Frage am ähnlichsten sind, und filtern Sie das Ergebnis mit article_rank < 500.
```python
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"])

# CoT für GPT-3.5 erhalten

Kombinieren Sie die aus MyScale abgerufenen Zusammenfassungen zu einer gültigen Eingabeaufforderung.

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

Ausgabe:

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

# Ergebnis von GPT-3.5 erhalten

Verwenden Sie die generierte CoT, um gpt-3.5-turbo abzufragen.

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)

Ausgabe:

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.

Wir erhalten eine vollständige und detaillierte Antwort. Wir haben großartige Ergebnisse erhalten.

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