0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

OpenClaw Qwen3.5 think モード無効化

0
Posted at

OpenClaw + ollama-proxy.py:役割と2026.3.28アップデート対応

はじめに

OpenClawでローカルLLM(ollama)をエージェントのバックエンドとして使う場合、OpenClawとollamaの間に薄いHTTPプロキシを挟む構成が有効です。この記事では、そのプロキシ(ollama-proxy.py)の目的・役割・設計と、OpenClaw 2026.3.28アップデートで発生したインシデントおよびその対応を記録します。


ollama-proxy.pyとは

ollama-proxy.py は、OpenClawとollamaサーバーの間に立つ薄いHTTPプロキシです。外部ライブラリを一切使わず、Pythonの標準ライブラリのみで実装されています。

OpenClaw gateway
    ↓ POST /v1/chat/completions  または  POST /api/chat
ollama-proxy.py(127.0.0.1:11436 など)
    ↓ POST /api/chat
ollama server(192.168.0.x:11434)

主な役割

1. think モードの無効化

Qwen3.5 など推論モデルは think: true がデフォルトで、<think>...</think> タグ内に内部思考を出力します。エージェントの応答としてそのまま返すと、長い思考ブロックがユーザーに届いてしまいます。プロキシは think: false をリクエストに注入することでこれを無効化します。

2. <think> タグおよび内部独白の除去(clean_response())

モデルによってはthinkを無効にしても思考断片が漏れることがあります。プロキシはレスポンスを後処理し、残留する <think>...</think> ブロック、独立した (内部独白) 形式の段落を除去します。

3. ストリームの制御

ollamaのNDJSON形式とOpenClawのSSE形式(text/event-stream)の変換を担います。OpenClawは openai-completions プロバイダに対して stream: true でリクエストを送りますが、プロキシ内部では stream: false でollamaから一括取得し、後処理後にSSEとして返します。

4. toolsフィールドの除去

tool calling非対応モデル(RIN:latest、gemma3:、llama3.1:)に tools フィールドが含まれるとollamaが400エラーを返します。プロキシはモデルIDで判定し、非対応モデルへのリクエストから tools を除去します。

5. DIRECT_HINTの注入

キャラクターエージェント向けに、思考・前置き・ト書きを出力しないようシステムプロンプトへ指示を追記します。


設計

標準ライブラリの http.server.HTTPServer + urllib.request のみで実装。依存関係ゼロ、launchdとの相性も良く、Mac mini上で安定して動作します。

2ポートで起動し、それぞれ異なるollamaサーバーを向けます:

ai.openclaw.ollama-proxy-m4pro  : 127.0.0.1:11436 → 192.168.0.27:11434 (M4Pro)
ai.openclaw.ollama-proxy-geekom : 127.0.0.1:11437 → 192.168.0.3:11434  (Geekom)

2026.3.28アップデートで発生したインシデントと対応

問題1:api: ollama プロバイダの廃止

現象: アップデート後、Kei・Rin・Tokioが以下のエラーで起動不能になりました。

No API provider registered for api: ollama

