16
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?

ADBとPythonでお手軽AIエージェントアプリ構築 (SELECT AI for Python+Streamlit)

16
Last updated at Posted at 2026-03-29

OCIのADBにはSELECT AI AgentというAIエージェントを手軽に作成できる機能があります。
一方Oracle DBの機能としてよくあるのが、実装にPL/SQLを使う必要があり、そこが利用にあたりネックとなり得るポイントでした。
というのもAIアプリはPythonのエコシステムが充実しており、大抵はPythonで実装されているかと思います。

そうした背景を意識してか、2025年9月に「SELECT AI fo Python」がリリースされました。
こちらはSELECT AI Agent含め、SELECT AI関連機能をPythonから利用できるパッケージになります。
SELECT AI for Pythonにより、ADBのAI機能とPythonのエコシステムを効率的に融合させられるようになっています。

今回はこのSELECT AI for PythonとAIアプリでよく使われるStreamlitを使い、AIエージェントアプリを作ってみました。
通常であればLangChain/LangGraphとStreamlitで実装するところ、LangChain/LangGraphが担う部分をADB SELECT AI Agentで実装するイメージです。
SELECT AI AgentにはNL2SQLやRAG、Web検索、メール/Salck通知といったPre-Builtツールが揃っており、お手軽にAIエージェントを実装できます。

なお実装シナリオは以下のSELECT AI Agentチュートリアルを利用させて頂きました。
もとの記事ではPL/SQLで実装していますが、そこをSELECT AI for Pythonで置き換えます。

また今回の実装にあたり、以下SELECT AI for Pythonのマニュアルを参照してコーディングしました。

目次

検証環境

Python実行環境

  • OCI Compute (VM.Standard.E5.Flex 1 OCPU, 12 GB RAM)
  • Oracle Linux 8

ADB

  • ATP
  • 2 ECPU

生成AI

  • OCI Generative AI Service
  • model: openai.gpt-oss-120b

事前準備

もとの記事に従い、ADBに検証用DBユーザやテーブル、必要なデータを作成しておきます。

SELECT AI Agent for Pythonセットアップ

OSパッケージインストール

sudo dnf install cmake gcc-c++ make -y

uvインストール

curl -LsSf https://astral.sh/uv/install.sh | sh
source $HOME/.local/bin/env

新しく仮想環境を作成

uv init saat -p 3.14
cd saat

仮想環境の初期化

uv venv

仮想環境のアクティベート

source .venv/bin/activate

oci-cliインストール

uv add oci-cli
oci setup config

途中で入力する項目等については下記をご参照ください。

  • 2-2. 構成情報の確認
    1. CLIの設定

oci-cliテスト

oci iam region list --output table

Pythonパッケージインストール

uv add select_ai python-dotenv

SELECT AI Agentセットアップ

SELECT AI Agent実行に必要な以下DBオブジェクトを作ります。

  • 生成AIやObject Storage利用に必要な資格証明
  • Agent
  • Task
  • Tool
  • Agent Team

上記DBオブジェクトをまとめて作成する以下Pythonコードを select_ai_agent_setup.py として保存します。

select_ai_agent_setup.pyのコード
from dotenv import load_dotenv
load_dotenv()
import os
import oci
import select_ai
import select_ai.agent
from select_ai.agent import Agent, AgentAttributes
from select_ai.agent import Task, TaskAttributes
from select_ai.agent import Team, TeamAttributes

user = os.getenv("SELECT_AI_USER")
password = os.getenv("SELECT_AI_P")
dsn = os.getenv("SELECT_AI_DB_CONNECT_STRING")
wallet_pw = os.getenv("WALLETPASS")
wallet_dir = os.environ.get("TNS_ADMIN")

# ADB接続
select_ai.connect(user=user, password=password, dsn=dsn, config_dir=wallet_dir, wallet_location=wallet_dir, wallet_password=wallet_pw)

# OCIプロファイル読み込み
default_config = oci.config.from_file()
oci.config.validate_config(default_config)

# クレデンシャル作成
with open(default_config["key_file"]) as fp:
    key_contents = fp.read()
    credential = {
        "credential_name": "OCI_GENAI_CRED",
        "user_ocid": default_config["user"],
        "tenancy_ocid": default_config["tenancy"],
        "private_key": key_contents,
        "fingerprint": default_config["fingerprint"],
    }
    
    select_ai.create_credential(credential=credential, replace=True)

# SELECT AI (SQLツール) 用AIプロファイル作成
provider = select_ai.OCIGenAIProvider(
    region="ap-osaka-1",
    oci_apiformat="GENERIC",
    model="openai.gpt-oss-120b",
)

