7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Oracle Cloud][Autonomous Database]「Select AI for Python v1.2.0」を使ってみた。(2025/12/08)

Last updated at Posted at 2025-12-07

こちらの記事はOracle Cloud Infrastructure Advent Calendar 2025 シリーズ3 Day 08 の記事として書かれています。Day 07の記事は @yushibats さんの記事「【BaseDB】リカバリ・サービス(RCV)を使った自動バックアップ設定手順」でした。

はじめに

Oracle CloudのAutonomous Databaseで提供される自然言語によるクエリ実行(SELECT AI)のPythonモジュール「select_ai」の v1.2.0が提供されました。
インストールし同時に提供されているサンプルプログラムを動かしてみました。

Select AI for Python v1.2.0 新機能

  • Select AI Agentのサポート
    • select_ai.agent.Tool
    • select_ai.agent.Task
    • select_ai.agent.Agent
    • select_ai.agent.Team
  • 要約のサポート
    • ai_profile.summarize()
  • SELECT AIフィードバックのサポート
    • ai_profile.add_positive_feedback()
    • ai_profile.add_negative_feedback()
    • ai_profile.delete_feedback()
  • プロキシオブジェクトに新しいフェッチAPIが導入
    • Profile.fetch(profile_name)
    • Conversation.fetch(conversation_id)
    • Agent.fetch(agent_name)
    • Tool.fetch(tool_name)
    • Task.fetch(task_name)
    • Team.fetch(team_name)
  • 権限の付与/取り消し
    • select_ai.grant_privileges
    • select_ai.revoke_privileges
    • select_ai.grant_http_access
    • select_ai.revoke_http_access
    • 次のPL/SQLパッケージに対する権限
      • DBMS_CLOUD、DMBS_CLOUD_AI、DBMS_CLOUD_AI_AGENT、DBMS_CLOUD_PIPELINE
  • Python 3.14のサポートを追加
  • Github Actionsを使用したCIサポート

事前準備

  • Python環境
    • Select AI Python API(select_aiモジュール)は、Pythonバージョン3.9、3.10、3.11、3.12、3.13および3.14をサポートしています。
    • PIP
      • uv 環境での準備
$ curl -LsSf https://astral.sh/uv/install.sh | sh
downloading uv 0.9.15 x86_64-unknown-linux-gnu
no checksums to verify
installing to /home/opc/.local/bin
  uv
  uvx
everything's installed!
$ mkdir /home/opc/selectai1.2
$ cd /home/opc/selectai1.2
$ uv venv --python 3.14
$ source .venv/bin/activate
$ python3 -m ensurepip --upgrade
Looking in links: /tmp/tmpxvq2bxqr
Processing /tmp/tmpxvq2bxqr/pip-25.3-py3-none-any.whl
Installing collected packages: pip
Successfully installed pip-25.3
-- C++ コンパイラをインストール
$ sudo dnf install gcc-c++
  • Oracle Cloud Infrastructure CLI構成ファイルでのプロファイル
  • Autonomous Databaseに接続用のtnsnames.oraやウォレット

「select_ai」モジュールのインストール

Github より「select_ai-1.2.0.tar.gz」を入手し、作業用ディレクトリに展開し、「select_ai」モジュールのインストール

$ python3 -m pip install select_ai --upgrade
Collecting select_ai
  Using cached select_ai-1.2.0-py3-none-any.whl.metadata (4.6 kB)
Collecting oracledb (from select_ai)
  Using cached oracledb-3.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.metadata (7.7 kB)
