Snowflake Cortex / ArcticによるAI分析【入門②】
はじめに
Snowflake の AI 周りを色々学習中でして、前回に続き、今回は以下のチュートリアルの実施記録とそれによって理解できたことを簡単に記します。内容としては主に Cortex と Arctic に関してとなります。
1. Snowflake Cortex とは?
Snowflake Cortex は、Snowflake ユーザー向けに提供される完全管理型の AI および機械学習サービスです。これにより、複雑な AI モデルのデプロイや管理を気にすることなく、さまざまな AI 機能を利用できます。具体的には、以下のような機能があります。
- LLM 機能: 大規模言語モデルを活用し、テキストの理解、クエリ、翻訳、要約、生成を行います。
- ML 機能: 構造化データに対する予測分析(例: 異常検出)を実施し、日常の分析を加速します。
2. Snowflake Arctic とは?
Snowflake Arctic は、エンタープライズ向けに設計されたモデル群で、SQL 生成やコード生成などのタスクに優れた性能を持っています。これらのモデルは、Apache 2.0 ライセンスの下で商業利用が可能です。
3. 実施した内容
データの概要
チュートリアル用に公開されているテストデータを使用しました。これは顧客との通話/チャット、アンケート、インタビュー、マーケティング チームや営業チームで生成されるその他のテキスト データなど、組織で一般的に見落とされがちなテキストソースを模倣した通話記録データです。
データの準備
まず、Amazon S3 からのデータを使用して、通話記録テーブルを作成しました。以下の SQL コマンドを実行して、データをインポートしました。
CREATE or REPLACE file format csvformat
SKIP_HEADER = 1
FIELD_OPTIONALLY_ENCLOSED_BY = '"'
type = 'CSV';
CREATE or REPLACE stage call_transcripts_data_stage
file_format = csvformat
url = 's3://sfquickstarts/misc/call_transcripts/';
CREATE or REPLACE table CALL_TRANSCRIPTS (
date_created date,
language varchar(60),
country varchar(60),
product varchar(60),
category varchar(60),
damage_type varchar(90),
transcript varchar
) COMMENT = '{"origin":"sf_sit-is", "name":"aiml_notebooks_artic_cortex", "version":{"major":1, "minor":0}, "attributes":{"is_quickstart":1, "source":"sql"}}';
COPY into CALL_TRANSCRIPTS
from @call_transcripts_data_stage;
結果として、以下のようなデータが CALL_TRANSCRIPTS テーブルに格納されました。
DATE_CREATED | LANGUAGE | COUNTRY | PRODUCT | CATEGORY | DAMAGE_TYPE | TRANSCRIPT |
---|---|---|---|---|---|---|
2023-10-27 | German | Germany | XtremeX | helmet | broken buckle | Kunde: Hallo Agent: Hallo, ich hoffe, es geht Ihnen gut. ... |
2023-10-27 | German | Germany | XtremeX | helmet | broken buckle | Kunde: Guten Tag Mitarbeiter: Guten Tag, ich hoffe, Sie haben einen schönen Tag. ... |
2023-10-31 | German | Germany | XtremeX | helmet | broken buckle | Kunde: Hallo Mitarbeiter: Hallo, ich hoffe, Sie haben einen schönen Tag. ... |
... | ... | ... | ... | ... | ... | ... |
Snowflake Cortex の活用
ここから、実際に Snowflake の AI 機能を使っていきます。ここでは Snowflake Cortex を使用して、通話記録の翻訳、感情分析、要約を行いました。例えば、以下の SQL を使って、ドイツ語のトランスクリプトを英語に翻訳しました。
SELECT transcript, snowflake.cortex.translate(transcript, 'de_DE', 'en_XX')
FROM call_transcripts
WHERE language = 'German';
結果は以下のようになります。
TRANSCRIPT | SNOWFLAKE.CORTEX.TRANSLATE(TRANSCRIPT,'DE_DE','EN_XX') |
---|---|
Kunde: Hallo Agent: Hallo, ich hoffe, es geht Ihnen gut. ... | Customer: Hello. Agent: Hello, I hope you are well. To best assist you, please share your first and last name and the name of the company you are calling from. ... |
Kunde: Guten Tag Mitarbeiter: Guten Tag, ich hoffe, Sie haben einen schönen Tag. ... | Customer: Good day. Employee: Good day, I hope you're having a nice day. To help you as best as possible, please share your first and last name and the name of the company you're calling from. ... |
Kunde: Hallo Mitarbeiter: Hallo, ich hoffe, Sie haben einen schönen Tag. Um Ihnen bestmöglich zu helfen, teilen Sie bitte Ihren Vor- und ... | Customer: Hello Employee: Hello, I hope you're having a nice day. To help you as best as possible, please provide your first and last name and the name of the company you're calling from. ... |
... | ... |
感情スコアを生成するためには、次のように実行しました。
SELECT transcript, snowflake.cortex.sentiment(transcript)
FROM call_transcripts
WHERE language = 'English';
結果は以下のようになります。
(注: スコアは -1 から 1 の間です。-1 = 最も否定的、1 = 肯定的、0 = 中立的)
TRANSCRIPT | SNOWFLAKE.CORTEX.SENTIMENT(TRANSCRIPT) |
---|---|
Customer: Hello Agent: Hi there, I hope you're having a great day! To better assist you, could you please provide your first and last name and the company you are calling from? ... | 0.31572506 |
Customer: Hello there Agent: Hello, I hope you're having a great day. To provide you with the most help, can you please share your first and last name and the company you are calling from? ... | 0.5504076 |
Customer: Hello there Agent: Hello, I hope you're having a great day. To provide you with the most help, can you please share your first and last name and the company you are calling from? ... | -0.83638066 |
... | ... |
テキストの要約は、次のように実行しました。ここでは、トークン数についても併せて出力しています。
select transcript,snowflake.cortex.summarize(transcript) as summary,snowflake.cortex.count_tokens('summarize',transcript) as number_of_tokens from call_transcripts where language = 'English' limit 1;
結果は以下のようになります。
TRANSCRIPT | SUMMARY | NUMBER_OF_TOKENS |
---|---|---|
Customer: Hello Agent: Hi there, I hope you're having a great day! To better assist you, could you please provide your first and last name and the company you are calling from? Customer: Sure, my name is Jessica Turner and I'm calling from Mountain Ski Adventures. Agent: Thanks, Jessica. What can I help you with today? ... | Customer reported ten broken XtremeX helmets with faulty buckles from Mountain Ski Adventures. Agent confirmed order number and offered replacement or refund. Customer preferred replacement and specified quantity. Agent initiated process for sending new helmets. Estimated arrival within 3-5 business days. | 398 |
最後に、テキストの内容から予測されるカテゴリに分類しました。
select transcript,snowflake.cortex.classify_text(transcript,['Refund','Exchange']) as classification from call_transcripts where language = 'English';
結果は以下のようになります。
TRANSCRIPT | CLASSIFICATION |
---|---|
Customer: Hello Agent: Hi there, I hope you're having a great day! To better assist you, could you please provide your first and last name and the company you are calling from? ... | { "label": "Exchange"} |
Customer: Hello there Agent: Hello, I hope you're having a great day. To provide you with the most help, can you please share your first and last name and the company you are calling from? ... | { "label": "Exchange"} |
Customer: Hello there Agent: Hello, I hope you're having a great day. To provide you with the most help, can you please share your first and last name and the company you are calling from? ... | { "label": "Exchange"} |
... | ... |
Snowflake Arctic でのプロンプトエンジニアリング
要約機能を使って、特定の情報を JSON 形式で取得するために、プロンプトを設定しました。以下の SQL を実行することで、製品名や欠陥を含む要約を得ることができました。
SET prompt =
'###
Summarize this transcript in less than 200 words.
Put the product name, defect and summary in JSON format.
###';
select snowflake.cortex.complete('snowflake-arctic',concat('[INST]',$prompt,transcript,'[/INST]')) as summary
from call_transcripts where language = 'English' limit 1;
結果は以下のようになります。プロンプトで指定した通り、概要を 200 文字以内で抜き出していることがわかります。
SUMMARY |
---|
{"product_name": "XtremeX helmets","defect": "broken buckles","summary": "Customer reports that several XtremeX helmets have broken buckles that won't secure the helmet properly. The customer prefers a replacement for the damaged helmets. The agent confirms the order number and starts the process to send out replacements for the damaged helmets. The customer should expect the new shipment of ten XtremeX helmets with functioning buckles to arrive within 3-5 business days."} |
{
"product": "XtremeX helmets",
"defect": "broken buckles",
"summary": "Customer reports that several XtremeX helmets have broken buckles that won't secure the helmet properly. The customer prefers a replacement for the damaged helmets. The agent confirms the order number and starts the process to send out replacements for the damaged helmets. The customer should expect the new shipment of ten XtremeX helmets with functioning buckles to arrive within 3-5 business days."
}
Streamlit アプリケーションの構築
最後に、Snowflake 内で Streamlit アプリケーションを構築しました。このアプリでは、ユーザーがテキストを入力し、要約、翻訳、感情分析を行うことができます。以下のコードを使用して、Snowsight 上で Streamlit アプリケーションを作成しました。
import streamlit as st
from snowflake.snowpark.context import get_active_session
st.set_page_config(layout='wide')
session = get_active_session()
def summarize():
with st.container():
st.header("JSON Summary With Snowflake Arctic")
entered_text = st.text_area("Enter text",label_visibility="hidden",height=400,placeholder='Enter text. For example, a call transcript.')
btn_summarize = st.button("Summarize",type="primary")
if entered_text and btn_summarize:
entered_text = entered_text.replace("'", "\\'")
prompt = f"Summarize this transcript in less than 200 words. Put the product name, defect if any, and summary in JSON format: {entered_text}"
cortex_prompt = "'[INST] " + prompt + " [/INST]'"
cortex_response = session.sql(f"select snowflake.cortex.complete('snowflake-arctic', {cortex_prompt}) as response").to_pandas().iloc[0]['RESPONSE']
st.json(cortex_response)
def translate():
supported_languages = {'German':'de','French':'fr','Korean':'ko','Portuguese':'pt','English':'en','Italian':'it','Russian':'ru','Swedish':'sv','Spanish':'es','Japanese':'ja','Polish':'pl'}
with st.container():
st.header("Translate With Snowflake Cortex")
col1,col2 = st.columns(2)
with col1:
from_language = st.selectbox('From',dict(sorted(supported_languages.items())))
with col2:
to_language = st.selectbox('To',dict(sorted(supported_languages.items())))
entered_text = st.text_area("Enter text",label_visibility="hidden",height=300,placeholder='Enter text. For example, a call transcript.')
btn_translate = st.button("Translate",type="primary")
if entered_text and btn_translate:
entered_text = entered_text.replace("'", "\\'")
cortex_response = session.sql(f"select snowflake.cortex.translate('{entered_text}','{supported_languages[from_language]}','{supported_languages[to_language]}') as response").to_pandas().iloc[0]['RESPONSE']
st.write(cortex_response)
def sentiment_analysis():
with st.container():
st.header("Sentiment Analysis With Snowflake Cortex")
entered_text = st.text_area("Enter text",label_visibility="hidden",height=400,placeholder='Enter text. For example, a call transcript.')
btn_sentiment = st.button("Sentiment Score",type="primary")
if entered_text and btn_sentiment:
entered_text = entered_text.replace("'", "\\'")
cortex_response = session.sql(f"select snowflake.cortex.sentiment('{entered_text}') as sentiment").to_pandas().iloc[0]['SENTIMENT']
st.text(f"Sentiment score: {cortex_response}")
st.caption("Note: Score is between -1 and 1; -1 = Most negative, 1 = Positive, 0 = Neutral")
page_names_to_funcs = {
"JSON Summary": summarize,
"Translate": translate,
"Sentiment Analysis": sentiment_analysis,
}
selected_page = st.sidebar.selectbox("Select", page_names_to_funcs.keys())
page_names_to_funcs[selected_page]()
アプリケーション実行後に表示される画面上のテキストボックスにトランスクリプトを入力し、Summrize ボタンを押します。
Customer: Hello!
Agent: Hello! I hope you're having a great day. To best assist you, can you please share your first and last name and the company you're calling from?
Customer: Sure, I'm Michael Green from SnowSolutions.
Agent: Thanks, Michael! What can I help you with today?
Customer: We recently ordered several DryProof670 jackets for our store, but when we opened the package, we noticed that half of the jackets have broken zippers. We need to replace them quickly to ensure we have sufficient stock for our customers. Our order number is 60877.
Agent: I apologize for the inconvenience, Michael. Let me look into your order. It might take me a moment.
Customer: Thank you.
要約処理が実行され、以下のような結果が出力されます。
{
"product_name":"DryProof670 jackets",
"defect":"broken zippers",
"summary":
"Customer reports that half of the DryProof670 jackets they received
have broken zippers and need to be replaced as soon as possible."
}
また、Arctic 以外のモデルを使用した場合に結果がどのように異なるのかを見てみましょう。これには、Streamlit のソースコードを以下のように修正します。
- 16 行目の snowflake-arctic を llama3.1-70b に置換する。
- 17 行目の st.json(cortex_response)を st.write(cortex_response)に置換する。
修正したアプリケーションに同じテキストを入力した結果は以下のようになります。両者に違いがあること、Arctic の方がより簡潔にまとめていることがわかります。
Here is a summary of the transcript in under 200 words in JSON format:
{
"product": "DryProof670 jackets",
"defect": "broken zippers",
"summary": "Michael Green from SnowSolutions called to report a defect in their recent order of DryProof670 jackets. Half of the jackets received had broken zippers. The customer needs a replacement quickly to ensure sufficient stock for their customers. The agent apologized for the inconvenience and is investigating the issue."
}
Let me know if you'd like me to make any changes!
4. まとめ
このチュートリアルを通じて、Snowflake Cortex と Arctic を使用して、AI を活用したデータ分析の基本を学びました。特に、自然言語処理を用いたデータの翻訳、感情分析、要約の実施方法を理解できました。また、Streamlit を使ってインタラクティブなアプリケーションを構築することで、実際のビジネスシナリオにおける AI の活用方法を体験しました。
Snowflake の AI 関連のチュートリアルは他にもたくさんあるので、引き続き触れていきたいと思います。
Discussion