profile_attributes = select_ai.ProfileAttributes(
    credential_name="OCI_GENAI_CRED",
    object_list=[{"owner": "adb_agent", "name": "orders"},
        {"owner": "adb_agent", "name": "order_items"},
        {"owner": "adb_agent", "name": "products"}],
    provider=provider,
)

profile = select_ai.Profile(
    profile_name="GENAI",
    attributes=profile_attributes,
    replace=True,
)

# SELECT AI with RAG (RAGツール) 用AIプロファイル作成
rag_provider = select_ai.OCIGenAIProvider(
    region="ap-osaka-1",
    oci_apiformat="GENERIC",
    model="openai.gpt-oss-120b",
    embedding_model="cohere.embed-v4.0",
)

rag_profile_attributes = select_ai.ProfileAttributes(
    credential_name="OCI_GENAI_CRED",
    provider=rag_provider,
    vector_index_name="MY_INDEX",
)

rag_profile = select_ai.Profile(
    profile_name="RAG_PROFILE",
    attributes=rag_profile_attributes,
    replace=True,
)

# ベクトル索引作成
vector_index_attributes = select_ai.OracleVectorIndexAttributes(
    location="https://orasejapan.objectstorage.ap-osaka-1.oci.customer-oci.com/n/orasejapan/b/docs/o/",
    object_storage_credential_name="OCI_GENAI_CRED",
    vector_dimension=1536,
    vector_distance_metric='COSINE',
    chunk_overlap=128,
    chunk_size=400,
    refresh_rate=1,
)

vector_index = select_ai.VectorIndex(
    index_name="MY_INDEX",
    attributes=vector_index_attributes,
    profile=rag_profile,
)

vector_index.create(replace=True)

# Agent#1作成
sql_agent_attributes = AgentAttributes(
    profile_name="GENAI",
    role="あなたの役割は、データベース上にある注文・売り上げ・商品データなどの情報を抽出して答える役割です。",
)

sql_agent = Agent(
    agent_name="ORDERS_ANALYST",
    attributes=sql_agent_attributes,
)

sql_agent.create(enabled=True, replace=True)

# SQL Tool作成
sql_tool = select_ai.agent.Tool.create_sql_tool(
    tool_name="ORDERS_QUERY",
    profile_name="GENAI",
    replace=True,
)

# Agent#1 Task作成
sql_task = Task(
    task_name="ORDERS_ANALYSIS_TASK",
    attributes=TaskAttributes(
        instruction="ORDERS表、ORDER_ITEMS表、PRODUCTS表に対するデータ検索を支援してください。ユーザからの質問: {query}。"
        "ORDERS表、ORDER_ITEMS表、PRODUCTS表を参照する際には ORDERS_QUERY ツールを利用してください。"
        "You can use SQL tool to search the data from database",
        tools=["ORDERS_QUERY"],
        enable_human_tool=False,
    ),
)

sql_task.create(replace=True)

# Agent#2作成
rag_agent_attributes = AgentAttributes(
    profile_name="RAG_PROFILE",
    role="あなたの役割は、登録されている商品カタログの情報を検索してその内容に基づいて回答する役割です。",
)

rag_agent = Agent(
    agent_name="PRODUCT_CATALOG_SEARCHER",
    attributes=rag_agent_attributes,
)

rag_agent.create(enabled=True, replace=True)

# RAG Tool作成
sql_tool = select_ai.agent.Tool.create_sql_tool(
    tool_name="RAG_TOOL",
    profile_name="RAG_PROFILE",
    replace=True,
)

# Agent#2 Task作成
rag_task = Task(
    task_name="ANALYZE_CATALOG_TASK",
    attributes=TaskAttributes(
        instruction="ORDERS表、ORDER_ITEMS表、PRODUCTS表からの結果を元に、さらに製品情報に関するデータ検索してユーザーからの質問に回答します。ユーザからの質問: {query}。"
        "回答する際に商品情報が登録されているナレッジベースの情報を検索する時は RAG_TOOL を利用してください。",
        tools=["RAG_TOOL"],
        input="ORDERS_ANALYSIS_TASK",
        enable_human_tool=False,
    ),
)

rag_task.create(replace=True)

# Agent Team作成
team = Team(
    team_name="SALES_AGENT_TEAM",
    attributes=TeamAttributes(
        agents=[{"name": "ORDERS_ANALYST", "task": "ORDERS_ANALYSIS_TASK"},
            {"name": "PRODUCT_CATALOG_SEARCHER", "task": "ANALYZE_CATALOG_TASK"}],
        process="sequential",
    ),
)

team.create(enabled=True, replace=True)

.envファイルに各パラメータを設定します。