Collecting pandas==2.2.3 (from select_ai)
  Using cached pandas-2.2.3.tar.gz (4.4 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
  Preparing metadata (pyproject.toml) ... |
done
Collecting numpy>=1.26.0 (from pandas==2.2.3->select_ai)
  Using cached numpy-2.3.5-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl.metadata (62 kB)
Collecting python-dateutil>=2.8.2 (from pandas==2.2.3->select_ai)
  Downloading python_dateutil-2.9.0.post0-py2.py3-none-any.whl.metadata (8.4 kB)
Collecting pytz>=2020.1 (from pandas==2.2.3->select_ai)
  Downloading pytz-2025.2-py2.py3-none-any.whl.metadata (22 kB)
Collecting tzdata>=2022.7 (from pandas==2.2.3->select_ai)
  Downloading tzdata-2025.2-py2.py3-none-any.whl.metadata (1.4 kB)
Collecting six>=1.5 (from python-dateutil>=2.8.2->pandas==2.2.3->select_ai)
  Downloading six-1.17.0-py2.py3-none-any.whl.metadata (1.7 kB)
Collecting cryptography>=3.2.1 (from oracledb->select_ai)
  Downloading cryptography-46.0.3-cp311-abi3-manylinux_2_34_x86_64.whl.metadata (5.7 kB)
Collecting typing_extensions>=4.14.0 (from oracledb->select_ai)
  Downloading typing_extensions-4.15.0-py3-none-any.whl.metadata (3.3 kB)
Collecting cffi>=2.0.0 (from cryptography>=3.2.1->oracledb->select_ai)
  Downloading cffi-2.0.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl.metadata (2.6 kB)
Collecting pycparser (from cffi>=2.0.0->cryptography>=3.2.1->oracledb->select_ai)
  Downloading pycparser-2.23-py3-none-any.whl.metadata (993 bytes)
Downloading select_ai-1.2.0-py3-none-any.whl (50 kB)
Using cached numpy-2.3.5-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl (16.6 MB)
Downloading python_dateutil-2.9.0.post0-py2.py3-none-any.whl (229 kB)
Downloading pytz-2025.2-py2.py3-none-any.whl (509 kB)
Downloading six-1.17.0-py2.py3-none-any.whl (11 kB)
Downloading tzdata-2025.2-py2.py3-none-any.whl (347 kB)
Downloading oracledb-3.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (2.5 MB)
   qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq 2.5/2.5 MB 87.7 MB/s  0:00:00
Downloading cryptography-46.0.3-cp311-abi3-manylinux_2_34_x86_64.whl (4.5 MB)
   qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq 4.5/4.5 MB 103.2 MB/s  0:00:00
Downloading cffi-2.0.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl (219 kB)
Downloading typing_extensions-4.15.0-py3-none-any.whl (44 kB)
Downloading pycparser-2.23-py3-none-any.whl (118 kB)
Building wheels for collected packages: pandas
  Building wheel for pandas (pyproject.toml) ... done
  Created wheel for pandas: filename=pandas-2.2.3-cp314-cp314-linux_x86_64.whl size=45531236 sha256=a01fc664612f6a7e96b78c69befb6c88462e0630a5d7ed094f1f38a796d0e7e8
  Stored in directory: /home/opc/.cache/pip/wheels/2d/2f/71/b3d0040a34711301eba6154281563ea5ff2aafd8e8023836ff
Successfully built pandas
Installing collected packages: pytz, tzdata, typing_extensions, six, pycparser, numpy, python-dateutil, cffi, pandas, cryptography, oracledb, select_ai
Successfully installed cffi-2.0.0 cryptography-46.0.3 numpy-2.3.5 oracledb-3.4.1 pandas-2.2.3 pycparser-2.23 python-dateutil-2.9.0.post0 pytz-2025.2 select_ai-1.2.0 six-1.17.0 typing_extensions-4.15.0 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=/home/opc/wallet

以下のような select_ai_connection_test.py を作成しデータベース接続を確認。

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)
print("Connected to the Database")
$ python3 select_ai_connection_test.py
Connected to the Database

SELECT AIの動作確認

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}

$

Show SQL の実行 (生成されたSQL文を実行せずに表示)

select_ai.Action.SHOWSQL (DBMS_CLOUD_AI.GENERATEファンクションのAction=showql)の実行
プロンプト:「What are customer sales by product?」

profile_show_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)
provider = select_ai.OCIGenAIProvider(region        = 'us-chicago-1',
                                      oci_apiformat = 'GENERIC')

profile_attributes = select_ai.ProfileAttributes(provider        = provider ,
                                                 credential_name = 'my_oci_ai_profile_key',
                                                 object_list     = [{'owner': 'SH'}])

profile = select_ai.Profile(profile_name = 'oci_ai_profile',
                            attributes   = profile_attributes,
                            description  = 'MY OCI AI Profile for accessing SH tables and views',
                            replace      = True)

sql = profile.show_sql(prompt = 'What are customer sales by product?')
print(sql)

実行例

$ python3 profile_show_sql.py
SELECT
  "P"."PROD_NAME" AS "Product Name",
  SUM("S"."AMOUNT_SOLD") AS "Total Sales"
FROM
  "SH"."SALES" "S"
  JOIN "SH"."PRODUCTS" "P" ON "S"."PROD_ID" = "P"."PROD_ID"
GROUP BY
  "P"."PROD_NAME"
$

文章のサマライズ

profile_summarize_content.py
# -----------------------------------------------------------------------------
# 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_summarize.py
#
# Summarize the content
# -----------------------------------------------------------------------------

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

