ソースを見る

はじめに

このガイドでは、バックエンドデータベースとして Couchbase を使用して強力なセマンティック検索エンジンを構築する方法を説明します。 Deepseek V3が言語モデルプロバイダーとして機能します(OpenRouter経由または直接APIによる接続) and OpenAI for embeddings. Semantic search goes beyond simple keyword matching by understanding the context and meaning behind the words in a query, making it an essential tool for applications that require intelligent information retrieval. This tutorial is designed to be beginner-friendly, with clear, step-by-step instructions that will equip you with the knowledge to create a fully functional semantic search system using the Search Vector Index from scratch. Alternatively if you want to perform semantic search using the Hyperscale or Composite Vector Index, please take a look at このもの。.

このチュートリアルの実行方法

このチュートリアルはJupyter Notebookとして利用可能です(.ipynb ファイル) を実行できます。オリジナルのノートブックにアクセスできます。 これ.

ノートブックファイルをダウンロードして実行するか、 Google Colab または、Python環境をセットアップしてシステム上で実行してください。.

始める前に

OpenRouterとDeepseekの資格情報を入手する

  • アカウントの登録 OpenRouter APIキーを取得するには
  • OpenRouterはDeepseekモデルへのアクセスを提供するため、別途Deepseekの認証情報が必要ありません。
  • OpenRouter API キーを安全に保管してください。このキーはモデルへのアクセスに使用されます。
  • For ディープサーチ モデルでは、OpenRouterが提供するデフォルトのモデルを使用できます。

Capellaで無料Tier運用クラスターを作成およびデプロイ

Couchbase Capella の利用を開始するには、アカウントを作成し、これを使用して永久無料の運用クラスターをデプロイします。このアカウントでは、時間制限なく Capella を探索して学習できる環境を提供します。.

詳細については、以下をご覧ください。 説明書.

Couchbase Capellaの設定

「couchbase」を以下のように実行すると、 Capella, 以下のような前提条件を満たしている必要があります。.

準備段階:必要なライブラリのインストール

当社のセマンティック検索エンジンを構築するには、強力なツールセットが必要です。インストールしたライブラリは、データベースへの接続から複雑な機械学習タスクの実行まで、あらゆる作業に対応します。.

%pip install --no-user --quiet datasets==3.6.0
[お知らせ] pip の新しいリリースが利用可能になりました:25.0.1 -> 26.0.1
[通知] 更新するには、次のコマンドを実行してください:pip install --upgrade pip
注:更新されたパッケージを使用するには、カーネルを再起動する必要がある場合があります。.

必要なライブラリのインポート

スクリプトは、JSON の処理、ログ記録、時間追跡、Couchbase 接続、埋め込み生成、データセットの読み込みなど、さまざまなタスクに必要なライブラリのリストをインポートして開始します。.

import getpass
import json
import logging
import os
import time
from datetime import timedelta

from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import Cluster
from couchbase.exceptions import (CouchbaseException,
                                InternalServerFailureException,
                                QueryIndexAlreadyExistsException,ServiceUnavailableException)
from couchbase.management.buckets import CreateBucketSettings
from couchbase.management.search import SearchIndex
from couchbase.options import ClusterOptions
from datasets import load_dataset
from dotenv import load_dotenv
from langchain_core.globals import set_llm_cache
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts.chat import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_couchbase.cache import CouchbaseCache
from langchain_couchbase.vectorstores import CouchbaseSearchVectorStore
from langchain_openai import OpenAIEmbeddings
/Users/kaustavghosh/Desktop/vector-search-cookbook/.venv/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. jupyterとipywidgetsをアップデートして下さい。詳細はこちら https://ipywidgets.readthedocs.io/en/stable/user_install.html
  .autonotebook import トラッキング関数をノートブック_トグラムとして読み込む

セットアップのログ記録

ログは、スクリプトの進行状況を追跡し、エラーや警告をキャプチャするように設定されています。.

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', force=True)

# httpx のログを抑制する
logging.getLogger('httpx').setLevel(logging.CRITICAL)

環境変数と設定

このセクションでは、環境変数と設定の読み込みおよび検証を行います。

  1. API キー:
    • 直接のDeepseek APIまたはOpenRouter APIへのアクセスをサポート
    • 環境にない場合は API キーの入力を求めるプロンプトが表示されます。
    • エンベディングにはOpenAI APIキーが必要です。
  1. Couchbaseの設定:
    • 接続の詳細(ホスト名、ユーザー名、パスワード)
    • バケット、スコープ、コレクション名の例
    • ベクトル検索インデックスの構成
    • キャッシュ収集設定

このコードは、進む前に必要なすべての認証情報が揃っていることを検証します。 環境変数やインタラクティブなプロンプトを使用して柔軟な設定が可能で、ローカル開発用の適切なデフォルト設定も提供されます。.

# Load environment variables from .env file if it exists
load_dotenv()

# API Keys
# Allow either Deepseek API directly or via OpenRouter
DEEPSEEK_API_KEY = os.getenv('DEEPSEEK_API_KEY')
OPENROUTER_API_KEY = os.getenv('OPENROUTER_API_KEY')

if not DEEPSEEK_API_KEY and not OPENROUTER_API_KEY:
    api_choice = input('Choose API (1 for Deepseek direct, 2 for OpenRouter): ')
    if api_choice == '1':
        DEEPSEEK_API_KEY = getpass.getpass('Enter your Deepseek API Key: ')
    else:
        OPENROUTER_API_KEY = getpass.getpass('Enter your OpenRouter API Key: ')

OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') or getpass.getpass('Enter your OpenAI API Key: ')

# Couchbase Settings
CB_HOST = os.getenv('CB_HOST') or input('Enter your Couchbase host (default: couchbase://localhost): ') or 'couchbase://localhost'
CB_USERNAME = os.getenv('CB_USERNAME') or input('Enter your Couchbase username (default: Administrator): ') or 'Administrator'
CB_PASSWORD = os.getenv('CB_PASSWORD') or getpass.getpass('Enter your Couchbase password (default: password): ') or 'password'
CB_BUCKET_NAME = os.getenv('CB_BUCKET_NAME') or input('Enter your Couchbase bucket name (default: vector-search-testing): ') or 'vector-search-testing'
INDEX_NAME = os.getenv('INDEX_NAME') or input('Enter your index name (default: vector_search_deepseek): ') or 'vector_search_deepseek'
SCOPE_NAME = os.getenv('SCOPE_NAME') or input('Enter your scope name (default: shared): ') or 'shared'
COLLECTION_NAME = os.getenv('COLLECTION_NAME') or input('Enter your collection name (default: deepseek): ') or 'deepseek'
CACHE_COLLECTION = os.getenv('CACHE_COLLECTION') or input('Enter your cache collection name (default: cache): ') or 'cache'

# Check if required credentials are set
required_creds = {
    'OPENAI_API_KEY': OPENAI_API_KEY,
    'CB_HOST': CB_HOST,
    'CB_USERNAME': CB_USERNAME,
    'CB_PASSWORD': CB_PASSWORD,
    'CB_BUCKET_NAME': CB_BUCKET_NAME
}

# Add the API key that was chosen
if DEEPSEEK_API_KEY:
    required_creds['DEEPSEEK_API_KEY'] = DEEPSEEK_API_KEY
elif OPENROUTER_API_KEY:
    required_creds['OPENROUTER_API_KEY'] = OPENROUTER_API_KEY
else:
    raise ValueError("Either Deepseek API Key or OpenRouter API Key must be provided")

for cred_name, cred_value in required_creds.items():
    if not cred_value:
        raise ValueError(f"{cred_name} is not set")

Couchbase クラスターへの接続

Couchbase クラスターへの接続は、当社のプロジェクトの基盤です。Couchbase は当社のセマンティック検索エンジンのためのすべてのストレージおよび検索操作を処理するメインのデータストアとして機能します。この接続を確立することで、アプリケーションがデータベースとやり取りできるようになり、エンベディングの保存、データのクエリ、コレクションの管理といった操作を実行できるようになります。この接続はすべてのデータのフローのゲートウェイであるため、正しく設定されていることが不可欠です。.

