1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OCI Generative AI (Llama)で WebSearchOptions を使って“最新ニュース+根拠URLつき”要約を作る

Last updated at Posted at 2025-10-30

はじめに

OCI Generative AI Inference では Llama 系モデルに対して、回答前にWeb 検索で外部情報を取り込みできるオプション WebSearchOptions が用意されています。
これを使うと「鮮度の高い情報を検索→根拠(URL)に基づいて回答」というワークフローを、SDK からシンプルに実装できます。

重要ポイント

  • WebSearchOptions は Llama + GenericChatRequest のときだけ使える(Cohere では不可)。
  • WebSearchOptions は“検索してよい”ヒントであり 強制ではないSystemMessage で「検索必須・出典URL必須」 を明示するのがコツ。
  • この記事は Python SDK(oci 2.160 以上推奨) を前提に、日本(JP)にバイアスした検索の例を示します

環境と前提

  • Python 3.10+(例)
  • oci Python SDK 2.160+(WebSearchOptions が含まれる)
  • 利用リージョン例:us-chicago-1(必要に応じて自環境に変更)
  • Llama 系の on-demand モデル OCID を保有していること(例:meta.llama-*-instruct
  • ~/.oci/config が正しく設定済み

設定手順

1) SDK セットアップ

python -m pip install -U oci
python -c "import oci; print(oci.__version__)"  # バージョン確認

2) 認証設定(~/.oci/config)

[DEFAULT]
tenancy=ocid1.tenancy.oc1...
user=ocid1.user.oc1...
fingerprint=aa:bb:...
key_file=C:\oci\oci_api_key.pem
region=us-chicago-1   # 設定しておくと優先。使うリージョンに合わせる

3) モデル OCID の準備

  • Llama 系モデルの OCID を用意(ocid1.generativeaimodel.oc1.....)
  • 後述のコードの model_id に差し替えます。

動作確認(LLAMA × WebSearchOptions)

以下は 日本向け(JP)にバイアスした Web 検索を行い、「日付・タイトル・公式URL」を必ず付けて日本語要約させる最小実装です。

import oci
from oci.generative_ai_inference import GenerativeAiInferenceClient
from oci.generative_ai_inference.models import (
    ChatDetails, OnDemandServingMode, GenericChatRequest,
    SystemMessage, UserMessage, TextContent,
    WebSearchOptions, ApproximateLocation
)

# --- 自環境に合わせて設定 ---
YOUR_COMPARTMENT_OCID = "ocid1.compartment.oc1..***" # ← 実行するコンパートメントのOCID
YOUR_LLAMA_MODEL_OCID = "ocid1.generativeaimodel.oc1.us-chicago-1.***" # ← Llama系モデルのOCID
# -------------------------

# 1) クライアント生成(~/.oci/config 使用)
# configファイルやプロファイルを指定する場合
# config = oci.config.from_file(profile_name="YOUR_PROFILE")
# client = GenerativeAiInferenceClient(config)

# デフォルトプロファイルを使用する場合
client = GenerativeAiInferenceClient(oci.config.from_file())

# 2) Llama + GenericChatRequest + WebSearchOptions
details = ChatDetails(
    compartment_id=YOUR_COMPARTMENT_OCID,
    serving_mode=OnDemandServingMode(
        serving_type="ON_DEMAND",
        model_id=YOUR_LLAMA_MODEL_OCID
    ),
    chat_request=GenericChatRequest(
        api_format="GENERIC",
        messages=[
            # 検索と出典必須を強く指示(重要)
            SystemMessage(
                role="SYSTEM",
                content=[TextContent(
                    type="TEXT",
                    text=(
                        "You MUST use web search to gather up-to-date information. "
                        # 検索期間を限定(デモ用の仮日付)
                        "Restrict items to 2025-08-01..2025-10-30. "
                        # 出力形式を厳密に指定
                        "For each item, output: YYYY-MM-DD, title, and the official source URL. "
                        "Answer in Japanese."
                    )
                )]
            ),
            UserMessage(
                role="USER",
                content=[TextContent(
                    type="TEXT",
                    text=(
                        "OCI(Oracle Cloud Infrastructure)の最新ニュースを要約し、"
                        "各項目に日付と公式URLを必ず付けてください(日本語)。"
                    )
                )]
            )
        ],
        web_search_options=WebSearchOptions(
            # 取り込みコンテキスト量(HIGH/MEDIUM/LOW)
            search_context_size="HIGH",
            # 日本の文脈に寄せる(city は任意)
            user_location=ApproximateLocation(country="JP", timezone="Asia/Tokyo")
        )
    )
)

try:
    resp = client.chat(chat_details=details)
    print("--- API Response (Full) ---")
    print(resp.data)

    # テキスト部分のみを抽出
    if resp.data.chat_response.choices:
        print("\n--- Answer Text ---")
        print(resp.data.chat_response.choices[0].message.content[0].text)

except Exception as e:
    print(f"Error occurred: {e}")

実行結果:

--- API Response (Full) ---
{
  "chat_response": {
    "api_format": "GENERIC",
    "choices": [
      {
        "finish_reason": "stop",
        "grounding_metadata": null,
        "index": 0,
        "logprobs": {
          "text_offset": null,
          "token_logprobs": null,
          "tokens": null,
          "top_logprobs": null
        },
        "message": {
          "annotations": null,
          "content": [
            {
              "text": "最新のOCI(Oracle Cloud Infrastructure)に関するニュースを調べた結果を以下に示します。\n\n2025-09-27、Oracleは、Oracle CloudWorld 2025の基調講演で、今後の新機能や最新技術の発表を行いました。詳しくは、Oracle CloudWorld 2025の公式サイト(https://www.oracle.com/cloudworld/)をご覧ください。\n\n2025-09-23、Oracle Cloud Infrastructure(OCI)は、Microsoft Azureと連携し、マルチクラウド環境での柔軟性と拡張性を強化しました。詳しくは、Oracle Cloudの公式ブログ(https://blogs.oracle.com/cloud-infrastructure-jp/post/2025/09/oci-azure-interconnect)をご覧ください。\n\n2025-09-17、OCIは、GPUクラスタの新機能を追加し、AIや機械学習のワークロードをさらに強化しました。詳しくは、Oracle Cloud Infrastructureの公式ドキュメント(https://docs.oracle.com/ja-jp/iaas/Content/Compute/References/gpu-cluster.htm)をご覧ください。\n\nこれらの情報は、Oracle Cloud Infrastructureの最新の動向を理解するのに役立ちます。公式ソースURLを参照して、詳細な情報をご確認ください。",
              "type": "TEXT"
            }
          ],
          "name": null,
          "refusal": null,
          "role": "ASSISTANT",
          "tool_calls": null
        },
        "usage": null
      }
    ],
    "time_created": "2025-10-30T14:13:38.313000+00:00",
    "usage": {
      "completion_tokens": 251,
      "completion_tokens_details": null,
      "prompt_tokens": 98,
      "prompt_tokens_details": null,
      "total_tokens": 349
    }
  },
  "model_id": "ocid1.generativeaimodel.oc1.us-chicago-1.amaaaaaask7dceyayjawvuonfkw2ua4bob4rlnnlhs522pafbglivtwlfzta",
  "model_version": "1.0.0"
}

--- Answer Text ---
最新のOCI(Oracle Cloud Infrastructure)に関するニュースを調べた結果を以下に示します。

2025-09-27、Oracleは、Oracle CloudWorld 2025の基調講演で、今後の新機能や最新技術の発表を行いました。詳しくは、Oracle CloudWorld 2025の公式サイト(https://www.oracle.com/cloudworld/)をご覧ください。

2025-09-23、Oracle Cloud Infrastructure(OCI)は、Microsoft Azureと連携し、マルチクラウド環境での柔軟性と拡張性を強化しました。詳しくは、Oracle Cloudの公式ブログ(https://blogs.oracle.com/cloud-infrastructure-jp/post/2025/09/oci-azure-interconnect)をご覧ください。

2025-09-17、OCIは、GPUクラスタの新機能を追加し、AIや機械学習のワークロードをさらに強化しました。詳しくは、Oracle Cloud Infrastructureの公式ドキュメント(https://docs.oracle.com/ja-jp/iaas/Content/Compute/References/gpu-cluster.htm)をご覧ください。

これらの情報は、Oracle Cloud Infrastructureの最新の動向を理解するのに役立ちます。公式ソースURLを参照して、詳細な情報をご確認ください。

レスポンス内の "text": フィールドに注目すると、SystemMessage で指示した通り、指定期間内のニュースが検索され、日付と出典URL(Markdown形式)付きで日本語要約されていることが確認できます。

改善のヒント

  • モデルが一般論を喋る/古いURLを出す → SystemMessage をさらに厳格化
    例:「少なくとも3件の公式URLを列挙」「裏取りできない項目は出力禁止」「日本語で簡潔に」など
  • 検索範囲を日付で縛る(上の Restrict items to ...)
  • 検索キーワードのヒントを UserMessage に並べる(例:Oracle AI World 2025, Dedicated Region 25, AI Database 26ai

Oracle DB(Select AI / DBMS_CLOUD_AI)での利用

DBMS_CLOUD_AI.CREATE_PROFILE の attributes JSON には web_search_options に相当する項目がありません。Oracle DB(Select AI / DBMS_CLOUD_AI)で 直接は使えません。 Workaround として下記の方法で実現できます。
Functions で REST API を提供 → API Gateway で公開 → DB から UTL_HTTP で呼び出し

Oracle DB (Autonomous or on-prem)
│ HTTPS (UTL_HTTP)
▼
API Gateway ─ (optional) WAF/Rate Limiting/Auth
│ Invoke
▼
OCI Functions (Fn) ←→ Generative AI Inference (Llama + WebSearchOptions)

まとめ

やりたいこと

Llama に WebSearchOptions を渡し、Web 検索してから回答する。

実装の要点:

  • Llama + GenericChatRequest(api_format="GENERIC")
  • WebSearchOptions に user_location(JP) と search_context_size を指定
  • SystemMessage で「検索必須・URL必須・期間制限」 を明確化
  • DB から直接は不可:OCI Functions で自作 API を提供し、DB から UTL_HTTP で呼び出すワークアラウンドを採用。
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?