content = """
A gas cloud in our galaxy, Sagittarius B2, contains enough alcohol to brew 400
trillion pints of beer, and some stars are so cool that you could touch them
without being burned. Meanwhile, on the exoplanet 55 Cancri e, a form of
"hot ice" exists where high pressure prevents water from becoming gas even at
high temperatures. Additionally, some ancient stars found in the Milky Way's
halo are much older than the Sun, providing clues about the early universe and
its composition
"""

select_ai.connect(user=user, password=password, dsn=dsn)
profile = select_ai.Profile(profile_name="oci_ai_profile")
summary = profile.summarize(content=content)
print(summary)

実行例

$ python3 profile_summarize_content.py
{'content': '\nA gas cloud in our galaxy, Sagittarius B2, contains enough alcohol to brew 400\ntrillion pints of beer, and some stars are so cool that you could touch them\nwithout being burned. Meanwhile, on the exoplanet 55 Cancri e, a form of\n"hot ice" exists where high pressure prevents water from becoming gas even at\nhigh temperatures. Additionally, some ancient stars found in the Milky Way\'s\nhalo are much older than the Sun, providing clues about the early universe and\nits composition\n', 'profile_name': 'oci_ai_profile'}

A gas cloud in the Sagittarius B2 galaxy contains a large amount of alcohol, while some stars are cool enough to touch without being burned. The exoplanet 55 Cancri e has a unique form of "hot ice" where water remains solid despite high temperatures due to high pressure. Ancient stars in the Milky Way's halo are older than the Sun, providing insights into the early universe's composition. These celestial phenomena showcase the diverse and complex nature of the universe.

$

URI先のサマライズ

profile_summarize_uri.py
# -----------------------------------------------------------------------------
# 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_summarize_uri.py
#
# Summarize content at a certain URI
# -----------------------------------------------------------------------------

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")
summary = profile.summarize(
    location_uri="https://en.wikipedia.org/wiki/Astronomy"
)
print(summary)

実行例

$ python3 profile_summarize_uri.py
{'location_uri': 'https://en.wikipedia.org/wiki/Astronomy', 'profile_name': 'oci_ai_profile'}
Astronomy is a natural science that studies celestial objects and phenomena, using mathematics, physics, and chemistry to explain their origin and evolution. The field has a long history, with early civilizations making methodical observations of the night sky, and has since split into observational and theoretical branches. Observational astronomy focuses on acquiring data from observations, while theoretical astronomy develops computer or analytical models to describe astronomical objects and phenomena. Amateur astronomers also play an active role, contributing to discoveries and observations, particularly in the detection of transient events. The study of astronomy encompasses various subfields, including astrophysics, cosmology, and planetary science, and has led to a greater understanding of the universe, including the discovery of dark matter and dark energy. Astronomers use a range of techniques, including spectroscopy, astrophotography, and space telescopes, to study the universe, and have made significant advances in recent years, including the detection of gravitational waves and exoplanets.

ベクトルインデックスの属性を取得

vector_index_fetch.py
# -----------------------------------------------------------------------------
# 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.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# vector_index_fetch.py
#
# Gets attributes for a vector index
# -----------------------------------------------------------------------------

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)

vector_index = select_ai.VectorIndex.fetch(index_name="test_vector_index")
print(vector_index.attributes)
print(vector_index.profile)

実行例

$ python3 vector_index_fetch.py
OracleVectorIndexAttributes(chunk_size=1024, chunk_overlap=128, location='https://XXXXX.objectstorage.us-chicago-1.oci.customer-oci.com/n/XXXXX/b/ForRAG/o/rocket.txt', match_limit=5, object_storage_credential_name='my_oci_ai_profile_key', profile_name='oci_vector_ai_profile', refresh_rate=1440, similarity_threshold=0.0, vector_distance_metric='COSINE', vector_db_endpoint=None, vector_db_credential_name=None, vector_db_provider=<VectorDBProvider.ORACLE: 'oracle'>, vector_dimension=None, vector_table_name=None, pipeline_name='TEST_VECTOR_INDEX$VECPIPELINE')
Profile(profile_name=oci_vector_ai_profile, attributes=ProfileAttributes(annotations=None, case_sensitive_values=None, comments=None, constraints=None, conversation=None, credential_name='my_oci_ai_profile_key', enable_custom_source_uri=None, enable_sources=None, enable_source_offsets=None, enforce_object_list=None, max_tokens=1024, object_list=None, object_list_mode=None, provider=OCIGenAIProvider(embedding_model='cohere.embed-v4.0', 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='test_vector_index'), description=MY OCI AI Profile)

$

ベクトルインデックスの属性を更新

vector_index_update_attributes.py
# -----------------------------------------------------------------------------
# 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.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# vector_index_update_attributes.py
#
# Update attributes for a vector index
# -----------------------------------------------------------------------------

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)
vector_index = select_ai.VectorIndex(
    index_name="test_vector_index",
)