試す:
    auth = PasswordAuthenticator(CB_USERNAME, CB_PASSWORD)
    options = ClusterOptions(auth)
    cluster = クラスタ(CB_HOST, オプション)
    cluster.wait_until_ready(timedelta(seconds=5))
    logging.info("Couchbaseに接続されました")
例外として e を除きます:
    ConnectionErrorを発生させる (f"Couchbaseへの接続に失敗しました: {str(e}")")
2026-02-12 10:38:30,988 - INFO - Successfully connected to Couchbase

Couchbaseでのコレクションのセットアップ

setup_collection() 関数は、Couchbase で階層的なデータ構造の作成と設定を処理します:

  1. バケットの作成:

    • 指定されたバケットが存在するかどうかをチェックし、存在しない場合は作成します。
    • RAM割り当て(1024MB)、レプリケーション(無効)などのバケットプロパティを設定します
    • 注:Capella を使用している場合は、同じプロパティでベクター検索テスト(またはお好みの名前)という名前でバケットを手動で作成してください。.
  2. スコープ管理:

    • リクエストされたスコープがバケット内に存在するかどうかを確認します。
    • 必要に応じて新しいスコープを作成します(デフォルトの「_default」スコープの場合は除きます)。
  3. コレクションのセットアップ:

    • 範囲内でコレクションが存在するかどうかをチェックする
    • 存在しない場合コレクションを作成する
    • コレクションの準備が完了するまで2秒待つ

追加のタスク:

  • Creates primary index on collection for query performance
  • 既存のドキュメントをすべてクリアして、状態をクリアにします
  • 包括的なエラー処理とログの記録を実装

この関数は設定するために 2 回呼び出されます:

  1. ベクトル埋め込み用のメインコレクション
  2. 結果の保存用のキャッシュコレクション
def setup_collection(cluster, bucket_name, scope_name, collection_name):
    try:
        # Check if bucket exists, create if it doesn't
        try:
            bucket = cluster.bucket(bucket_name)
            logging.info(f"Bucket '{bucket_name}' exists.")
        except Exception as e:
            logging.info(f"Bucket '{bucket_name}' does not exist. Creating it...")
            bucket_settings = CreateBucketSettings(
                name=bucket_name,
                bucket_type='couchbase',
                ram_quota_mb=1024,
                flush_enabled=True,
                num_replicas=0
            )
            cluster.buckets().create_bucket(bucket_settings)
            time.sleep(2)  # Wait for bucket creation to complete and become available
            bucket = cluster.bucket(bucket_name)
            logging.info(f"Bucket '{bucket_name}' created successfully.")

        bucket_manager = bucket.collections()

        # Check if scope exists, create if it doesn't
        scopes = bucket_manager.get_all_scopes()
        scope_exists = any(scope.name == scope_name for scope in scopes)
        
        if not scope_exists and scope_name != "_default":
            logging.info(f"Scope '{scope_name}' does not exist. Creating it...")
            bucket_manager.create_scope(scope_name)
            logging.info(f"Scope '{scope_name}' created successfully.")

        # Check if collection exists, create if it doesn't
        collection_exists = any(
            scope.name == scope_name and collection_name in [col.name for col in scope.collections]
            for scope in scopes
        )

        if not collection_exists:
            logging.info(f"Collection '{collection_name}' does not exist. Creating it...")
            bucket_manager.create_collection(scope_name, collection_name)
            logging.info(f"Collection '{collection_name}' created successfully.")
        else:
            logging.info(f"Collection '{collection_name}' already exists. Skipping creation.")

        # Wait for collection to be ready
        collection = bucket.scope(scope_name).collection(collection_name)
        time.sleep(2)  # Give the collection time to be ready for queries

        # Ensure primary index exists
        try:
            cluster.query(f"CREATE PRIMARY INDEX IF NOT EXISTS ON `{bucket_name}`.`{scope_name}`.`{collection_name}`").execute()
            logging.info("Primary index present or created successfully.")
        except Exception as e:
            logging.warning(f"Error creating primary index: {str(e)}")

        # Clear all documents in the collection
        try:
            query = f"DELETE FROM `{bucket_name}`.`{scope_name}`.`{collection_name}`"
            cluster.query(query).execute()
            logging.info("All documents cleared from the collection.")
        except Exception as e:
            logging.warning(f"Error while clearing documents: {str(e)}. The collection might be empty.")

        return collection
    except Exception as e:
        raise RuntimeError(f"Error setting up collection: {str(e)}")
    
setup_collection(cluster, CB_BUCKET_NAME, SCOPE_NAME, COLLECTION_NAME)
setup_collection(cluster, CB_BUCKET_NAME, SCOPE_NAME, CACHE_COLLECTION)

2026-02-12 10:38:30,999 - INFO - Bucket 'vector-search-testing' exists.
2026-02-12 10:38:31,002 - INFO - Collection 'deepseek' already exists. Skipping creation.
2026-02-12 10:38:33,012 - INFO - Primary index present or created successfully.
2026-02-12 10:38:33,064 - INFO - All documents cleared from the collection.
2026-02-12 10:38:33,065 - INFO - Bucket 'vector-search-testing' exists.
2026-02-12 10:38:33,066 - INFO - Collection 'cache' already exists. Skipping creation.
2026-02-12 10:38:35,075 - INFO - Primary index present or created successfully.
2026-02-12 10:38:35,078 - INFO - All documents cleared from the collection.





<couchbase.collection.Collection at 0x14173c620>

Loading Couchbase Vector Search Index

Semantic search requires an efficient way to retrieve relevant documents based on a user’s query. This is where the Couchbase Vector Search Index comes into play. In this step, we load the Vector Search Index definition from a JSON file, which specifies how the index should be structured. This includes the fields to be indexed, the dimensions of the vectors, and other parameters that determine how the search engine processes queries based on vector similarity.

This OpenRouter Deepseek vector search index configuration requires specific default settings to function properly. This tutorial uses the bucket named vector-search-testing with the scope shared and collection deepseek. The configuration is set up for vectors with exactly 1536 dimensions, using dot product similarity and optimized for recall. If you want to use a different bucket, scope, or collection, you will need to modify the index configuration accordingly.

For more information on creating a vector search index, please follow the 説明書.

try:
    with open('deepseek_index.json', 'r') as file:
        index_definition = json.load(file)
except Exception as e:
    raise ValueError(f"Error loading index definition: {str(e)}")

Creating or Updating Search Indexes

With the index definition loaded, the next step is to create or update the Vector Search Index in Couchbase. This step is crucial because it optimizes our database for vector similarity search operations, allowing us to perform searches based on the semantic content of documents rather than just keywords. By creating or updating a Vector Search Index, we enable our search engine to handle complex queries that involve finding semantically similar documents using vector embeddings, which is essential for a robust semantic search engine.Creating search indexes placeholder text.

try:
    scope_index_manager = cluster.bucket(CB_BUCKET_NAME).scope(SCOPE_NAME).search_indexes()

    # Check if index already exists
    existing_indexes = scope_index_manager.get_all_indexes()
    index_name = index_definition["name"]

    if index_name in [index.name for index in existing_indexes]:
        logging.info(f"Index '{index_name}' found")
    else:
        logging.info(f"Creating new index '{index_name}'...")

    # Create SearchIndex object from JSON definition
    search_index = SearchIndex.from_json(index_definition)

    # Upsert the index (create if not exists, update if exists)
    scope_index_manager.upsert_index(search_index)
    logging.info(f"Index '{index_name}' successfully created/updated.")

except QueryIndexAlreadyExistsException:
    logging.info(f"Index '{index_name}' already exists. Skipping creation/update.")
except ServiceUnavailableException:
    raise RuntimeError("Search service is not available. Please ensure the Search service is enabled in your Couchbase cluster.")
except InternalServerFailureException as e:
    logging.error(f"Internal server error: {str(e)}")
    raise
2026-02-12 10:38:35,099 - INFO - Creating new index 'vector_search_deepseek'...
2026-02-12 10:38:35,113 - INFO - Index 'vector_search_deepseek' successfully created/updated.

エンベッドメントの作成

