Open Responses APIを使う

2025年3月、OpenAIは新しい responses APIを公開した。これに基づいて、2026年1月に Open Responses というオープンなAPI規格が作られた。LM Studio もさっそくこれに対応した(Open Responses with local models via LM Studio)。

ここではこれを使ってLM StudioをPythonから操作し、さらにLM StudioのOpen Responses APIに実装されたlogprobsの仕組みを使ってLLMの回答の確信度を調べる方法を解説する。

まずはLM Studioをインストールし、適当なモデルをダウンロードする。ここでは qwen/qwen3-vl-32b-instruct を例として使う。Pythonのパッケージとして openai を使う。

from openai import OpenAI

client = OpenAI(base_url="http://localhost:1234/v1")
response = client.responses.create(
    model="qwen/qwen3-vl-32b-instruct",
    input="Tell me the secret of life in one word (without `**` or `*`).",
)
print(response.output[0].content[0].text)

やってみたところ、“Love” という1語が返された。追加で質問してみよう。追加の質問には次のように previous_response_id=response.id のオプションを付ける。

response = client.responses.create(
    model="qwen/qwen3-vl-32b-instruct",
    previous_response_id=response.id,
    input="Why?"
)
print(response.output[0].content[0].text)

“Because love connects, heals, inspires, ...” といった解答が出力された。さらに何回でも追加の質問をつなげることができる。もちろん日本語にも対応しているので、日本語で質問してもよい。

さて、ここでわざわざ1語で答えてもらったのは、その確信度を調べたかったためである。確信度を出力するには、最初の質問を次のようにする。

import numpy as np
from openai import OpenAI

client = OpenAI(base_url="http://localhost:1234/v1")
response = client.responses.create(
    model="qwen/qwen3-vl-32b-instruct",
    input="Tell me the secret of life in one word (without `**` or `*`).",
    include=["message.output_text.logprobs"],
    top_logprobs=3  # 上位3個まで出力
)
print(response.output[0].content[0].text)

for x in response.output[0].content[0].logprobs[:5]:
    print(repr(x.token))
    for y in x.top_logprobs:
        print(f"  {np.exp(y.logprob):7.5f} {repr(y.token)}")
Love
'Love'
  0.96847 'Love'
  0.00990 'Peace'
  0.00895 'Joy'

Loveが約97%、PeaceやJoyは1%未満である。