原因: OpenClaw 2026.3.28で register-builtins.js から api: ollama プロバイダが削除されました(GitHub #57099/#57811)。openclaw.json の設定が旧形式のまま残っていたことが原因です。

修正: openclaw.json の該当プロバイダを以下のように変更します。

// 変更前
"ollama-m4pro": {
  "baseUrl": "http://127.0.0.1:11436",
  "api": "ollama"
}

// 変更後
"ollama-m4pro": {
  "baseUrl": "http://127.0.0.1:11436/v1",
  "api": "openai-completions"
}

ollama-rin も同様に変更します(port 11437)。

変更後、各エージェントの models.json を削除して再生成させます。

rm ~/.openclaw/agents/*/agent/models.json

問題2:/v1/chat/completions のSSE非対応によるサイレント失敗(最重要)

現象: openclaw.jsonを修正してエージェントが起動するようになったにもかかわらず、Telegramに応答が届かない。typing... は表示されるが出力なし。

診断の難しさ: エラーログが一切出ず、セッションファイルを直接確認するまで原因を特定できませんでした。

セッションファイル(~/.openclaw/agents/kei/sessions/*.jsonl)を確認すると:

{
  "role": "assistant",
  "content": [],
  "usage": {"input": 0, "output": 0, "totalTokens": 0}
}

LLMが空のレスポンスを返しているように見えましたが、proxyに直接curlすると正常に応答していました。

根本原因: OpenClawは openai-completions プロバイダに対して stream: true でリクエストを送ります。プロキシはこのリクエストを受け取り /api/chat から一括取得していましたが、レスポンスを通常のJSONで返していました。OpenClawはSSE形式(text/event-stream)を期待しているため、レスポンスをパースできず content: [] として記録していました。

プロキシのデバッグログを追加して初めて stream=True であることが判明しました:

[ollama-proxy] v1/chat/completions: model=qwen3.5:35b-a3b stream=True msgs=9

修正: stream: true の場合にSSE形式で返すよう対応します。

修正1:ollama_to_openai() の usageフィールド

# 変更前
"usage": data.get("usage", {}),

# 変更後
"usage": {
    "prompt_tokens": data.get("prompt_eval_count", 0),
    "completion_tokens": data.get("eval_count", 0),
    "total_tokens": (data.get("prompt_eval_count", 0) + data.get("eval_count", 0)),
},

修正2:/v1/chat/completions ルートのSSE対応

do_POST の /v1/chat/completions 処理部分を以下のように変更します。

def do_POST(self):
    raw = self._read_body()

    if self.path == "/v1/chat/completions":
        try:
            payload = json.loads(raw)
        except Exception as e:
            self.send_error(400, f"invalid json: {e}")
            return
        # デバッグログ(stream値の確認に重要)
        log(f"v1/chat/completions: model={payload.get('model')} "
            f"stream={payload.get('stream')} "
            f"msgs={len(payload.get('messages', []))}")

        parsed = openai_to_ollama(payload)

        # tool calling非対応モデルからtoolsを除去
        model_id = parsed.get("model", "")
        if any(m in model_id for m in ("RIN:", "gemma3:", "llama3.1:")):
            parsed.pop("tools", None)

        # DIRECT_HINTをsystemメッセージに注入
        injected = False
        for msg in parsed["messages"]:
            if msg.get("role") == "system":
                msg["content"] = msg.get("content", "") + DIRECT_HINT
                injected = True
                break
        if not injected:
            parsed["messages"].insert(0, {"role": "system", "content": DIRECT_HINT.strip()})

        body = json.dumps(parsed).encode("utf-8")
        req = urllib.request.Request(
            f"{UPSTREAM}/api/chat", data=body, method="POST",
            headers=self._build_req_headers(len(body))
        )
        try:
            resp = urllib.request.urlopen(req, timeout=300)
            data = json.loads(resp.read().decode("utf-8", errors="replace").strip())
            model = payload.get("model", "")
            completion = ollama_to_openai(data, model)
            is_stream = payload.get("stream", False)

            if is_stream:
                # SSE形式で返す
                content = completion["choices"][0]["message"]["content"]
                chunk = {
                    "id": completion["id"],
                    "object": "chat.completion.chunk",
                    "created": int(datetime.now().timestamp()),
                    "model": model,
                    "choices": [{"index": 0, "delta": {"role": "assistant", "content": content}, "finish_reason": None}],
                }
                done_chunk = {
                    "id": completion["id"],
                    "object": "chat.completion.chunk",
                    "created": int(datetime.now().timestamp()),
                    "model": model,
                    "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
                }
                sse = (
                    "data: " + json.dumps(chunk, ensure_ascii=False) + "\n\n" +
                    "data: " + json.dumps(done_chunk, ensure_ascii=False) + "\n\n" +
                    "data: [DONE]\n\n"
                ).encode("utf-8")
                self.send_response(200)
                self.send_header("Content-Type", "text/event-stream")
                self.send_header("Cache-Control", "no-cache")
                self.send_header("Content-Length", str(len(sse)))
                self.end_headers()
                self.wfile.write(sse)
                self.wfile.flush()
                log(f"v1/chat/completions SSE: model={model} chars={len(content)}")
            else:
                out = json.dumps(completion, ensure_ascii=False).encode("utf-8")
                self.send_response(200)
                self.send_header("Content-Type", "application/json")
                self.send_header("Content-Length", str(len(out)))
                self.end_headers()
                self.wfile.write(out)
            return
        except Exception as e:
            log(f"v1/chat/completions error: {e}")
            self.send_error(502, str(e))
            return

content: [] が返る場合のデバッグ手順

  1. セッションファイルを確認
tail -3 ~/.openclaw/agents/{エージェント名}/sessions/*.jsonl | \
  python3 -c "import sys,json; [print(json.loads(l).get('message',{}).get('content','')) for l in sys.stdin if l.strip()]"
  1. proxyのログを確認
tail -f /tmp/openclaw/ollama-proxy-m4pro.log
  1. curlでSSE形式を確認
curl -s http://127.0.0.1:11436/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer ollama-local" \
  -d '{"model":"qwen3.5:9b","messages":[{"role":"user","content":"hi"}],"stream":true}'
# 期待される出力:
# data: {"object":"chat.completion.chunk",...}
# data: {"object":"chat.completion.chunk","choices":[{"finish_reason":"stop"}]}
# data: [DONE]

まとめ

問題 原因 対応
No API provider registered for api: ollama openclaw.jsonのapi: ollamaが廃止 openai-completions + baseUrl/v1 に変更
content: [] サイレント失敗 proxy が SSE 非対応 stream=True 時に SSE 形式で返すよう修正
Rin HTTP 400 /v1ルートにtools除去がなかった モデル判定によるtools除去を追加

最重要の教訓: OpenClawは openai-completions プロバイダに stream: true でリクエストを送ります。proxy が非SSEで返すと content: [] という無音の失敗が発生し、診断に時間がかかります。proxyのデバッグログ(stream= の値を含む)は常時有効にしておくことを強く推奨します。


環境

  • OpenClaw: 2026.3.28
  • Python: 3.9 (CommandLineTools)
  • ollama: Mac mini M4Pro 64GB RAM (192.168.0.27) / Geekom A8 MAX 32GB RAM (192.168.0.3)
  • macOS: Mac mini 2020
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?