このセクションでは、OpenAI API キーを使用して OpenAI エンベディングス クライアントを作成します。 エンベディングクライアントは、「text-embedding-3-small」モデルを使用するように設定されています。 これはテキストを数値ベクトル表現に変換します。 これらのベクトルエンベディングは、セマンティック検索および類似性マッチングにおいて不可欠です。 このクライアントは、ベクトルストアによってドキュメントのエンベディングを生成するために使用されます。.

試す:
    エンベディング = OpenAIEmbeddings(
        api_key=OPENAI_API_KEY,
        model="text-embedding-3-small"
    )
    logging.info("OpenAI エンベディング クライアントが正常に作成されました")
例外として e を除きます:
    ValueErrorを発生させる(f"OpenAI エンベディングクライアントの作成にエラーが発生しました: {str(e}")")
2026-02-12 10:38:35,252 - INFO - Successfully created OpenAI embeddings client

Setting Up the Couchbase Search Vector Store

ベクターストアは、エンベデッドモデルを保管する場所です。ベクターストアは、エンベデッドモデルを処理し、類似性の検索を実行するために特別に設計されています。ユーザーがクエリを入力すると、検索エンジンはクエリをエンベデッドモデルに変換し、ベクターストアに保存されているエンベデッドモデルと比較します。これにより、単に同じ単語が含まれていないとしても、検索結果に意味合いや文脈に基づいた類似するドキュメントを検索することが可能になります。Couchbaseでベクターストアを設定することで、検索エンジンが単に特定の単語ではなく、クエリの意味や文脈に基づいて情報を理解して検索できる強力なツールが作成されます。.

try:
    vector_store = CouchbaseSearchVectorStore(
        cluster=cluster,
        bucket_name=CB_BUCKET_NAME,
        scope_name=SCOPE_NAME,
        collection_name=COLLECTION_NAME,
        embedding=embeddings,
        index_name=INDEX_NAME,
    )
    logging.info("Successfully created vector store")
except Exception as e:
    raise ValueError(f"Failed to create vector store: {str(e)}")
2026-02-12 10:38:35,264 - INFO - Successfully created vector store

BBCニュースデータセットを読み込む

検索エンジンを構築するには、検索するためのデータが必要です。我々は RealTimeData の BBC News データセットを使用しています。このデータセットには現実世界のニュース記事が含まれています。このデータセットには BBC が取り扱う様々なトピックや時代を網羅したニュース記事が含まれています。データセットのロードは重要なステップです。なぜなら、このデータセットは検索エンジンの作業に不可欠な素材を提供してくれるからです。ニュース記事の質の高さと多様性は、検索エンジンのテストと改良に最適で、実世界のニュースコンテンツを効果的に処理できることを保証します。.

BBC Newsのデータセットを使用することで、本物のニュース記事を扱うことができ、効果的に関連するニュースコンテンツを処理して取得できる検索エンジンを構築およびテストすることができます。このデータセットは、Hugging Faceのデータセットライブラリを使用して読み込みられ、具体的には「RealTimeData/bbc_news_alltime」データセットを「2024-12」バージョンで読み込みます。.

試す:
    news_dataset = load_dataset(
        「RealTimeData/bbc_news_alltime」、分割「train」で2024年12月20日時点のデータ
    )
    print(f"BBCニュースデータセットを読み込みました。長さ {len(news_dataset)} の行があります")
    logging.info(f"BBCニュースデータセットを {len(news_dataset)} 行で正常に読み込んだ")
例外として e を除きます:
    ValueErrorを発生させる(「BBCニュースデータセットの読み込みエラー: {str(e)}」)
2026-02-12 10:38:39,263 - INFO - Successfully loaded the BBC News dataset with 2687 rows.


Loaded the BBC News dataset with 2687 rows

データの整理

我々は、ニュース記事の内容をRAGシステムに使用します。.

このデータセットには重複するレコードがいくつか含まれています。この重複したレコードを削除することで、RAGシステムの検索段階で重複した結果を回避します。.

news_articles = news_dataset["content"]
unique_articles = set()
ニュース記事の記事の項について:
    記事の場合:
        unique_articles.add(article)
unique_news_articles = list(unique_articles)
print(f"データベースには {len(unique_news_articles)} の記事があります")
弊社データベースには1749件のユニークな記事があります。.

ベクトルストアへのデータの保存

大量の記事を効率的に処理するため、一度に複数の記事を処理します。このバッチ処理アプローチにより、メモリ使用量を管理し、インジェストプロセスをより適切に制御できます。.

まず、トークン制限の問題を避けるために、文字数が50,000文字を超える記事はすべて除外します。その後、ベクターストアのadd_textsメソッドを使用して、フィルタリングされた記事をベクターデータベースに追加します。batch_sizeパラメータは、各イテレーションで処理される記事数を制御します。.

このアプローチにはいくつかの利点があります:

  1. メモリ効率:より小さなバッチでの処理によりメモリの過負荷を防ぐ
  2. 進捗の追跡:取り込みの進捗をより簡単に監視および追跡できます
  3. リソース管理:CPUおよびネットワークリソースの利用率のより良い制御

信頼性の高い運用を確保するために、保守的なバッチサイズを50個とします。 最適なバッチサイズは、以下のような多くの要因に依存します:

  • 挿入されているドキュメントのサイズ
  • 利用可能なシステムリソース
  • ネットワークの状況
  • 同時作業の負荷

調整前に、具体的な作業負荷に基づいてパフォーマンスを測定することを検討してください。.

batch_size = 50

# 自動バッチ処理
記事 = [unique_news_articlesの記事ごとに記事が含まれる場合、記事とlen(article) <= 50000]

試す:
    vector_store.add_texts(
        texts=記事、
        batch_size=batch_size
    )
    logging.info("ドキュメントの取り込みが正常に完了しました")
例外として e を除きます:
    ValueErrorを発生させる(f"ベクトルストアにドキュメントを保存できません: {str(e}")")
2026-02-12 10:39:17,525 - INFO - Document ingestion completed successfully.

LLM応答キャッシュの設定

システムのさらなる最適化のため、Couchbaseベースのキャッシュを設定しました。キャッシュは頻繁にアクセスされるデータを一時的に保存する層であり、データベースから同じ情報を繰り返し取得する必要性を減らすことで操作の高速化を実現します。弊社ではこのキャッシュを利用することで、類似ドキュメントの検索など、繰り返し行うタスクの処理を高速化できます。キャッシュの導入により、弊社検索エンジンの全体的なパフォーマンスが向上し、高いクエリ量に対応して迅速な結果の提供が可能になります。.

キャッシュ機能は、ユーザーが類似のクエリを複数回送信する場合や、特定の情報が頻繁に要求される状況において特に価値があります。これらの情報をキャッシュに保存することで、これらのクエリに対する応答にかかる時間を大幅に短縮し、ユーザーエクスペリエンスを向上させることができます。.

試す:
    cache = CouchbaseCache(
        cluster=cluster,
        bucket_name=CB_BUCKET_NAME、
        scope_name=SCOPE_NAME,
        collection_name=CACHE_COLLECTION、
    )
    logging.info("キャッシュが正常に作成されました")
    set_llm_cache(cache)
例外として e を除きます:
    ValueErrorを発生させる(f"キャッシュの作成に失敗しました: {str(e)}")
2026-02-12 10:39:17,537 - INFO - Successfully created cache

LLMモデルの設定

