6.2 Pythonを使ったLLM実装例 | Hugging Face, OpenAI, Google Cloud, Azureを活用したテキスト生成

前回は、LLMを活用するためのオープンソースツールやAPIについて学びました。今回は、実際にPythonを使ってLLMを試してみましょう。

6.2 Pythonを使った簡単な実装例

LLM(大規模言語モデル)は、Pythonで簡単に実装できます。Hugging FaceやOpenAI、Google Cloud、AzureなどのライブラリやAPIを使用すれば、高度な自然言語処理(NLP)タスクを手軽に行うことが可能です。ここでは、Pythonを使ったLLMの簡単な実装例をいくつか紹介します。

6.2.1 Hugging Face Transformersでのテキスト生成

Hugging Face Transformersは、事前トレーニング済みのモデルを簡単に使用できるライブラリです。以下の例では、GPT-2を使用してテキスト生成を行います。

# Hugging Faceライブラリのインストール
!pip install transformers

# モデルとトークナイザーの読み込み
from transformers import GPT2LMHeadModel, GPT2Tokenizer

model = GPT2LMHeadModel.from_pretrained("gpt2")
tokenizer = GPT2Tokenizer.from_pretrained("gpt2")

input_text = "The future of AI is"
input_ids = tokenizer.encode(input_text, return_tensors="pt")
output = model.generate(input_ids, max_length=50)

print(tokenizer.decode(output[0], skip_special_tokens=True))

このコードでは、GPT-2モデルを使用して、与えられたテキストの続きとなる文章を生成します。簡単にモデルを読み込み、テキスト生成が可能です。

6.2.2 OpenAI APIでのテキスト生成

OpenAI APIは、GPTシリーズを利用できるAPIです。以下の例では、OpenAIのGPT-3を使ってテキストを生成します。

# OpenAIライブラリのインストール
!pip install openai

# APIキーの設定
import openai
openai.api_key = 'YOUR_API_KEY'

# テキスト生成
response = openai.Completion.create(
    model="text-davinci-003",
    prompt="The future of AI is",
    max_tokens=50
)

print(response.choices[0].text.strip())

このコードは、OpenAI APIを使用してプロンプトに基づいたテキスト生成を行います。APIキーの設定後、簡単にテキスト生成が可能です。

6.2.3 Google Cloud AIでのテキスト解析

Google Cloud AIは、BERTなどのモデルを使用してテキスト解析を行うためのAPIを提供しています。以下は、Google Cloudの自然言語APIを使用した感情分析の例です。

# Google Cloudライブラリのインストール
!pip install google-cloud-language

# クライアントの設定
from google.cloud import language_v1
client = language_v1.LanguageServiceClient()

document = language_v1.Document(content="The future of AI is bright.", type_=language_v1.Document.Type.PLAIN_TEXT)
response = client.analyze_sentiment(document=document)

print(f"Sentiment score: {response.document_sentiment.score}")

Google Cloud AIのAPIを使用すれば、大規模なデータに対してスケーラブルに感情分析が可能です。

6.2.4 Azure Cognitive Servicesでのテキスト生成

Azure Cognitive Servicesは、Microsoftが提供するクラウドベースのAIサービスで、テキスト生成や分析が簡単に行えます。以下は、Azureのテキスト生成APIを使用した例です。

# Azureライブラリのインストール
!pip install azure-ai-textanalytics

# クライアントの設定
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

endpoint = "YOUR_ENDPOINT"
key = "YOUR_KEY"
client = TextAnalyticsClient(endpoint=endpoint, credential=AzureKeyCredential(key))

documents = ["The future of AI is bright."]
response = client.analyze_sentiment(documents)

for idx, doc in enumerate(response):
    print(f"Document {idx}: Sentiment score {doc.confidence_scores}")

Azure Cognitive Servicesを使用することで、クラウド上で効率的なテキスト生成や分析が可能になります。

Pythonを使ったLLMの実装は非常に簡単で、Hugging Face、OpenAI、Google Cloud、AzureなどのライブラリやAPIを使用すれば、多様なNLPタスクに対応できます。ぜひ上記のコードを試してみて、LLMの強力な機能を実感してください。

それでは、最後の章となる第7章「LLMの未来と課題」について学び、これからの技術動向を見ていきましょう。

公開日: 2024-09-26
最終更新日: 2025-02-01
バージョン: 3

下田 昌平

開発と設計を担当。1994年からプログラミングを始め、今もなお最新技術への探究心を持ち続けています。