AI21 Studio チュートリアル: Chat Completions APIをマスターする
AI21 Studioの上級チュートリアルへようこそ!このノートブックでは、統一されたChat Completions APIを活用して幅広いタスクを実行する方法を示します。異なるタスクごとに異なるAPIを使うのではなく、単一のモデルJamba-miniに細心のプロンプトを与えることで、テキスト生成、言い換え、要約、文脈に基づくQ&Aを実行する方法を紹介します。
1. セットアップとインストール
まず、必要なライブラリをインストールしましょう。その後、.envファイルからAPIキーを自動的に読み込むAI21Clientを設定します。
#!pip install -q ai21 python-dotenvimport os
from ai21 import AI21Client
from ai21.models.chat import ChatMessage
from dotenv import load_dotenv
# Load environment variables from a .env file
load_dotenv()
# The client automatically uses the AI21_API_KEY environment variable
client = AI21Client()2. 一般的なテキスト生成
一般的なテキスト生成では、ユーザーメッセージに指示を含めてモデルに渡します。モデルは「アシスタント」の役割で応答を生成します。
def generate_text_with_chat(user_prompt):
"""Generates text using the Chat Completions API."""
try:
messages = [ChatMessage(role="user", content=user_prompt)]
response = client.chat.completions.create(
model="jamba-mini",
messages=messages,
max_tokens=150
)
return response.choices[0].message.content
except Exception as e:
return f"An error occurred: {e}"
# Example usage
prompt = "Write a short, optimistic paragraph about the future of renewable energy."
generated_text = generate_text_with_chat(prompt)
print(f"Generated Text:\n{generated_text}")Generated Text: The future of renewable energy is brighter than ever, with groundbreaking innovations and growing global investments driving its rapid expansion. Solar, wind, and battery technologies are becoming more efficient and cost-effective, making clean energy accessible to communities worldwide. As nations prioritize sustainability, renewable energy will play a pivotal role in combating climate change, creating jobs, and fostering energy independence. The transition to renewables is not just an environmental necessity but a powerful opportunity to build a cleaner, healthier, and more equitable future for generations to come.
3. チャットタスクとしての言い換え
テキストを言い換えるには、システムメッセージを使ってモデルに特定の役割を割り当てることで指示します。システムメッセージは、モデルの振る舞いを導き、専門の編集者として振る舞うように伝えます。ユーザーメッセージには、言い換え対象のテキストを指定します。
def paraphrase_text_with_chat(text_to_paraphrase):
"""Paraphrases text using an instruction-based chat call."""
try:
system_prompt = "You are an expert editor. Your task is to paraphrase the given text, ensuring the original meaning is perfectly preserved but the wording is different."
user_prompt = f"Please paraphrase the following text: \"{text_to_paraphrase}\""
messages = [
ChatMessage(role="system", content=system_prompt),
ChatMessage(role="user", content=user_prompt)
]
response = client.chat.completions.create(
model="jamba-mini",
messages=messages,
max_tokens=100
)
return response.choices[0].message.content
except Exception as e:
return f"An error occurred: {e}"
# Example usage
original_text = "The quick brown fox jumps over the lazy dog."
paraphrased_text = paraphrase_text_with_chat(original_text)
print(f"Original Text: {original_text}")
print(f"Paraphrased Text: {paraphrased_text}")Original Text: The quick brown fox jumps over the lazy dog. Paraphrased Text: The fast-moving brown fox leaps gracefully over the sluggish dog.
4. チャットタスクとしての要約
同様に、システムメッセージでモデルの役割を定義し、長いテキストをユーザーメッセージに渡すことで要約を実行できます。
def summarize_text_with_chat(long_text):
"""Summarizes text using an instruction-based chat call."""
try:
system_prompt = "You are a helpful assistant that summarizes long texts into a single, concise paragraph."
user_prompt = f"Please summarize the following text: \n\n{long_text}"
messages = [
ChatMessage(role="system", content=system_prompt),
ChatMessage(role="user", content=user_prompt)
]
response = client.chat.completions.create(
model="jamba-mini",
messages=messages,
max_tokens=200
)
return response.choices[0].message.content
except Exception as e:
return f"An error occurred: {e}"
# Example usage
text_to_summarize = """AI21 Labs is an AI company specializing in Natural Language Processing. Founded in 2017, its goal is to build AI systems with an unprecedented capacity to understand and generate natural language. They have developed a family of large language models, including the Jurassic and Jamba series, which are among the largest and most sophisticated in the world. These models power applications for text generation, summarization, and paraphrasing."""
summary = summarize_text_with_chat(text_to_summarize)
print(f"Summary:\n{summary}")Summary: AI21 Labs, founded in 2017, is an AI company specializing in Natural Language Processing, aiming to build AI systems with advanced natural language understanding and generation capabilities. They have developed a family of large language models, including the Jurassic and Jamba series, which are among the largest and most sophisticated in the world, powering applications for text generation, summarization, and paraphrasing.
5. 文脈に基づく回答をチャットタスクとして実行
最後に、ユーザープロンプト内にコンテキストと質問を提供することでQ&Aシステムを構築できます。システムプロンプトは、モデルに提供されたコンテキストのみを使用して回答するよう指示します。
def get_contextual_answer_with_chat(context, question):
"""Gets a contextual answer using an instruction-based chat call."""
try:
system_prompt = "You are a question-answering assistant. You must answer the user's question based ONLY on the provided context. If the answer is not in the context, say 'The answer is not available in the provided text.'"
user_prompt = f"Context: {context}\n\nQuestion: {question}"
messages = [
ChatMessage(role="system", content=system_prompt),
ChatMessage(role="user", content=user_prompt)
]
response = client.chat.completions.create(
model="jamba-mini",
messages=messages,
max_tokens=100
)
return response.choices[0].message.content
except Exception as e:
return f"An error occurred: {e}"
# Example usage
qa_context = "The capital of France is Paris. Paris is known for its art, fashion, and culture."
qa_question = "What is the primary industry in Paris?"
answer = get_contextual_answer_with_chat(qa_context, qa_question)
print(f"Context: {qa_context}")
print(f"Question: {qa_question}")
print(f"Answer: {answer}")Context: The capital of France is Paris. Paris is known for its art, fashion, and culture. Question: What is the primary industry in Paris? Answer: The answer is not available in the provided text.
6. まとめと次のステップ
このノートブックでは、単一の統一されたChat Completionsインターフェース(jamba-miniモデル)を使って、会話メッセージを変えるだけで複数の古典的なNLP機能を実現できることを確認しました。
構築したもの
- ユーザーメッセージのみでの一般的なテキスト生成
- システムメッセージによる明示的な編集役割の割り当てによる言い換え
- システムプロンプトでスタイルと圧縮を制御することによる要約
- 提供されたコンテキストを超えて幻覚を起こさない文脈制限Q&A
次のステップ
- これらの関数を軽量なFastAPIまたはFlaskサービスにラップする
- 対話的な実験のためにフロントエンド(Streamlit / Gradio)を作成する
- 以前の
assistantおよびuserメッセージを追加することで多ターン会話に拡張する - レイテンシとトークンコストのトレードオフに応じて、より大きなAI21モデルを探索する
慎重なプロンプト設計と薄いヘルパー関数の層により、一貫したチャットエンドポイントを使用して広範な言語タスクをカバーできます。Happy building! 🚀