このセクションでは、RAGシステム用の大型言語モデル(LLM)を設定します。ここではDeepseekモデルを使用しています。このモデルは2つの方法でアクセスできます:

  1. Deepseek APIキーこれはDeepseekのプラットフォームから直接取得されます(https://deepseek.ai) アカウントを作成し、APIサービスをサブスクライブすることで実現できます。このキーを使って、Deepseekのモデルに直接アクセスできます。 ChatDeepSeek クラスから langchain_deepseek パッケージ。.

  2. OpenRouter APIキーオープンルーターhttps://openrouter.ai) は、Deepseek を含む複数の LLM プロバイダーへの統合アクセスを提供するサービスです。OpenRouter のウェブサイトでアカウントを作成することで API キーを取得できます。このアプローチでは、 ChatOpenAI クラスから langchain_openai しかし、カスタムベースURLはOpenRouterのAPIエンドポイントを指しています。.

主な違いは、OpenRouterは様々なLLMプロバイダーへのリクエストのルーティングを行う中間サービスとして機能するのに対し、Deepseek APIはDeepseekのモデルに直接アクセスできる点です。OpenRouterは、コードを変更することなくさまざまなLLMプロバイダーを切り替える必要がある場合に役立ちます。.

弊社の実装では、キーの両方をチェックし、利用可能な場合は直接 Deepseek API を優先的に使用します。利用できない場合は OpenRouter に切り替わります。モデルは温度=0 を設定して、RAG アプリケーションに適した決定的な、集中型の応答を保証します。.

langchain_deepseek import ChatDeepSeek
llngan_openai から ChatOpenAI をインポートする

if DEEPSEEK_API_KEY:
    試す:
        llm = ChatDeepSeek(
            api_key=DEEPSEEK_API_KEY,
            model_name="deepseek-chat",
            温度=0
        )
        logging.info("Deepseek LLM クライアントが正常に作成されました")
    例外として e を除きます:
        ValueErrorを発生させる(f"Deepseek LLM クライアントの作成時にエラー: {str(e}")")
elif OPENROUTER_API_KEY:
    試す:
        llm = ChatOpenAI(
            api_key=OPENROUTER_API_KEY,
            base_url=https://openrouter.ai/api/v1""
            model="deepseek/deepseek-chat-v3.1", 
            温度=0,
        )
        logging.info("OpenRouter を使用して Deepseek LLM クライアントが正常に作成されました")
    例外として e を除きます:
        ValueErrorを発生させる(f"Deepseek LLM クライアントの作成時にエラー: {str(e}")")
else:
    ValueError ("Deepseek API キーまたは OpenRouter API キーのどちらかを指定する必要があります") を発生します。
2026-02-12 10:39:17,561 - INFO - Successfully created Deepseek LLM client through OpenRouter

Semantic search in Couchbase involves converting queries and documents into vector representations using an embeddings model. These vectors capture the semantic meaning of the text and are stored directly in Couchbase. When a query is made, Couchbase performs a similarity search by comparing the query vector against the stored document vectors. The similarity metric used for this comparison is configurable, allowing flexibility in how the relevance of documents is determined.

In the provided code, the search process begins by recording the start time, followed by executing the similarity_search_with_score method of the CouchbaseSearchVectorStore. This method searches Couchbase for the most relevant documents based on the vector similarity to the query. The search results include the document content and a similarity score that reflects how closely each document aligns with the query in the defined semantic space. The time taken to perform this search is then calculated and logged, and the results are displayed, showing the most relevant documents along with their similarity scores. This approach leverages Couchbase as both a storage and retrieval engine for vector data, enabling efficient and scalable semantic searches. The integration of vector storage and search capabilities within Couchbase allows for sophisticated semantic search operations without relying on external services for vector storage or comparison.

query = "What were Luke Littler's key achievements and records in his recent PDC World Championship match?"

try:
    # Perform the semantic search
    start_time = time.time()
    search_results = vector_store.similarity_search_with_score(query, k=10)
    search_elapsed_time = time.time() - start_time

    logging.info(f"Semantic search completed in {search_elapsed_time:.2f} seconds")

    # Display search results
    print(f"nSemantic Search Results (completed in {search_elapsed_time:.2f} seconds):")
    print("-" * 80)

    for doc, score in search_results:
        print(f"Score: {score:.4f}, Text: {doc.page_content}")
        print("-" * 80)

except CouchbaseException as e:
    raise RuntimeError(f"Error performing semantic search: {str(e)}")
except Exception as e:
    raise RuntimeError(f"Unexpected error: {str(e)}")
2026-02-12 10:39:17,842 - INFO - Semantic search completed in 0.28 seconds



Semantic Search Results (completed in 0.28 seconds):
--------------------------------------------------------------------------------
Score: 0.6306, Text: The Littler effect - how darts hit the bullseye

Teenager Luke Littler began his bid to win the 2025 PDC World Darts Championship with a second-round win against Ryan Meikle. Here we assess Littler's impact after a remarkable rise which saw him named BBC Young Sports Personality of the Year and runner-up in the main award to athlete Keely Hodgkinson.

One year ago, he was barely a household name in his own home. Now he is a sporting phenomenon. After emerging from obscurity aged 16 to reach the World Championship final, the life of Luke Littler and the sport he loves has been transformed. Viewing figures, ticket sales and social media interest have rocketed. Darts has hit the bullseye. This Christmas more than 100,000 children are expected to be opening Littler-branded magnetic dartboards as presents. His impact has helped double the number of junior academies, prompted plans to expand the World Championship and generated interest in darts from Saudi Arabian backers.

Just months after taking his GCSE exams and ranked 164th in the world, Littler beat former champions Raymond van Barneveld and Rob Cross en route to the PDC World Championship final in January, before his run ended with a 7-4 loss to Luke Humphries. With his nickname 'The Nuke' on his purple and yellow shirt and the Alexandra Palace crowd belting out his walk-on song, Pitbull's tune Greenlight, he became an instant hit. Electric on the stage, calm off it. The down-to-earth teenager celebrated with a kebab and computer games. "We've been watching his progress since he was about seven. He was on our radar, but we never anticipated what would happen. The next thing we know 'Littlermania' is spreading everywhere," PDC president Barry Hearn told BBC Sport. A peak TV audience of 3.7 million people watched the final - easily Sky's biggest figure for a non-football sporting event. The teenager from Warrington in Cheshire was too young to legally drive or drink alcohol, but earned £200,000 for finishing second - part of £1m prize money in his first year as a professional - and an invitation to the elite Premier League competition. He turned 17 later in January but was he too young for the demanding event over 17 Thursday nights in 17 locations? He ended up winning the whole thing, and hit a nine-dart finish against Humphries in the final. From Bahrain to Wolverhampton, Littler claimed 10 titles in 2024 and is now eyeing the World Championship.

As he progressed at the Ally Pally, the Manchester United fan was sent a good luck message by the club's former midfielder and ex-England captain David Beckham. In 12 months, Littler's Instagram followers have risen from 4,000 to 1.3m. Commercial backers include a clothing range, cereal firm and train company and he will appear in a reboot of the TV darts show Bullseye. Google say he was the most searched-for athlete online in the UK during 2024. On the back of his success, Littler darts, boards, cabinets, shirts are being snapped up in big numbers. "This Christmas the junior magnetic dartboard is selling out, we're talking over 100,000. They're 20 quid and a great introduction for young children," said Garry Plummer, the boss of sponsors Target Darts, who first signed a deal with Littler's family when he was aged 12. "All the toy shops want it, they all want him - 17, clean, doesn't drink, wonderful."

Littler beat Luke Humphries to win the Premier League title in May

The number of academies for children under the age of 16 has doubled in the last year, says Junior Darts Corporation chairman Steve Brown. There are 115 dedicated groups offering youngsters equipment, tournaments and a place to develop, with bases including Australia, Bulgaria, Greece, Norway, USA and Mongolia. "We've seen so many inquiries from around the world, it's been such a boom. It took us 14 years to get 1,600 members and within 12 months we have over 3,000, and waiting lists," said Brown. "When I played darts as a child, I was quite embarrassed to tell my friends what my hobby was. All these kids playing darts now are pretty popular at school. It's a bit rock 'n roll and recognised as a cool thing to do." Plans are being hatched to extend the World Championship by four days and increase the number of players from 96 to 128. That will boost the number of tickets available by 25,000 to 115,000 but Hearn reckons he could sell three times as many. He says Saudi Arabia wants to host a tournament, which is likely to happen if no-alcohol regulations are relaxed. "They will change their rules in the next 12 months probably for certain areas having alcohol, and we'll take darts there and have a party in Saudi," he said. "When I got involved in darts, the total prize money was something like £300,000 for the year. This year it will go to £20m. I expect in five years' time, we'll be playing for £40m."

Former electrician Cross charged to the 2018 world title in his first full season, while Adrian Lewis and Michael van Gerwen were multiple victors in their 20s and 16-time champion Phil ‘The Power’ Taylor is widely considered the greatest of all time. Littler is currently fourth in the world rankings, although that is based on a two-year Order of Merit. There have been suggestions from others the spotlight on the teenager means world number one Humphries, 29, has been denied the coverage he deserves, but no darts player has made a mark at such a young age as Littler. "Luke Humphries is another fabulous player who is going to be around for years. Sport is a very brutal world. It is about winning and claiming the high ground. There will be envy around," Hearn said. "Luke Littler is the next Tiger Woods for darts so they better get used to it, and the only way to compete is to get better." World number 38 Martin Lukeman was awestruck as he described facing a peak Littler after being crushed 16-3 in the Grand Slam final, with the teenager winning 15 consecutive legs. "I can't compete with that, it was like Godly. He was relentless, he is so good it's ridiculous," he said. Lukeman can still see the benefits he brings, adding: "What he's done for the sport is brilliant. If it wasn't for him, our wages wouldn't be going up. There's more sponsors, more money coming in, all good." Hearn feels future competition may come from players even younger than Littler. "I watched a 10-year-old a few months ago who averaged 104.89 and checked out a 4-3 win with a 136 finish. They smell the money, the fame and put the hard work in," he said. How much better Littler can get is guesswork, although Plummer believes he wants to reach new heights. "He never says 'how good was I?' But I think he wants to break records and beat Phil Taylor's 16 World Championships and 16 World Matchplay titles," he said. "He's young enough to do it." A version of this article was originally published on 29 November.
• None Know a lot about Littler? Take our quiz
--------------------------------------------------------------------------------
Score: 0.6099, Text: Luke Littler has risen from 164th to fourth in the rankings in a year

A tearful Luke Littler hit a tournament record 140.91 set average as he started his bid for the PDC World Championship title with a dramatic 3-1 win over Ryan Meikle. The 17-year-old made headlines around the world when he reached the tournament final in January, where he lost to Luke Humphries. Starting this campaign on Saturday, Littler was millimetres away from a nine-darter when he missed double 12 as he blew Meikle away in the fourth and final set of the second-round match. Littler was overcome with emotion at the end, cutting short his on-stage interview. "It was probably the toughest game I've ever played. I had to fight until the end," he said later in a news conference. "As soon as the question came on stage and then boom, the tears came. It was just a bit too much to speak on stage. "It is the worst game I have played. I have never felt anything like that tonight." Admitting to nerves during the match, he told Sky Sports: "Yes, probably the biggest time it's hit me. Coming into it I was fine, but as soon as [referee] George Noble said 'game on', I couldn't throw them." Littler started slowly against Meikle, who had two darts for the opening set, but he took the lead by twice hitting double 20. Meikle did not look overawed against his fellow Englishman and levelled, but Littler won the third set and exploded into life in the fourth. The tournament favourite hit four maximum 180s as he clinched three straight legs in 11, 10 and 11 darts for a record set average, and 100.85 overall. Meanwhile, two seeds crashed out on Saturday night – five-time world champion Raymond van Barneveld lost to Welshman Nick Kenny, while England's Ryan Joyce beat Danny Noppert. Australian Damon Heta was another to narrowly miss out on a nine-darter, just failing on double 12 when throwing for the match in a 3-1 win over Connor Scutt. Ninth seed Heta hit four 100-plus checkouts to come from a set down against Scutt in a match in which both men averaged more than 97.

Littler was hugged by his parents after victory over Meikle

Littler returned to Alexandra Palace to a boisterous reception from more than 3,000 spectators and delivered an astonishing display in the fourth set. He was on for a nine-darter after his opening two throws in both of the first two legs and completed the set in 32 darts - the minimum possible is 27. The teenager will next play after Christmas against European Championship winner Ritchie Edhouse, the 29th seed, or Ian White, and is seeded to meet Humphries in the semi-finals. Having entered last year's event ranked 164th, Littler is up to fourth in the world and will go to number two if he reaches the final again this time. He has won 10 titles in his debut professional year, including the Premier League and Grand Slam of Darts. After reaching the World Championship final as a debutant aged just 16, Littler's life has been transformed and interest in darts has rocketed. Google say he was the most searched-for athlete online in the UK during 2024. This Christmas, more than 100,000 children are expected to be opening Littler-branded magnetic dartboards as presents. His impact has helped double the number of junior academies and has prompted plans to expand the World Championship. Littler was named BBC Young Sports Personality of the Year on Tuesday and was runner-up to athlete Keely Hodgkinson for the main award.

Nick Kenny will play world champion Luke Humphries in round three after Christmas

Barneveld was shocked 3-1 by world number 76 Kenny, who was in tears after a famous victory. Kenny, 32, will face Humphries in round three after defeating the Dutchman, who won the BDO world title four times and the PDC crown in 2007. Van Barneveld, ranked 32nd, became the sixth seed to exit in the second round. His compatriot Noppert, the 13th seed, was stunned 3-1 by Joyce, who will face Ryan Searle or Matt Campbell next, with the winner of that tie potentially meeting Littler in the last 16. Elsewhere, 15th seed Chris Dobey booked his place in the third round with a 3-1 win over Alexander Merkx. Englishman Dobey concluded an afternoon session which started with a trio of 3-0 scorelines. Northern Ireland's Brendan Dolan beat Lok Yin Lee to set up a meeting with three-time champion Michael van Gerwen after Christmas. In the final two first-round matches of the 2025 competition, Wales' Rhys Griffin beat Karel Sedlacek of the Czech Republic before Asia number one Alexis Toylo cruised past Richard Veenstra.
--------------------------------------------------------------------------------
Score: 0.5981, Text: Luke Littler is one of six contenders for the 2024 BBC Sports Personality of the Year award.

Here BBC Sport takes a look at the darts player's year in five photos.
--------------------------------------------------------------------------------
Score: 0.5590, Text: Littler is Young Sports Personality of the Year

This video can not be played To play this video you need to enable JavaScript in your browser.

Darts player Luke Littler has been named BBC Young Sports Personality of the Year 2024. The 17-year-old has enjoyed a breakthrough year after finishing runner-up at the 2024 PDC World Darts Championship in January. The Englishman, who has won 10 senior titles on the Professional Darts Corporation tour this year, is the first darts player to claim the award. "It shows how well I have done this year, not only for myself, but I have changed the sport of darts," Littler told BBC One. "I know the amount of academies that have been brought up in different locations, tickets selling out at Ally Pally in hours and the Premier League selling out - it just shows how much I have changed it."

He was presented with the trophy by Harry Aikines-Aryeetey - a former sprinter who won the award in 2005 - and ex-rugby union player Jodie Ounsley, both of whom are stars of the BBC television show Gladiators. Skateboarder Sky Brown, 16, and Para-swimmer William Ellard, 18, were also shortlisted for the award. Littler became a household name at the start of 2024 by reaching the World Championship final aged just 16 years and 347 days. That achievement was just the start of a trophy-laden year, with Littler winning the Premier League Darts, Grand Slam and World Series of Darts Finals among his haul of titles. Littler has gone from 164th to fourth in the world rankings and earned more than £1m in prize money in 2024. The judging panel for Young Sports Personality of the Year included Paralympic gold medallist Sammi Kinghorn, Olympic silver medal-winning BMX freestyler Keiran Reilly, television presenter Qasa Alom and Radio 1 DJ Jeremiah Asiamah, as well as representatives from the Youth Sport Trust, Blue Peter and BBC Sport.
--------------------------------------------------------------------------------
Score: 0.5414, Text: Wright is the 17th seed at the World Championship

Two-time champion Peter Wright won his opening game at the PDC World Championship, while Ryan Meikle edged out Fallon Sherrock to set up a match against teenage prodigy Luke Littler. Scotland's Wright, the 2020 and 2022 winner, has been out of form this year, but overcame Wesley Plaisier 3-1 in the second round at Alexandra Palace in London. "It was this crowd that got me through, they wanted me to win. I thank you all," said Wright. Meikle came from a set down to claim a 3-2 victory in his first-round match against Sherrock, who was the first woman to win matches at the tournament five years ago. The 28-year-old will now play on Saturday against Littler, who was named BBC Young Sports Personality of the Year and runner-up in the main award to athlete Keely Hodgkinson on Tuesday night. Littler, 17, will be competing on the Ally Pally stage for the first time since his rise to stardom when finishing runner-up in January's world final to Luke Humphries. Earlier on Tuesday, World Grand Prix champion Mike de Decker – the 24th seed - suffered a surprise defeat to Luke Woodhouse in the second round. He is the second seed to exit following 16th seed James Wade's defeat on Monday to Jermaine Wattimena, who meets Wright in round three. Kevin Doets recovered from a set down to win 3-1 against Noa-Lynn van Leuven, who was making history as the first transgender woman to compete in the tournament.

Sherrock drew level at 2-2 but lost the final set to Meikle

The 54-year-old Wright only averaged 89.63 to his opponent's 93.77, but did enough to progress. Sporting a purple mohawk and festive outfit, crowd favourite 'Snakebite' showed glimpses of his best to win the first set and survived eight set darts to go 2-0 ahead. He lost the next but Dutchman Plaisier missed two more set darts in the fourth and Wright seized his opportunity. "Wesley had his chances but he missed them and I took them," he said. "He's got his tour card and he's going to be a dangerous player next year for all the players playing against him." Sherrock, 30, fought back from 2-1 down to force a decider against her English compatriot Meikle. She then narrowly missed the bull to take out 170 in the fourth leg before left-hander Meikle held his nerve to hit double 18 for a 96 finish to seal a hard-fought success. "I felt under pressure from the start and to come through feels unbelievable," said Meikle. "It's an unbelievable prize to play Luke here on this stage. It's the biggest stage of them all. I'm so happy." World number 81 Jeffrey de Graaf, who was born in the Netherlands but now represents Sweden, looked in trouble against Rashad Sweeting before prevailing 3-1. Sweeting, who was making history as the first player from the Bahamas to compete in the tournament, took the first set, but De Graaf fought back to clinch a second-round meeting with two-time champion Gary Anderson Germany's Ricardo Pietreczko, ranked 34, beat China's Xiaochen Zong 3-1 and will face Gian van Veen next.
--------------------------------------------------------------------------------
Score: 0.5403, Text: Second seed Smith knocked out of Worlds by Doets

Michael Smith was 2-1 ahead but fell to a shock exit

Former champion Michael Smith has been sensationally knocked out of the PDC World Championship by Kevin Doets. Englishman Smith, seeded second, went down 3-2 after a pulsating second-round duel at Alexandra Palace in London. Dutchman Doets prevailed 6-4 in the deciding set, despite checkouts of 123, 84, 94 and 76 from 2023 champion Smith. "This was the most stressful game of my life and I've won it, yes," said world number 51 Doets. "I felt if I can keep my focus, I won't lose this. It was so very tight, to get over the line was amazing." Doets, 26, took the first set and fought back after going 2-1 down to avenge his narrow defeat to Smith at the same stage last year. Having lost in the second round of the tournament for the first time since 2020, the 34-year-old Smith will now drop to at least 15 in the rankings.

Doets won in the first round against Noa-Lynn van Leuven, who was the first transgender woman to play in the tournament

England's Scott Williams, who made a shock run to the semi-finals in the 2024 tournament before losing to eventual champion Luke Humphries, overcame Niko Springer 3-1 in a thriller. German debutant Springer, second on this year's development tour, won all three legs in the opening set before the match exploded into life. Williams hit back, showing his old swagger as he went ahead after a sensational third set which featured seven 180s. The 34-year-old edged the deciding leg in the fourth and will meet 2018 champion Rob Cross in round two on Monday. Nick Kenny delighted the Ally Pally crowd with a fabulous 170 finish to seal a 3-0 victory in round one over American Stowe Buntz. The Welshman, 31, will face five-time world champion Raymond Barneveld on Saturday evening on a bill which also features teenage star Luke Littler against Ryan Meikle. Canadian Matt Campbell set up a second-round match against Ryan Searle with a 3-2 defeat of Austrian Mensur Suljovic.

England's Callan Rydz averaged 107.06 to book his place in the second round, before Gabriel Clemens was knocked out by Wales' Robert Owen on Thursday afternoon. Rydz beat Croatian Romeo Grbavac 3-0, recording the tournament's highest average first-round match average in its current 96-player format. It was the competition's 26th highest match average overall and comfortably the best so far at the 2025 event. The previous record was held by teenager Luke Littler, who scored 106.12 at this stage last year. Rydz, from Bedlington in Northumberland, meets Germany's Martin Schindler in the second round on Sunday evening. The afternoon session concluded with Germany's 27th seed Clemens being beaten by Owen, who is ranked 50 places below him. Owen recorded a 3-1 victory, his second in a matter of days, to reach the third round, which begins on 27 December. Hong Kong's Lok Yin Lee came from a set down to beat Chris Landman 3-1 after winning nine straight legs. Lee will face Northern Ireland's Brendan Dolan in round two on Saturday afternoon. Meanwhile, 2024 Grand Slam of Darts runner-up Martin Lukeman came from a set down to beat Indian qualifier Nitin Kumar 3-1. Lukeman meets 21st seed Andrew Gilding on Monday afternoon for a place in the last 32.
--------------------------------------------------------------------------------
Score: 0.5329, Text: Cross loses as record number of seeds out of Worlds

Rob Cross has suffered three second-round exits in his eight World Championships

Former champion Rob Cross became the latest high-profile casualty as a record-breaking 14th seed exited the PDC World Darts Championship in the second round. The number five seed was beaten 3-1 by close friend Scott Williams, who will face Germany's Ricardo Pietreczko in round three. Cross, who won the event on his debut in 2018, took the opening set but failed to reach anywhere near his best as he suffered his third second-round exit. He was joined by number six seed David Chisnall, who was beaten 3-2 in a sudden-death leg by Ricky Evans, who came into the tournament 46th in the PDC's Order of Merit. The 2021 semi-finalist won the opening set, but then found himself 2-1 down to an inspired Evans, who was cheered on relentlessly by the Alexandra Palace crowd. He forced the game into a deciding set and faced match dart but Evans missed bullseye by the width of the wire. Chisnall then missed his own match dart on double tops, before he made a miscalculation when attempting to checkout 139 at 5-4 down. No real harm was done with a sudden-death leg forced but he was unable to hold off Evans, who reaches the third round for the third time in the last five years. "It's not even what it is, again I've played a world-class darts player. I've played quite well and won," Evans told Sky Sports. "Look at this [the crowd], wow. I don't understand it, why are they cheering me on? "I don't get this reception in my household. Thank you very much. You've made a very fat guy very happy." Evans will face unseeded Welshman Robert Owen when the third round starts after the three-day Christmas break.

World youth champion Gian van Veen had become the 12th seed to be knocked out when he lost 3-1 to Pietreczko. The 28th seed lost the opening set, having missed nine darts at double, but levelled. However, the Dutchman was unable to match Pietreczko, who closed out a comfortable win with a checkout percentage of 55.6%. Pietreczko said: "I am over the moon to win. It is very important for me to be in the third round after Christmas. I love the big stage." The 26th seed trailed 1-0 and 2-1, and both players went on to miss match darts, before Gurney won the final set 3-1 on legs.

Jonny Clayton is into the third round of the PDC World Darts Championship for a sixth consecutive year

In the afternoon session, Welsh number seven seed Jonny Clayton also needed sudden death to pull off a sensational final-set comeback against Mickey Mansell in. He was a leg away from defeat twice to his Northern Irish opponent, but came from behind to win the final set 6-5 in a sudden-death leg to win 3-2. Clayton, who will play Gurney in round three, lost the opening set of the match, but fought back to lead 2-1, before being pegged back again by 51-year-old Mansell, who then missed match darts on double tops in the deciding set. "I was very emotional. I've got to be honest, that meant a lot," said Clayton, who is in the favourable half of the draw following shock second-round exits for former world champions Michael Smith and Gary Anderson. "I had chances before and Mickey definitely had chances before. It wasn't great to play in, not the best - I wouldn't wish that on my worst enemy. "There is a lot of weight off my shoulders after that. I know there is another gear or two in the bank, but I'll be honest that meant a lot to me, it is a tester and will try and make me believe again." Clayton was 2-0 down in the fifth set after consecutive 136 and 154 checkouts from Mansell, but won three legs on the trot in 15, 12 and 10 darts to wrestle a 3-2 lead. He missed three darts for the match, before his unseeded opponent held and broke Clayton's throw to lead 4-3. Mansell missed a match dart at double 20, before Clayton won on double five after two missed checkouts. Elsewhere, Northern Ireland's Josh Rock booked his place in the third round against England's Chris Dobey with a 3-0 win over Wales' Rhys Griffin. Martin Lukeman, runner-up to Luke Littler at the Grand Slam of Darts last month, is out after a 3-1 loss to number 21 seed Andrew Gilding. The final day before the Christmas break started with Poland's number 31 seed Krzysztof Ratajski recording a 3-1 win over Alexis Toylo of the Philippines.

All times are GMT and subject to change. Two fourth-round matches will also be played
--------------------------------------------------------------------------------
Score: 0.5118, Text: Michael van Gerwen has made just one major ranking event final in 2024

Michael van Gerwen enjoyed a comfortable 3-0 victory over English debutant James Hurrell in his opening match of the PDC World Darts Championship. The three-time world champion has had a tough year by his standards, having fallen behind Luke Littler and Luke Humphries, so a relatively stress-free opening match at Alexandra Palace was just what was needed. Hurrell, 40, offered some resistance early on when taking the opening leg of the match, but he would win just two more as Van Gerwen proved far too strong. The third-seeded Dutchman averaged 94.85, took out two three-figure checkouts and hit 50% of his doubles - with six of his nine misses coming in one scrappy leg. Van Gerwen, 35, will now face either Brendan Dolan or Lok Yin Lee in the third round.

"I think I played OK," Van Gerwen told Sky Sports after his match. "Of course, I was a bit nervous. Like everyone knows it's been a tough year for me. "Overall, it was a good performance. I was confident. I won the game, that's the main thing." Also on Friday night, Germany's Florian Hempel showed why he loves playing on the Alexandra Palace stage with a thrilling 3-1 victory in a high-quality contest against Jeffrey de Zwaan. Both men hit seven 180s in a match played at a fast and furious pace, but 34-year-old Hempel's superior doubles gave him a fourth straight first-round victory in the competition. Hempel moves on to a tie with 26th seed Daryl Gurney but it was a damaging loss for De Zwaan, 28, who came through a late qualifier in November and needed a good run here to keep his PDC tour card for next season. Mickey Mansell earned a second-round date with world number seven Jonny Clayton after a scrappy 3-1 win over Japan's Tomoya Goto, while Dylan Slevin came through an all-Irish tie against William O'Connor to progress to a meeting with Dimitri van den Bergh.

Stephen Bunting is in the third round of the PDC World Darts Championship for a third consecutive year

In the afternoon session, Stephen Bunting came from behind to beat Kai Gotthardt 3-1 and book his place in the third round. Englishman Bunting, ranked eighth in the world, dropped the first set and almost went 2-0 down in the match before staging an impressive recovery. Tournament debutant Gotthardt missed three darts at double eight to win the second set, allowing Bunting to take out double 10 to level the match before powering away to victory by winning the third and fourth sets without losing a leg. Victory for "The Bullet" sets up a last 32 meeting with the winner of Dirk van Duijvenbode's meeting with Madars Razma after Christmas. Should Bunting progress further, he is seeded to face world number one and defending world champion Luke Humphries in the quarter-finals on New Year's Day. Elsewhere in Friday afternoon's session, the Dutch duo of Alexander Merkx and Wessel Nijman advanced to the second round with wins over Stephen Burton and Cameron Carolissen respectively. England's Ian White was handed a walkover victory against Sandro Eric Sosing of the Philippines. Sosing withdrew from the competition on medical grounds and was taken to hospital following chest pains.
--------------------------------------------------------------------------------
Score: 0.5114, Text: Gary Anderson was the fifth seed to be beaten on Sunday

Two-time champion Gary Anderson has been dumped out of the PDC World Championship on his 54th birthday by Jeffrey de Graaf. The Scot, winner in 2015 and 2016, lost 3-0 to the Swede in a second-round shock at Alexandra Palace in London. "Gary didn't really show up as he usually does. I'm very happy with the win," said De Graaf, 34, who had a 75% checkout success and began with an 11-dart finish. "It's a dream come true for me. He's been my idol since I was 14 years old." Anderson, ranked 14th, became the 11th seed to be knocked out from the 24 who have played so far, and the fifth to fall on Sunday.

He came into the competition with the year's highest overall three-dart average of 99.66 but hit just three of his 20 checkout attempts to lose his opening match of the tournament for the first time. De Graaf will now meet Filipino qualifier Paolo Nebrida after he stunned England's Ross Smith, the 19th seed, in straight sets. Ritchie Edhouse, Dirk van Duijvenbode and Martin Schindler were the other seeds beaten on day eight. England's Callan Rydz, who hit a record first-round average of 107.06 on Thursday, followed up with a 3-0 win over 23rd seed Schindler on Sunday. The German missed double 12 for a nine-darter in the first set – the third player to do so in 24 hours after Luke Littler and Damon Heta – and ended up losing the leg. Rydz next meets Belgian Dimitri van den Bergh, who hit six 180s and averaged 96 in a 3-0 win over Irishman Dylan Slevin.

England's Joe Cullen abruptly left his post-match news conference and accused the media of not showing him respect after his 3-0 win over Dutchman Wessel Nijman. Nijman, who has previously served a ban for breaching betting and anti-corruption rules, had been billed as favourite beforehand to beat 23rd seed Cullen. "Honestly, the media attention that Wessel's got, again this is not a reflection on him," Cullen said. "He seems like a fantastic kid, he's been caught up in a few things beforehand, but he's served his time and he's held his hands up, like a lot haven't. "I think the way I've been treated probably with the media and things like that - I know you guys have no control over the bookies - I've been shown no respect, so I won't be showing any respect to any of you guys tonight. "I'm going to go home. Cheers." Ian 'Diamond' White beat European champion and 29th seed Edhouse 3-1 and will face teenage star Littler in the next round. White, born in the same Cheshire town as the 17-year-old, acknowledged he would need to up his game in round three. Asked if he knew who was waiting for him, White joked: "Yeah, Runcorn's number two. I'm from Runcorn and I'm number one." Ryan Searle started Sunday afternoon's action off with a 10-dart leg and went on to beat Matt Campbell 3-0, while Latvian Madars Razma defeated 25th seed Van Duijvenbode 3-1. Seventh seed Jonny Clayton and 2018 champion Rob Cross are among the players in action on Monday as the second round concludes. The third round will start on Friday after a three-day break for Christmas.
--------------------------------------------------------------------------------
Score: 0.5106, Text: Christian Kist was sealing his first televised nine-darter

Christian Kist hit a nine-darter but lost his PDC World Championship first-round match to Madars Razma. The Dutchman became the first player to seal a perfect leg in the tournament since Michael Smith did so on the way to beating Michael van Gerwen in the 2023 final. Kist, the 2012 BDO world champion at Lakeside, collects £60,000 for the feat, with the same amount being awarded by sponsors to a charity and to one spectator inside Alexandra Palace in London. The 38-year-old's brilliant finish sealed the opening set, but his Latvian opponent bounced back to win 3-1. Darts is one of the few sports that can measure perfection; snooker has the 147 maximum break, golf has the hole-in-one, darts has the nine-dart finish. Kist scored two maximum 180s to leave a 141 checkout which he completed with a double 12, to the delight of more than 3,000 spectators. The English 12th seed, who has been troubled by wrist and back injuries, could next play Andrew Gilding in the third round - which begins on 27 December - should Gilding beat the winner of Martin Lukeman's match against qualifier Nitin Kumar. Aspinall faces a tough task to reach the last four again, with 2018 champion Rob Cross and 2024 runner-up Luke Littler both in his side of the draw.

Kist - who was knocked out of last year's tournament by teenager Littler - will still earn a bigger cheque than he would have got for a routine run to the quarter-finals. His nine-darter was the 15th in the history of the championship and first since the greatest leg in darts history when Smith struck, moments after Van Gerwen just missed his attempt. Darts fan Kris, a railway worker from Sutton in south London, was the random spectator picked out to receive £60,000, with Prostate Cancer UK getting the same sum from tournament sponsors Paddy Power. "I'm speechless to be honest. I didn't expect it to happen to me," Kris said. "This was a birthday present so it makes it even better. My grandad got me tickets. It was just a normal day - I came here after work." Kist said: "Hitting the double 12 felt amazing. It was a lovely moment for everyone and I hope Kris enjoys the money. Maybe I will go on vacation next month." Earlier, Jim Williams was favourite against Paolo Nebrida but lost 3-2 in an epic lasting more than an hour. The Filipino took a surprise 2-1 lead and Williams only went ahead for the first time in the opening leg of the deciding set. The Welshman looked on course for victory but missed five match darts. UK Open semi-finalist Ricky Evans set up a second-round match against Dave Chisnall, checking out on 109 to edge past Gordon Mathers 3-2.
--------------------------------------------------------------------------------

CouchbaseとLangChainを使用した検索拡張生成(RAG)

Couchbase と LangChain はシームレスに統合され、RAG (Retrieval-Augmented Generation) チェーンを作成できます。これにより、文脈的に関連したレスポンスの生成プロセスが強化されます。この設定では、Couchbase がベクターストアとして機能し、ドキュメントのエンベディングが保存されます。クエリが実行されると、LangChain はクエリのエンベディングと保存されたドキュメントエンベディングを比較して、最も関連性の高いドキュメントをCouchbaseから取得します。これらの文脈情報を提供するドキュメントは、LangChain 内の生成言語モデルに渡されます。.

取得したドキュメントのコンテキストを搭載した言語モデルは、情報に基づいた正確なレスポンスを生成します。この統合により、RAG チェーンはCouchbaseの効率的なストレージと検索機能を利用できます。一方、LangChainは取得したドキュメントのコンテキストに基づいてレスポンスの生成を行います。これらを組み合わせることで、検索と生成の両方の強みを組み合わせ、非常に関連性があり正確な回答を提供できる強力なシステムが構築されます。.

# RAG プロンプトテンプレートを作成する
rag_prompt = ChatPromptTemplate.from_messages([
    (「システム」、「あなたは提供された文脈に基づいて質問に答える役に立つアシスタントです。」)
    (「人間」、「文脈: {context}nn質問:」 {question})
])

# RAG チェーンを作成する
rag_chain = (
    {"context": vector_store.as_retriever(), "question": RunnablePassthrough()}
    |rag_prompt
    LLM
    | StrOutputParser()
)
logging.info("RAG チェーンが正常に作成されました")
2026-02-12 10:39:17,847 - INFO - Successfully created RAG chain
試す:
    start_time = time.time()
    rag_response = rag_chain.invoke(query)
    rag_elapsed_time = time.time() - start_time

    print(f"RAG Response: {rag_response}")
    print(f"RAG の応答が {rag_elapsed_time:.2f} 秒で生成されました")
内部サーバー障害例外 e の場合を除いて:
    「query request rejected」が str(e) にあれば:
        print("エラー:レート制限により検索リクエストが拒否されました。後ほどもう一度お試しください")
    else:
        print(f"内部サーバーエラーが発生しました: {str(e)}")
例外として e を除きます:
    print(f"予期せぬエラーが発生しました: {str(e)}")
RAG Response: Based on the provided context, Luke Littler's key achievements and records in his recent PDC World Championship second-round match against Ryan Meikle were:

1.  **Tournament Record Average:** He hit a tournament record **set average of 140.91** during the fourth and final set of the match.
2.  **Near-Perfect Set:** In that same fourth set, he won three consecutive legs in 11, 10, and 11 darts, completing the set in just 32 darts (the minimum possible is 27).
3.  **Near-Nine-Darter:** He was "millimetres away" from achieving a nine-dart finish, narrowly missing double 12 on two separate occasions during the match.
4.  **Victory:** He won the match with a score of 3-1 to advance to the next round.
RAG response generated in 11.62 seconds

キャッシュの利点を実証する

Couchbaseは、RAG(Retrieval-Augmented Generation)のレスポンスに対するキャッシュメカニズムとして、特定のクエリに対する事前計算済みの結果を保存および取得することで効果的に使用できます。このアプローチは、特に繰り返しまたは類似したクエリに対応する場合、システムの効率性と速度を向上させます。クエリが最初に処理されるとき、RAG チェーンは関連するドキュメントを検索し、言語モデルを使用してレスポンスを生成し、そのレスポンスをCouchbaseに保存します。このクエリはキーとして機能します。.

同じクエリの次回のリクエストでは、システムがまずCouchbaseをチェックします。キャッシュされたレスポンスが見つかった場合は、RAGプロセス全体を再実行する必要がなくなって、直接Couchbaseから取得されます。これによりレスポンスタイムが大幅に短縮されます。これは、ドキュメントの検索とレスポンス生成という計算に時間がかかるステップを省くためです。このセットアップにおけるCouchbaseの役割は、これらのレスポンスをキャッシュするための高速でスケーラブルなストレージソリューションを提供することであり、頻繁に寄せられる問い合わせをより迅速かつ効率的に回答できるよう保証します。.

試す:
    クエリー = [
        「フルハムとリバプールの一戦で何が起こったのか?」
        「ルーク・リッターの最近の PDC ワールドチャンピオンシップでの試合における主な実績と記録は何でしたか?」 #
        「フルハムとリバプールの一戦で何が起こったのか?」という # 繰り返し質問
    [

    i の場合、enumerate(queries, 1) のクエリーを実行します。
        print(f"nQuery {i}: {query}")
        start_time = time.time()

        response = rag_chain.invoke(query)
        elapsed_time = time.time() - start_time
        print(f"レスポンス: {response}")
        print(f"所要時間:{elapsed_time:.2f}秒")

内部サーバー障害例外 e の場合を除いて:
    「query request rejected」が str(e) にあれば:
        print("エラー:レート制限により検索リクエストが拒否されました。後ほどもう一度お試しください")
    else:
        print(f"内部サーバーエラーが発生しました: {str(e)}")
例外として e を除きます:
    print(f"予期せぬエラーが発生しました: {str(e)}")
Query 1: What happened in the match between Fullham and Liverpool?
Response: In the match between Fulham and Liverpool, Liverpool played with 10 men for the majority of the game after Andy Robertson received a red card in the 17th minute. Despite the numerical disadvantage, Liverpool twice came from behind to secure a 2-2 draw. Diogo Jota scored an 86th-minute equalizer to earn Liverpool a point. Fulham's Antonee Robinson commented that Liverpool played so well it "didn't feel like they had 10 men at all." Liverpool manager Arne Slot praised his team's character and described their performance as "outstanding" in the face of adversity.
Time taken: 4.53 seconds

Query 2: What were Luke Littler's key achievements and records in his recent PDC World Championship match?
Response: Based on the provided context, Luke Littler's key achievements and records in his recent PDC World Championship second-round match against Ryan Meikle were:

1.  **Tournament Record Average:** He hit a tournament record **set average of 140.91** during the fourth and final set of the match.
2.  **Near-Perfect Set:** In that same fourth set, he won three consecutive legs in 11, 10, and 11 darts, completing the set in just 32 darts (the minimum possible is 27).
3.  **Near-Nine-Darter:** He was "millimetres away" from achieving a nine-dart finish, narrowly missing double 12 on two separate occasions during the match.
4.  **Victory:** He won the match with a score of 3-1 to advance to the next round.
Time taken: 0.31 seconds

Query 3: What happened in the match between Fullham and Liverpool?
Response: In the match between Fulham and Liverpool, Liverpool played with 10 men for the majority of the game after Andy Robertson received a red card in the 17th minute. Despite the numerical disadvantage, Liverpool twice came from behind to secure a 2-2 draw. Diogo Jota scored an 86th-minute equalizer to earn Liverpool a point. Fulham's Antonee Robinson commented that Liverpool played so well it "didn't feel like they had 10 men at all." Liverpool manager Arne Slot praised his team's character and described their performance as "outstanding" in the face of adversity.
Time taken: 0.30 seconds

結論

You’ve built a semantic search engine using Couchbase Search Vector Index with OpenRouter DeepSeek and LangChain. For the Hyperscale/Composite Vector Index alternative, see the query_based tutorial.

データベースの膨大なサイズを過去のものとしておく

スタックの追加ごとに新たな請求書が発生し、管理するものがさらに増えます。2分でどれだけの節約ができるかを試算してください。.