2
1

Databricksで構築するはじめての複合AIシステム

Posted at

新しいチュートリアルが追加されていました。ツールを活用したエージェント型のアプリケーションをウォークスルーします。

インストール

%pip install dbdemos
import dbdemos
dbdemos.install('llm-tools-functions', catalog='takaakiyayoi_catalog', schema='dbdemos_agent_tools')

llm-tools-functionsフォルダに関連ノートブックが作成され、クラスターも起動します。

設定

configノートブックには、カタログやスキーマ名、Vector Searchエンドポイント名が記載されています。必要に応じて変更ください。

config
VECTOR_SEARCH_ENDPOINT_NAME="one-env-shared-endpoint-13"

catalog = "takaakiyayoi_catalog"
dbName = db = "dbdemos_agent_tools"
volume_name = "dbdemos_agent_volume"

複合AIシステム:製品を販売するAIスタイリストスペシャリストの構築

00-AI-function-tools-introductionがメインのノートブックとなります。

複合AIシステムとは

LLMは生成された質問に答えるのに優れています。しかし、これだけではお客様に価値を提供するには不十分です。

価値ある回答を提供するためには、ユーザー(お客様の契約ID、サポートに送った最後のメール、最新の販売レポートなど)に特有の追加情報が必要です。

複合AIシステムは、この課題に対応するために設計されています。これらは、異なるアクション(情報の取得や外部システムへの作用)に特化した複数のエンティティ(ツール)で構成される、より高度なAIデプロイメントです。

ハイレベルには、AIにカスタム関数のセットを構築して提示します。その後、LLMはそれについて推論し、顧客のニーズに答えるためにどのツールを呼び出し、どの情報を収集するべきかを決定します。

Databricks Mosaic AIエージェントフレームワークを使用した複合AIシステムの構築

Databricksは、以下を提供することでこれを簡素化します:

  • UCを活用して関数(ツール)を作成および保存する
  • 関数を安全な方法で実行する
  • 選択したツールについて推論し、それらを適切に連携させて質問に答える

このデモで実装するAIシステムの概要は次のとおりです:

agent_flow.png

%pip install -U databricks-sdk==0.23.0 langchain-community==0.2.10 langchain-openai==0.1.19 mlflow==2.14.3 faker
dbutils.library.restartPython()
%run ./_resources/00-init $reset_all=false

ツールの作成: Unity Catalogにおける関数の活用

LLMが実行できる関数の定義からスタートしましょう。これらの関数には、シンプルなSQLから高度なPythonまで任意のロジックを含めることができます。

数学の計算: インチをセンチメートルに変換する

私たちのオンラインショップは全地域で販売しており、顧客がしばしばインチをセンチメートルに変換したいと求めています。しかし、単純なLLMは数学の実行が得意ではありません。これを解決するために、変換を行うシンプルな関数を作成しましょう。

この関数をUnity Catalog内に保存します。このノートブックで作成された関数を確認するためにエクスプローラーを開くことができます。

注: これはこのデモのための非常にシンプルな最初の例です。後ほど、より広範な数学ツールを実装します。

インチをセンチメートルに変換

%sql
CREATE OR REPLACE FUNCTION convert_inch_to_cm(size_in_inch FLOAT)
RETURNS FLOAT
LANGUAGE SQL
COMMENT 'convert size from inch to cm'
RETURN size_in_inch * 2.54;

-- 関数をテストしましょう
SELECT convert_inch_to_cm(10) as 10_inches_in_cm;

Screenshot 2024-10-04 at 19.54.36.png

内部データを取得するツールの実行:最新の顧客注文を取得する

スタイリストアシスタントがすべての既存の顧客注文をリストできるようにしましょう。

%sql
CREATE OR REPLACE FUNCTION get_customer_orders ()
RETURNS TABLE(user_id STRING,
  id STRING,
  transaction_date STRING,
  item_count DOUBLE,
  amount DOUBLE,
  order_status STRING)
