はじめに
Oracle CloudのAutonomous Databaseで提供される自然言語によるクエリ実行(SELECT AI)は、DBMS_CLOUD_AIパッケージを使用して行われ、PL/SQLがインタフェースになっています。2025年8月に Githubに、「Select AI for Python」が公開され、Pythonを使用してDBMS_CLOUD_AIを起動するのに役立つPythonモジュール「select_ai」が提供されました。
同時に提供されているサンプルプログラムを動かしてみました。
事前準備
- Python環境
- Select AI Python API(select_aiモジュール)は、Pythonバージョン3.9、3.10、3.11、3.12および3.13をサポートしています。
- PIP
- Oracle Cloud Infrastructure CLI構成ファイルでのプロファイル
- 参考)CLI構成ファイル
- oci cliのインストールは必須ではありません。
- (オプション)Autonomous Databaseに接続用のtnsnames.oraやウォレット
「select_ai」モジュールのインストール
Github より「Select AI for Python」を入手し、作業用ディレクトリに展開し、「select_ai」モジュールのインストール
$ python3 -m pip install select_ai
Defaulting to user installation because normal site-packages is not writeable
Collecting select_ai
Downloading select_ai-1.0.0.dev7-py3-none-any.whl (27 kB)
Collecting pandas==2.2.3
Downloading pandas-2.2.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (13.1 MB)
<略>
Installing collected packages: tzdata, python-dateutil, numpy, pandas, oracledb, select-ai
Successfully installed numpy-2.0.2 oracledb-3.3.0 pandas-2.2.3 python-dateutil-2.9.0.post0 select-ai-1.0.0.dev7 tzdata-2025.2
$
データベース接続の確認
環境変数の設定
データベース管理者ユーザとパスワード、SELECT AI実行データベースユーザとパスワード、データベース接続情報を環境変数として設定
export SELECT_AI_ADMIN_USER=admin
export SELECT_AI_ADMIN_PASSWORD=<PASSWORD>
export SELECT_AI_USER=PYTHONAI
export SELECT_AI_PASSWORD=<PASSWORD>
export SELECT_AI_DB_CONNECT_STRING=atp23ai_medium
export TNS_ADMIN=/u01/app/wallet
以下のような select_ai_connection_test.py を作成しデータベース接続を確認。
import select_ai
user = "<your_db_user>"
password = "<your_db_password>"
dsn = "<your_db_dsn>"
select_ai.connect(user=user, password=password, dsn=dsn)
$ python3 select_ai_connection_test.py
Connected to the Database
サンプルスクリプトの実行
sampleディレクトリにいくつかのサンプルスクリプトがありますので、実行してみました。
AI サービスプロバイダーの有効化
パッケージDBMS_CLOUD、DBMS_CLOUD_AIおよびDBMS_CLOUD_PIPELINEに対する実行権限を付与します。
$ python3 enable_ai_provider.py
Enabled AI provider for user: PYTHONAI
AI クレデンシャルの作成
OCI Gen AIサービス・プロバイダに対して認証するための資格証明オブジェクトを作成します。
$ python3 create_ai_credential.py
Created credential: my_oci_ai_profile_key
AI プロファイルの作成
SHスキーマのオブジェクトにアクセスを許可するAIプロファイル「oci_ai_profile」の作成
$ python3 profile_create.py
Created profile oci_ai_profile
Profile attributes are: {'annotations': None,
'case_sensitive_values': None,
'comments': None,
'constraints': None,
'conversation': None,
'credential_name': 'my_oci_ai_profile_key',
'enable_source_offsets': None,
'enable_sources': None,
'enforce_object_list': None,
'max_tokens': '1024',
'object_list': '[{"owner":"SH"}]',
'object_list_mode': None,
'provider': OCIGenAIProvider(embedding_model=None, model=None, provider_name='oci', provider_endpoint=None, region='us-chicago-1', oci_apiformat='GENERIC', oci_compartment_id=None, oci_endpoint_id=None, oci_runtimetype=None),
'seed': None,
'stop_tokens': None,
'streaming': None,
'temperature': None,
'vector_index_name': None}
$
Narrate の実行 (問合せの出力を自然言語で説明し、技術的な専門知識がなくてもユーザーが結果にアクセス)
select_ai.Action.NARRATE (DBMS_CLOUD_AI.GENERATEファンクションのAction=narrate)の実行
プロンプト:「How many promotions are there in the sh database?」
$ python3 profile_narrate.py
There are 503 promotions in the database.
# -----------------------------------------------------------------------------
# Copyright (c) 2025, Oracle and/or its affiliates.
#
# Licensed under the Universal Permissive License v 1.0 as shown at
# http://oss.oracle.com/licenses/upl.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# profile_narrate.py
#
# Narrate the description of the SQL resultset
# -----------------------------------------------------------------------------
import os
import select_ai
user = os.getenv("SELECT_AI_USER")
password = os.getenv("SELECT_AI_PASSWORD")
dsn = os.getenv("SELECT_AI_DB_CONNECT_STRING")
select_ai.connect(user=user, password=password, dsn=dsn)
profile = select_ai.Profile(
profile_name="oci_ai_profile",
)
narration = profile.narrate(
prompt="How many promotions are there in the sh database?"
)
print(narration)
Show SQL の実行 (生成されたSQL文を実行せずに表示)
select_ai.Action.SHOWSQL (DBMS_CLOUD_AI.GENERATEファンクションのAction=showql)の実行
プロンプト:「How many promotions are there in the sh database?」
$ python3 profile_show_sql.py
SELECT
COUNT("p"."PROMO_ID") AS "Number of Promotions"
FROM
"SH"."PROMOTIONS" "p"
$
# -----------------------------------------------------------------------------
# Copyright (c) 2025, Oracle and/or its affiliates.
#
# Licensed under the Universal Permissive License v 1.0 as shown at
# http://oss.oracle.com/licenses/upl.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# profile_show_sql.py
#
# Show the generated SQL without executing it
# -----------------------------------------------------------------------------
import os
import select_ai
user = os.getenv("SELECT_AI_USER")
password = os.getenv("SELECT_AI_PASSWORD")
dsn = os.getenv("SELECT_AI_DB_CONNECT_STRING")
select_ai.connect(user=user, password=password, dsn=dsn)
profile = select_ai.Profile(profile_name="oci_ai_profile")
sql = profile.show_sql(
prompt="How many promotions are there in the sh database?"
)
print(sql)
Run SQL の実行 (自然言語プロンプトから生成されたSQL問合せを実行)
select_ai.Action.RUNSQL (DBMS_CLOUD_AI.GENERATEファンクションのAction=runql)の実行
プロンプト:「How many promotions are there in the sh database?」
$ python3 profile_run_sql.py
Index(['Number of Promotions'], dtype='object')
Number of Promotions
0 503
$
# -----------------------------------------------------------------------------
# Copyright (c) 2025, Oracle and/or its affiliates.
#
# Licensed under the Universal Permissive License v 1.0 as shown at
# http://oss.oracle.com/licenses/upl.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# profile_run_sql.py
#
# Return a pandas.Dataframe built using the resultset of the generated SQL
# -----------------------------------------------------------------------------
import os
import select_ai
user = os.getenv("SELECT_AI_USER")
password = os.getenv("SELECT_AI_PASSWORD")
dsn = os.getenv("SELECT_AI_DB_CONNECT_STRING")
select_ai.connect(user=user, password=password, dsn=dsn)
profile = select_ai.Profile(profile_name="oci_ai_profile")
df = profile.run_sql(
prompt="How many promotions are there in the sh database?"
)
print(df.columns)
print(df)
explainql の実行 (生成されたSQL問合せの説明)
select_ai.Action.EXPLAINSQL (DBMS_CLOUD_AI.GENERATEファンクションのAction=explainql)の実行
プロンプト:「How many promotions are there in the sh database?」
$ python3 profile_explain_sql.py
MY OCI AI Profile
``sql
SELECT
COUNT("PROMO_ID") AS "Number of Promotions"
FROM
"SH"."PROMOTIONS" "p";
``
**Explanation:**
* We use the `COUNT` function to count the number of rows in the `"PROMOTIONS"` table, which represents the number of promotions.
* We use the table alias `"p"` to refer to the `"PROMOTIONS"` table, which makes the query more readable.
* We enclose the table name and column name in double quotes to ensure that the query is case-sensitive.
* Since we are not performing any string comparisons in the `WHERE` clause, we do not need to use the `UPPER` function.
* The result is returned as a single column with the alias `"Number of Promotions"`.
**Example Use Case:**
Suppose we want to know the total number of promotions in the `sh` database. We can run this query to get the count. The result will be a single row with a single column containing the count of promotions.
**Note:** The actual result will depend on the data in the `"PROMOTIONS"` table. If the table is empty, the result will be 0. If the table contains data, the result will be the number of rows in the table.
$
# -----------------------------------------------------------------------------
# Copyright (c) 2025, Oracle and/or its affiliates.
#
# Licensed under the Universal Permissive License v 1.0 as shown at
# http://oss.oracle.com/licenses/upl.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# profile_explain_sql.py
# -----------------------------------------------------------------------------
import os
import select_ai
user = os.getenv("SELECT_AI_USER")
password = os.getenv("SELECT_AI_PASSWORD")
dsn = os.getenv("SELECT_AI_DB_CONNECT_STRING")
select_ai.connect(user=user, password=password, dsn=dsn)
profile = select_ai.Profile(
profile_name="oci_ai_profile",
)
print(profile.description)
explanation = profile.explain_sql(
prompt="How many promotions are there in the sh database?"
)
print(explanation)
Chat の実行
select_ai.Action.CHAT (DBMS_CLOUD_AI.GENERATEファンクションのAction=chat)の実行
プロンプト:「What is OCI ?」
$ python3 profile_chat.py
OCI stands for several things, depending on the context:
1. **Oracle Cloud Infrastructure**: OCI is a cloud computing platform offered by Oracle Corporation. It provides a range of services, including computing, storage, networking, and database management, to help businesses build, deploy, and manage applications in the cloud.
2. **Open Container Initiative**: OCI is a Linux Foundation project that aims to create an open standard for container runtime and image format. The goal is to provide a common interface for containerization, making it easier to develop, deploy, and manage containers across different platforms.
3. **Overseas Citizenship of India**: OCI is a citizenship status granted by the Government of India to individuals who are of Indian origin but have acquired citizenship of another country. It provides certain benefits and privileges, such as visa-free travel to India and the ability to live and work in the country.
4. **Other meanings**: OCI can also stand for other things, such as "Organizational Change Initiative" or "Operational Control Interface", depending on the context in which it is used.
Without more information, it's difficult to determine which definition is most relevant. If you have any additional context or clarification, I'd be happy to try and provide a more specific answer!
$
# -----------------------------------------------------------------------------
# Copyright (c) 2025, Oracle and/or its affiliates.
#
# Licensed under the Universal Permissive License v 1.0 as shown at
# http://oss.oracle.com/licenses/upl.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# profile_chat.py
#
# Chat using an AI Profile
# -----------------------------------------------------------------------------
import os
import select_ai
user = os.getenv("SELECT_AI_USER")
password = os.getenv("SELECT_AI_PASSWORD")
dsn = os.getenv("SELECT_AI_DB_CONNECT_STRING")
select_ai.connect(user=user, password=password, dsn=dsn)
profile = select_ai.Profile(profile_name="oci_ai_profile")
response = profile.chat(prompt="What is OCI ?")
print(response)
List profiles
AIプロファイルのリスト表示
$ python3 profiles_list.py
OCI_AI_PROFILE
# -----------------------------------------------------------------------------
# Copyright (c) 2025, Oracle and/or its affiliates.
#
# Licensed under the Universal Permissive License v 1.0 as shown at
# http://oss.oracle.com/licenses/upl.
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# profile_list.py
#
# List all the profile names matching a certain pattern
# -----------------------------------------------------------------------------
import os
import select_ai
user = os.getenv("SELECT_AI_USER")
password = os.getenv("SELECT_AI_PASSWORD")
dsn = os.getenv("SELECT_AI_DB_CONNECT_STRING")
select_ai.connect(user=user, password=password, dsn=dsn)
profile = select_ai.Profile()
# matches all the profiles
for fetched_profile in profile.list():
print(fetched_profile.profile_name)
さいごに
「Select AI for Python」のPythonモジュール「select_ai」を使うことでPython言語でSELECT AIを実行でき、SELECT AIの活用シーンが増えると思います。
サンプルには SELECT AIのDBMS_CLOUD_AI.GENERATEファンクションに該当する操作以外に、synthetic data generation(合成データ生成)、検索拡張生成(RAG)などがあります。
また、「Select AI for Python」のドキュメントもGithubのソースから生成できます。