vim .env
## SELECT_AI_USER=adb_agent
## SELECT_AI_P=<your password for adb_agent>
## SELECT_AI_DB_CONNECT_STRING=<your db service name for adb>
## WALLETPASS=<your wallet password for adb>

select_ai_agent_setup.pyを実行し、SELECT AI Agent関連DBオブジェクトを作成します。

python select_ai_agent_setup.py

Streamlit構築

続いてチャットアプリのUIを提供するStreamlitを構築します。
StreamlitはWell Known Portではない 8501/tcp で稼働するため、80番ポートからポート転送できるようSELinuxやnginxを設定します。

SELinux無効化

sudo vim /etc/selinux/config
## SELINUX=disabled

再起動後にSELinux無効化を確認

getenforce

FW設定

sudo firewall-cmd --permanent --add-source=10.0.0.0/24 # ご自身のサブネットを指定
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=8501/tcp
sudo firewall-cmd --reload
sudo firewall-cmd --list-all

nginxインストール

sudo dnf install nginx -y

nginxのconfig設定

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup
sudo vim /etc/nginx/nginx.conf
## 既存の server ブロックをコメントアウト
## 代わりに以下を追記
##     server {
##         listen 80;
##         location / {
##             proxy_pass http://127.0.0.1:8501;
##             proxy_redirect http:// https://;
##             proxy_http_version 1.1;
##             proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
##             proxy_set_header Host $host;
##             proxy_set_header Upgrade $http_upgrade;
##             proxy_set_header Connection "upgrade";
##             proxy_read_timeout 86400; 
##         }
##     }

nginxのシンタックスCheck

sudo nginx -t 

nginx起動設定

sudo systemctl enable nginx
sudo systemctl start nginx
sudo systemctl status nginx

Streamlitインストール

uv add streamlit

SELECT AI Agentと連携して稼働するStreamlitチャットアプリを実装します。
select_ai_agent_streamlit.pyというファイル名で以下Pythonコードを保存します。

select_ai_agent_setup.pyのコード
from dotenv import load_dotenv
load_dotenv()
import os
import uuid
import select_ai
from select_ai.agent import Team, TeamAttributes
import streamlit as st

user = os.getenv("SELECT_AI_USER")
password = os.getenv("SELECT_AI_P")
dsn = os.getenv("SELECT_AI_DB_CONNECT_STRING")
wallet_pw = os.getenv("WALLETPASS")
wallet_dir = os.environ.get("TNS_ADMIN")

# ADB接続
select_ai.connect(user=user, password=password, dsn=dsn, config_dir=wallet_dir, wallet_location=wallet_dir, wallet_password=wallet_pw)

team = Team.fetch("SALES_AGENT_TEAM")

# Streamlit上でAgent Team実行
conversation_id = str(uuid.uuid4())

st.title("Sales Analyze AI")

if "messages" not in st.session_state:
    st.session_state.messages = []

if prompt := st.chat_input("売上に関する質問を入力してください。"):
    # チャット履歴にユーザーメッセージを追加
    st.chat_message("user").markdown(prompt)
    st.session_state.messages.append({"role": "user", "content": prompt})

    # SELECT AI Agentによる回答生成
    with st.spinner('回答を生成中...'):
        response = team.run(
            prompt=prompt,
            params={"conversation_id": conversation_id},
        )

    # チャット履歴にSELECT AI Agentのレスポンスを追加
    with st.chat_message("SELECT AI Agent"):
        st.markdown(response)

    st.session_state.messages.append({"role": "AI", "content": response})

# 過去のチャット履歴含め表示
for msg in st.session_state.messages:
    if msg["role"] == "user":
        st.write("ユーザー: " + msg["content"])
    else:
        st.write("SELECT AI Agent: " + msg["content"])

以上で実装完了です。
最後にStreamlitを実行してアプリの動作を確認します。

streamlit run select_ai_agent_streamlit.py

質問1つめ

2025年で多く売れている上位2つの商品を特定してください。それらの商品の特徴を商品情報から分析して。日本語で回答して。

スクリーンショット 2026-03-28 171105.png
スクリーンショット 2026-03-28 171122.png

質問2つめ

2015年に最も多く売れている2つの商品を特定してください。それらの商品について商品カタログで情報を検索し、共通する特徴を分析してください。日本語で回答して。

スクリーンショット 2026-03-28 171204.png
スクリーンショット 2026-03-28 171211.png

チャットアプリとして上手く動作してくれました。

このようにDB事前準備を除き、AIエージェントに関わる部分は全てPythonで実装できることが分かりました。
PL/SQLを使うという点でSELECT AI Agentの活用を躊躇されていた方は、SELECT AI for Pythonを是非お試しください!

16
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
16
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?