COMMENT 'Returns a list of customer orders for the given customer ID (expect a UUID)'
LANGUAGE SQL
    RETURN
    SELECT o.* from tools_orders o 
    inner join tools_customers c on c.id = o.user_id 
    where email=current_user() ORDER BY transaction_date desc;

SELECT * FROM get_customer_orders();

Screenshot 2024-10-04 at 19.55.32.png

上で00-initを実行した際に、自分のメールアドレスと紐付けられた注文データが作成されています。

Python関数を実行してリアルタイムで外部データセットを取得する:天気を取得する

スタイリストアシスタントが天気に基づいておすすめを提供できるように、経度/緯度に基づいて天気を取得するツールを追加しましょう。Pythonを使用して外部のWeather APIを呼び出します。

%sql
CREATE OR REPLACE FUNCTION get_weather(latitude DOUBLE, longitude DOUBLE)
RETURNS STRUCT<temperature_in_celsius DOUBLE, rain_in_mm DOUBLE>
LANGUAGE PYTHON
COMMENT 'This function retrieves the current temperature and rain information for a given latitude and longitude using the Open-Meteo API.'
AS
$$
  try:
    import requests as r
    #Note: this is provided for education only, non commercial - please get a license for real usage: https://api.open-meteo.com. Let s comment it to avoid issues for now
    #weather = r.get(f'https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m,rain&forecast_days=1').json()
    return {
      "temperature_in_celsius": weather["current"]["temperature_2m"],
      "rain_in_mm": weather["current"]["rain"]
    }
  except:
    return {"temperature_in_celsius": 25.0, "rain_in_mm": 0.0}
$$;

-- let's test our function:
SELECT get_weather(52.52, 13.41) as weather;

Screenshot 2024-10-04 at 19.56.44.png

この実装はダミーです。実際にAPIを呼び出しているわけではありません。

特定のプロンプトを使用してLLMを呼び出す関数を作成する

顧客のコンテキストに基づいてアクションを実行するために、LLMが使用できるカスタムプロンプトを含むツールを登録することもできます。

現在の天候に基づいて、ユーザーにスタイルを推奨するツールを作成しましょう。

%sql
CREATE OR REPLACE FUNCTION recommend_outfit_description(requested_style STRING, temperature_in_celsius FLOAT, rain_in_mm FLOAT)
RETURNS STRING
LANGUAGE SQL
COMMENT 'This function generate a stylist outfit description based on initial request and the current weather.'
RETURN SELECT ai_query('databricks-meta-llama-3-70b-instruct',
    CONCAT("You are a stylist assistant. Your goal is to give recommendation on what would be the best outfit for today. The current temperature is ",temperature_in_celsius ," celsius and rain is:", rain_in_mm, "mm. Give size in inches if any. Don't assume customer size if they don't share it. Give ideas of colors and other items to match. The user added this instruction based on what they like: ", requested_style)
  ) AS recommended_outfit;

-- let's test our function:
SELECT recommend_outfit_description("I need a dress for an interview.", 30.1, 0.0)
Perfect weather for a stylish and confident interview outfit!

Considering the warm temperature (30.1°C) and no rain, I'd recommend a lightweight, breathable, and professional dress. Here's a suggestion:

**Dress:**
Opt for a knee-length or just above the knee dress made from a comfortable, moisture-wicking fabric like cotton, linen, or a cotton-blend. A-line dresses or fit-and-flare styles are great for creating a flattering silhouette.

**Color:**
Neutral colors are always a safe bet for interviews. Consider:

* Navy blue (a classic choice)
* Charcoal grey
* Beige or light brown
* White or cream (if you want to add a pop of color with accessories)

**Additional details:**

* Look for a dress with a modest neckline and sleeves (cap sleeves or short sleeves are fine).
* A dress with a bit of texture or interest, like a subtle pattern or a belt, can add visual appeal.
* If you want to add some color, consider a dress with a small, tasteful print, like a tiny floral or geometric pattern.

