ドキュメンテーション

開始方法

エージェントフロー

テキスト埋め込み

トークン化

モデルの管理

モデル情報

チャット補完

チャット会話の補完を生成するには、llm.respond(...)を使用します。

クイック例: チャット応答の生成

以下のスニペットは、クイックチャットプロンプトに対するAIの応答を取得する方法を示しています。

import lmstudio as lms
model = lms.llm()
print(model.respond("What is the meaning of life?"))

チャット応答のストリーミング

以下のスニペットは、チャットプロンプトに対するAIの応答をストリーミングし、テキストフラグメントが受信されるたびに表示する方法を示しています(応答全体が生成されるのを待ってから表示するのではなく)。

import lmstudio as lms
model = lms.llm()

for fragment in model.respond_stream("What is the meaning of life?"):
    print(fragment.content, end="", flush=True)
print() # Advance to a new line at the end of the response

チャット応答のキャンセル

進行中の予測をキャンセルする方法については、「予測のキャンセル」セクションを参照してください。

モデルの取得

まず、モデルハンドルを取得する必要があります。これは、トップレベルのllm簡易API、またはスコープ付きリソースAPIを使用する際のllm名前空間内のmodelメソッドを使用して行えます。例えば、Qwen2.5 7B Instructの使用方法は以下の通りです。

import lmstudio as lms
model = lms.llm("qwen2.5-7b-instruct")

モデルハンドルを取得する方法は他にもあります。詳細については、「メモリ内のモデル管理」を参照してください。

チャットコンテキストの管理

モデルへの入力は「コンテキスト」と呼ばれます。概念的には、モデルは複数ターンの会話を入力として受け取り、その会話におけるアシスタントの応答を予測するよう求められます。

import lmstudio as lms

# Create a chat with an initial system prompt.
chat = lms.Chat("You are a resident AI philosopher.")

# Build the chat context by adding messages of relevant types.
chat.add_user_message("What is the meaning of life?")
# ... continued in next example

チャットコンテキストの管理に関する詳細については、「チャットの操作」を参照してください。

応答の生成

チャットコンテキストでの次の応答をLLMに予測させるには、respond()メソッドを使用できます。

# The `chat` object is created in the previous step.
result = model.respond(chat)

print(result)

推論パラメーターのカスタマイズ

.respond()configキーワードパラメーターを介して、推論パラメーターを渡すことができます。

prediction_stream = model.respond_stream(chat, config={
    "temperature": 0.6,
    "maxTokens": 50,
})

設定可能な内容の詳細については、「モデルの設定」を参照してください。

生成に使用されたモデル、生成されたトークン数、最初のトークンまでの時間、停止理由など、予測のメタデータも表示できます。

# After iterating through the prediction fragments,
# the overall prediction result may be obtained from the stream
result = prediction_stream.result()

print("Model used:", result.model_info.display_name)
print("Predicted tokens:", result.stats.predicted_tokens_count)
print("Time to first token (seconds):", result.stats.time_to_first_token_sec)
print("Stop reason:", result.stats.stop_reason)

例: マルチターンチャット

import lmstudio as lms

model = lms.llm()
chat = lms.Chat("You are a task focused AI assistant")

while True:
    try:
        user_input = input("You (leave blank to exit): ")
    except EOFError:
        print()
        break
    if not user_input:
        break
    chat.add_user_message(user_input)
    prediction_stream = model.respond_stream(
        chat,
        on_message=chat.append,
    )
    print("Bot: ", end="", flush=True)
    for fragment in prediction_stream:
        print(fragment.content, end="", flush=True)
    print()

進捗コールバック

長いプロンプトは、最初のトークンまでの時間が長くなることがよくあります。つまり、モデルがプロンプトを処理するのに時間がかかります。この処理の進捗状況に関する更新を取得したい場合は、プロンプト処理の進捗状況を0.0から1.0の範囲で表すフロート値を受け取るコールバックをrespondに提供できます。

import lmstudio as lms

llm = lms.llm()

response = llm.respond(
    "What is LM Studio?",
    on_prompt_processing_progress = (lambda progress: print(f"{progress*100}% complete")),
)

on_prompt_processing_progressに加えて、利用可能な他の進捗コールバックは以下の通りです。

  • on_first_token: プロンプト処理が完了し、最初のトークンが発行された後に呼び出されます。引数は受け取りません(トークンが発行されるときに処理するには、ストリーミングイテレーションAPIまたはon_prediction_fragmentを使用してください)。
  • on_prediction_fragment: クライアントが受信した各予測フラグメントに対して呼び出されます。ストリームイテレーションAPIを反復処理する場合と同じ予測フラグメントを受け取ります。
  • on_message: 予測が完了したときにアシスタントの応答メッセージとともに呼び出されます。受信したメッセージをチャット履歴インスタンスに追加することを目的としています。