GifproGifpro

動かせ!OllamaローカルLLMをNode.jsから呼ぶ方法

VISTA DE CÓDIGO

P

Prompt

Generate a minimal, functional code example that connects to a locally running Ollama instance using Node.js ESM (fetch / undici). The example should send a chat completion request to the Ollama API (http://localhost:11434/api/chat) with a simple message and log the streaming response. Include error handling for fetch failures.

この例では、ローカルで動作するOllamaインスタンスにNode.js ESMスクリプトから接続する方法を示します。Ollama API(http://localhost:11434/api/chat)にユーザーメッセージを含むチャット完了リクエストを送信し、ストリーミング応答を1行ずつ処理してコンソールに出力します。HTTPエラーやネットワーク障害のハンドリングも含まれています。

前提条件:
– ollama.com からOllamaをインストール
– モデルをダウンロード(例: ollama pull llama3.2)
– Ollamaサービスが起動していること

コードでは、Node.js 18以降で利用可能な組み込みの fetch API と ReadableStream リーダーを使ってストリーミングを処理しています。リクエストボディの stream: true パラメータにより、トークン単位でのストリーミング応答が有効になります。

¿Te resultó útil este prompt?

Comentarios

Los comentarios aparecen después de la moderación

Inicioヘルプ