**Shoes:**
Pair your dress with a pair of low- to moderate-heeled shoes in a neutral color that complements your dress. Pumps, loafers, or ballet flats are all great options.

**Accessories:**

* Keep jewelry simple and understated, like a classic watch, simple earrings, and a slim necklace.
* Add a belt to define your waist and break up the dress.
* Carry a simple, professional handbag in a neutral color.

**Size:**
Please share your size (bust, waist, and length) so I can provide more tailored recommendations.

How do these suggestions sound? Do you have any specific preferences or style inclinations you'd like to share?

類似コンテンツを見つけるためのツールとしてVector Searchを使用する

次に、記事の説明に基づいて類似のアイテムを推奨するツールを追加しましょう。

Databricks Vector Searchを使用して、リアルタイムの類似性検索を実行し、データベースから提案できる記事を返します。

これを行うには、新しい vector_search SQL関数を活用することができます。詳細については、ドキュメントを参照してください。

このデモを簡単にするために、vector_searchへの呼び出しを偽装し、デモの事前ロードなしで動作するようにします。

%sql
-- Generate fake data instead of calling the VS index with vector_search;
CREATE OR REPLACE FUNCTION find_clothes_matching_description (description STRING)
RETURNS TABLE (id BIGINT, name STRING, color STRING, category STRING, price DOUBLE, description STRING)
COMMENT 'Finds existing clothes in our catalog matching the description using AI query and returns a table of results.'
RETURN
SELECT clothes.* FROM (
  SELECT explode(from_json(
    ai_query(
      'databricks-meta-llama-3-70b-instruct', 
      CONCAT(
        'returns a json list of 3 json object clothes: <"id": bigint, "name": string, "color": string, "category": string, "price": double, "description": string>. These clothes should match the following user description: ', description, '. Return only the answer as a javascript json object ready to be parsed, no comment or text or javascript or ``` at the beginning.' ) ), 'ARRAY<STRUCT<id: BIGINT, name: STRING, color: STRING, category: STRING, price: DOUBLE, description: STRING>>' )) AS clothes );

-- let's test our function:
SELECT * FROM find_clothes_matching_description('a red dress');

Screenshot 2024-10-04 at 19.59.10.png

Databricks Playgroundを使用して、関数をテストする

Databricks Playgroundは、組み込みの関数との統合を提供します。Playgroundは利用可能な関数を分析し、適切な回答をするためにそれらを呼び出します。

Screenshot 2024-10-04 at 20.03.11.png

Playgroundで関数を試すには、以下の手順を実行します:

  • Playgroundを開く
  • ツールをサポートするモデル(例:Llama3.1)を選択する
  • モデルが利用する関数を追加する(catalog.schema.function_nameのような形式)
  • 質問をする(例:インチをセンチメートルに変換する)と、Playgroundが魔法を使って回答します!

Playgroundのツールはプレビュー版です。詳細と有効化については、Databricksのアカウントチームにお問い合わせください。

Databricks UC関数を活用したAIシステムの構築

これらのツールは、カスタムモデルでも直接活用することができます。この場合、関数のチェーンと呼び出しは自分で行う必要があります(プレイグラウンドは代わりに行ってくれます!)

Langchainを使用すると、簡単にカスタムAIシステムを作成できます。Langchainモデルと既存のツールのリスト(今回は作成した関数)を使用します。

MLflowトレースの有効化

MLflowトレースを有効にすると、以下のことが可能です:

  • このノートブックでチェーンのトレース可視化を表示する
  • インファレンステーブルを介して本番環境でチェーンのトレースをキャプチャする
  • Mosaic AI評価スイートを使用してチェーンを評価する
import mlflow
mlflow.langchain.autolog(disable=False)

Unityカタログからツールを作成して開始

デモ用のツールとして使用する関数を選択するためにUCFunctionToolkitを使用しましょう:

from langchain_community.tools.databricks import UCFunctionToolkit
import pandas as pd

# 共有ウェアハウスを取得します。詳細は_resources/01-initを参照してください。
wh = get_shared_warehouse(name=None) 

def get_tools():
    return (
        UCFunctionToolkit(warehouse_id=wh.id)
        # 関数をツールとして含めるには、その修飾名を使用します。
        # "{catalog_name}.{schema_name}.*" を使用してスキーマ内のすべての関数を取得できます。
        .include(f"{catalog}.{db}.*")
        .get_tools())

# ツールをテーブルで表示します。詳細は_resource/00-initを参照してください。
display_tools(get_tools())

Screenshot 2024-10-04 at 20.04.17.png

作成したツールを使用してlangchainエージェントを作成しましょう

チャットの作成

from langchain_openai import ChatOpenAI
from databricks.sdk import WorkspaceClient

# 注意: langchain_community.chat_models.ChatDatabricks はまだ create_tool_calling_agent をサポートしていません - 近々利用可能になります。今のところ ChatOpenAI を使用しましょう
llm = ChatOpenAI(
  base_url=f"{WorkspaceClient().config.host}/serving-endpoints/",
  api_key=dbutils.notebook.entry_point.getDbutils().notebook().getContext().apiToken().get(),
  model="databricks-meta-llama-3-70b-instruct"
)

プロンプトの定義

from langchain_core.prompts import ChatPromptTemplate
from langchain_community.chat_models import ChatDatabricks

def get_prompt(history = [], prompt = None):
    if not prompt:
            prompt = """あなたはおしゃれなファッションアシスタントです。ユーザーに洋服をおすすめすることがあなたの仕事です。以下のツールを使用できます:
    - convert_inch_to_cmを使用して、ユーザーがそれを求めた場合にインチをセンチメートルに変換します。
    - get_customer_ordersを使用して、注文のリストとそのステータス、合計金額、アイテム数を取得します。
    - find_clothes_matching_descriptionを使用して、内部カタログから既存の洋服を検索し、ユーザーにアイテムを提案します。
    - recommend_outfitを使用して、ユーザーがスタイルを求めた場合。この関数は天気をパラメータとして受け取ります。この関数を呼び出す前に、現在の気温と雨を取得するためにget_weather関数を使用してください。現在のユーザーの位置は52.52、13.41です。

    各ステップに適切なツールを使用し、ユーザーに合理的な回答を提供してください。ユーザーにツールについて言及しないでください。ユーザーが求めていることにのみ答えてください。質問がツールやスタイル/洋服に関連していない場合は、「申し訳ありませんが、お答えできません」とお伝えください。"""
    return ChatPromptTemplate.from_messages([
            ("system", prompt),
            ("human", "{input}"),
            ("placeholder", "{agent_scratchpad}"),
    ])
from langchain.agents import AgentExecutor, create_tool_calling_agent
prompt = get_prompt()
tools = get_tools()
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

試してみましょう: シンプルなサイズの変換を行うようにお願いします。

内部では、我々が作成した数学の変換関数を使って欲しいのです:

agent_executor.invoke({"input": "12インチは何センチ?"})
> Entering new AgentExecutor chain...

Invoking: `takaakiyayoi_catalog__dbdemos_agent_tools__convert_inch_to_cm` with `{'size_in_inch': 12}`


{"format": "SCALAR", "value": "30.48", "truncated": false}12インチは30.48センチメートルです。

> Finished chain.
{'input': '12インチは何センチ?', 'output': '12インチは30.48センチメートルです。'}

トレースも表示されます。

Screenshot 2024-10-04 at 20.05.51.png

agent_executor.invoke({"input": "私の最後の注文は何?"})


> Entering new AgentExecutor chain...

Invoking: `takaakiyayoi_catalog__dbdemos_agent_tools__get_customer_orders` with `{}`