# Use vector_index.set_attributes to update a multiple attributes
updated_attributes = select_ai.OracleVectorIndexAttributes(refresh_rate=1450)
vector_index.set_attributes(attributes=updated_attributes)

# Use vector_index.set_attribute to update a single attribute
vector_index.set_attribute(
    attribute_name="similarity_threshold", attribute_value=0.5
)
print(vector_index.attributes)

実行例

$ python3 vector_index_update_attributes.py
OracleVectorIndexAttributes(chunk_size=1024, chunk_overlap=128, location='https://XXXXX.objectstorage.us-chicago-1.oci.customer-oci.com/n/XXXXX/b/ForRAG/o/rocket.txt', match_limit=5, object_storage_credential_name='my_oci_ai_profile_key', profile_name='oci_vector_ai_profile', refresh_rate=1450, similarity_threshold=0.5, vector_distance_metric='COSINE', vector_db_endpoint=None, vector_db_credential_name=None, vector_db_provider=<VectorDBProvider.ORACLE: 'oracle'>, vector_dimension=None, vector_table_name=None, pipeline_name='TEST_VECTOR_INDEX$VECPIPELINE')

$

さいごに

「Select AI for Python v1.2.0」でSELECT AIの新機能対応ができました。
また、「Select AI for Python」のドキュメントがHTMLで提供されるようになりました。

参考情報

補足

2025/12/17 にSelect AI for Python version 1.2.1がリリースされました。
Select AI for Python version 1.2をインストールしてある環境では

pip install select_ai==1.2.1 

でアップデートすることができます。

$ pip install select_ai==1.2.1
Defaulting to user installation because normal site-packages is not writeable
Collecting select_ai==1.2.1
  Downloading select_ai-1.2.1-py3-none-any.whl (51 kB)
     |███████████████████▏            | 30 kB 5.6 MB/s eta 0                                                                                                                                                                  |█████████████████████████▋      | 40 kB 2.6 MB/s                                                                                                                                                                  |████████████████████████████████| 51 kB 3.                                                                                                                                                                  |████████████████████████████████| 51 kB 130 kB/s
Collecting oracledb
  Downloading oracledb-3.4.1-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (2.6 MB)
Collecting pandas==2.2.3
  Downloading pandas-2.2.3-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (13.1 MB)
Collecting tzdata>=2022.7
  Downloading tzdata-2025.3-py2.py3-none-any.whl (348 kB)
Collecting python-dateutil>=2.8.2
  Downloading python_dateutil-2.9.0.post0-py2.py3-none-any.whl (229 kB)
Requirement already satisfied: pytz>=2020.1 in /usr/lib/python3.9/site-packages (from pandas==2.2.3->select_ai==1.2.1) (2021.1)
Collecting numpy>=1.22.4
  Downloading numpy-2.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (19.5 MB)
Requirement already satisfied: cryptography>=3.2.1 in /usr/lib64/python3.9/site-packages (from oracledb->select_ai==1.2.1) (36.0.1)
Collecting typing_extensions>=4.14.0
  Downloading typing_extensions-4.15.0-py3-none-any.whl (44 kB)
Requirement already satisfied: cffi>=1.12 in /usr/lib64/python3.9/site-packages (from cryptography>=3.2.1->oracledb->select_ai==1.2.1) (1.14.5)
Requirement already satisfied: six>=1.5 in /usr/lib/python3.9/site-packages (from python-dateutil>=2.8.2->pandas==2.2.3->select_ai==1.2.1) (1.15.0)
Requirement already satisfied: pycparser in /usr/lib/python3.9/site-packages (from cffi>=1.12->cryptography>=3.2.1->oracledb->select_ai==1.2.1) (2.20)
Requirement already satisfied: ply==3.11 in /usr/lib/python3.9/site-packages (from pycparser->cffi>=1.12->cryptography>=3.2.1->oracledb->select_ai==1.2.1) (3.11)
Installing collected packages: tzdata, typing-extensions, python-dateutil, numpy, pandas, oracledb, select-ai
Successfully installed numpy-2.0.2 oracledb-3.4.1 pandas-2.2.3 python-dateutil-2.9.0.post0 select-ai-1.2.1 typing-extensions-4.15.0 tzdata-2025.3
7
4
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
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?