GifproGifpro

Talk to Local LLM: Ollama + Node.js ESM Integration

CODE PREVIEW

エディタを読み込み中…
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 パラメータにより、トークン単位でのストリーミング応答が有効になります。

Prompt Overview

This example demonstrates how to connect to a locally running Ollama instance from a Node.js ESM script. It sends a chat completion request to the Ollama API (http://localhost:11434/api/chat) with a user message, processes the streaming response line by line, and outputs the generated text to the console. Error handling is included for HTTP and network failures.

Prerequisites:
- Install Ollama from ollama.com
- Pull a model, e.g., ollama pull llama3.2
- Ensure the Ollama service is running

The code uses the built-in fetch API (available in Node.js 18+) and the ReadableStream reader to handle streaming. The stream: true parameter in the request body enables token-by-token streaming.

Was this prompt helpful?

Comments

Comments appear after moderation

この記事が役に立ったら投げ銭で応援

Apple Pay / Google Pay / カード (Visa/Mastercard/JCB/Amex) / Link / Alipay / WeChat Pay 対応 · Stripeで安全に決済

開発者が選ぶ最強ツール集

運営者が毎日使っているツール・ガジェット 6選

見る
Homeヘルプ