{"format": "CSV", "value": "user_id,id,transaction_date,item_count,amount,order_status\nd8ca793f-7f06-42d3-be1b-929e32fc8bc9,3c45e201-a78c-4b49-aa3b-ba387b8f27bb,10-01-2024 06:19:25,2.0,56.0,Delivered\nd8ca793f-7f06-42d3-be1b-929e32fc8bc9,67d638eb-60fa-473e-96cf-5a9b2241adb8,10-01-2024 06:15:35,2.0,42.0,Delivered\nd8ca793f-7f06-42d3-be1b-929e32fc8bc9,29b2fd7d-c04c-458b-9dba-ccdd181ee33d,10-01-2024 05:46:50,1.0,38.0,Shipped\nd8ca793f-7f06-42d3-be1b-929e32fc8bc9,ca007121-3bf8-40cf-adf0-f920a69c9e41,10-01-2024 05:21:51,2.0,52.0,Shipped\n", "truncated": false}Your last order was order #3c45e201-a78c-4b49-aa3b-ba387b8f27bb, placed on 10-01-2024 06:19:25. It contained 2 items and cost $56.00. The order status is Delivered.

> Finished chain.

複数ツールのチェーン

複数のツールを用い、あるツールから別のツールに値を引き渡すことで、このエージェントが適切にコールをチェーンするかどうかを確認しましょう。今日の外出着を訪ねると、最初にLLMが気候を取得することを期待します。

agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
answer = agent_executor.invoke({"input": "今日の面接にはどんなスタイルをおすすめしますか?"})


> Entering new AgentExecutor chain...

Invoking: `takaakiyayoi_catalog__dbdemos_agent_tools__get_weather` with `{'latitude': 52.52, 'longitude': 13.41}`


{"format": "SCALAR", "value": "{\"temperature_in_celsius\":\"25.0\",\"rain_in_mm\":\"0.0\"}", "truncated": false}
Invoking: `yayoi_catalog__dbdemos_agent_tools__recommend_outfit_description` with `{'rain_in_mm': 0.0, 'requested_style': 'interview', 'temperature_in_celsius': 25.0}`


{"format": "SCALAR", "value": "Lovely day ahead! Given the pleasant temperature of 25.0\u00b0C and no rain, I'd be delighted to suggest an outfit for an interview.\n\nFor a professional and stylish look, I recommend:\n\n**For Women:**\n\n* A tailored white or light-colored blouse (e.g., pale blue or pastel pink) with a modest neckline. Consider a classic style with a relaxed fit, perhaps with a subtle texture or pattern.\n* A pair of well-fitted, dark-washed trousers or a pencil skirt in navy, black, or charcoal gray. These neutral colors will create a sharp, professional look.\n* A tailored blazer in a neutral color like navy, black, or gray to add a polished touch. Look for one with a fitted silhouette and a length that hits just above the hip.\n\n**For Men:**\n\n* A crisp, white dress shirt with a slim collar. Opt for a classic fit with a subtle texture or pattern.\n* A pair of dark-washed, fitted trousers in navy, black, or charcoal gray. These will create a sharp, professional look.\n* A tailored blazer in a neutral color like navy, black, or gray to add a polished touch. Look for one with a fitted silhouette and a length that hits just above the hip.\n\n**Common Recommendations:**\n\n* Add a statement piece of jewelry, such as a simple watch, a classic necklace, or a pair of elegant earrings, to add a touch of personality to your outfit.\n* Choose a pair of closed-toe shoes with a low to moderate heel. For women, consider a pair of loafers, ballet flats, or low-heeled pumps. For men, opt for dress shoes in leather or a leather-like material.\n* Keep the color palette neutral and professional, with a focus on navy, black, gray, and white. You can add a pop of color with a tie, scarf, or handbag, but keep it subtle.\n\n**Additional Tips:**\n\n* Make sure your outfit is clean, ironed, and well-fitted to create a polished, professional look.\n* Pay attention to grooming: ensure your hair is clean and styled neatly, and your nails are trimmed and clean.\n* Consider the company culture and dress code when choosing your outfit. If you're still unsure, it's always better to err on the side of caution and dress more formally.\n\nI hope these recommendations help you create a stylish and professional outfit for your interview!", "truncated": false}Lovely day ahead! Given the pleasant temperature of 25.0°C and no rain, I'd be delighted to suggest an outfit for an interview.

For a professional and stylish look, I recommend:

**For Women:**

* A tailored white or light-colored blouse (e.g., pale blue or pastel pink) with a modest neckline. Consider a classic style with a relaxed fit, perhaps with a subtle texture or pattern.
* A pair of well-fitted, dark-washed trousers or a pencil skirt in navy, black, or charcoal gray. These neutral colors will create a sharp, professional look.
* A tailored blazer in a neutral color like navy, black, or gray to add a polished touch. Look for one with a fitted silhouette and a length that hits just above the hip.

**For Men:**

* A crisp, white dress shirt with a slim collar. Opt for a classic fit with a subtle texture or pattern.
* A pair of dark-washed, fitted trousers in navy, black, or charcoal gray. These will create a sharp, professional look.
* A tailored blazer in a neutral color like navy, black, or gray to add a polished touch. Look for one with a fitted silhouette and a length that hits just above the hip.

**Common Recommendations:**

* Add a statement piece of jewelry, such as a simple watch, a classic necklace, or a pair of elegant earrings, to add a touch of personality to your outfit.
* Choose a pair of closed-toe shoes with a low to moderate heel. For women, consider a pair of loafers, ballet flats, or low-heeled pumps. For men, opt for dress shoes in leather or a leather-like material.
* Keep the color palette neutral and professional, with a focus on navy, black, gray, and white. You can add a pop of color with a tie, scarf, or handbag, but keep it subtle.

**Additional Tips:**

* Make sure your outfit is clean, ironed, and well-fitted to create a polished, professional look.
* Pay attention to grooming: ensure your hair is clean and styled neatly, and your nails are trimmed and clean.
* Consider the company culture and dress code when choosing your outfit. If you're still unsure, it's always better to err on the side of caution and dress more formally.

I hope these recommendations help you create a stylish and professional outfit for your interview!

> Finished chain.
# 注意:実際のアプリでは、参照のためにプレビューの議論を履歴に含めるべきです。
answer = agent_executor.invoke({"input": "赤いドレスの購入リストを教えてください。"})
> Entering new AgentExecutor chain...

Invoking: `_catalog__dbdemos_agent_tools__find_clothes_matching_description` with `{'description': 'red dress'}`


{"format": "CSV", "value": "id,name,color,category,price,description\n1,Red Evening Gown,Red,Dress,120.0,A stunning red evening gown perfect for formal events.\n2,Crimson Sundress,Red,Dress,80.0,A bright red sundress ideal for summer outings.\n3,Ruby Red Bodycon,Red,Dress,90.0,A sleek red bodycon dress for a night out on the town.\n", "truncated": false}You might be interested in the following red dresses:

1. Red Evening Gown - A stunning red evening gown perfect for formal events. ($120.0)
2. Crimson Sundress - A bright red sundress ideal for summer outings. ($80.0)
3. Ruby Red Bodycon - A sleek red bodycon dress for a night out on the town. ($90.0)

> Finished chain.
displayHTML(answer['output'].replace('\n', '<br>'))
You might be interested in the following red dresses:

1. Red Evening Gown - A stunning red evening gown perfect for formal events. ($120.0)
2. Crimson Sundress - A bright red sundress ideal for summer outings. ($80.0)
3. Ruby Red Bodycon - A sleek red bodycon dress for a night out on the town. ($90.0)

元のノートブックでは、これ以降にさらに複雑なツールの例やチェーンのロギングもカバーされていますが、まずはここまで。

はじめてのDatabricks

はじめてのDatabricks

Databricks無料トライアル

Databricks無料トライアル

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1