Ollama動作確認スクリプト

はい、承知いたしました。
Python 3.11.3を使用し、指定されたOllama環境(モデル名: gemma3-12b
、サーバーIP: 10.200.100.150
、ポート: 11343
)で動作するサンプルプログラムを作成します。
ここでは、Python標準ライブラリに近い requests
ライブラリを使用する方法と、より便利な ollama-python
ライブラリを使用する方法の2つのサンプルを提供します。
requests
ライブラリを使用したサンプル
1. この方法は、外部ライブラリ requests
を使用して直接OllamaのAPIエンドポイントにHTTPリクエストを送信します。
実行前の準備:
requests
ライブラリがインストールされていない場合は、ターミナルまたはコマンドプロンプトで以下のコマンドを実行してインストールしてください。
pip install requests
サンプルコード (requests_example.py):
import requests
import json
# Ollamaサーバーの情報
OLLAMA_HOST = "10.200.100.150"
OLLAMA_PORT = 11343 # 指定されたポート番号
OLLAMA_BASE_URL = f"http://{OLLAMA_HOST}:{OLLAMA_PORT}"
MODEL_NAME = "gemma3-12b" # 指定されたモデル名
# APIエンドポイント
GENERATE_API_URL = f"{OLLAMA_BASE_URL}/api/generate"
def generate_text_with_ollama(prompt: str) -> str | None:
"""
Ollama APIにリクエストを送信し、テキスト生成結果を取得する関数 (ストリームなし)。
Args:
prompt: モデルへの入力プロンプト。
Returns:
生成されたテキスト、またはエラー時にNone。
"""
payload = {
"model": MODEL_NAME,
"prompt": prompt,
"stream": False # ストリームせず、一度に全応答を受け取る
}
headers = {"Content-Type": "application/json"}
try:
# POSTリクエストを送信
response = requests.post(GENERATE_API_URL, headers=headers, json=payload, timeout=60) # タイムアウトを適宜設定
response.raise_for_status() # ステータスコードが200番台以外なら例外を発生させる
# レスポンスをJSONとして解析
response_data = response.json()
# 生成されたテキストを取得
generated_text = response_data.get("response")
if generated_text:
return generated_text.strip()
else:
print("エラー: レスポンスに 'response' キーが含まれていません。")
print("レスポンス内容:", response_data)
return None
except requests.exceptions.ConnectionError as e:
print(f"エラー: Ollamaサーバー ({OLLAMA_BASE_URL}) に接続できませんでした。")
print(f"詳細: {e}")
print("Ollamaサーバーが起動しているか、ネットワーク設定(ファイアウォール等)を確認してください。")
return None
except requests.exceptions.Timeout as e:
print(f"エラー: Ollamaサーバーへのリクエストがタイムアウトしました。")
print(f"詳細: {e}")
return None
except requests.exceptions.RequestException as e:
print(f"エラー: Ollama APIへのリクエスト中にエラーが発生しました。")
print(f"URL: {e.request.url if e.request else 'N/A'}")
if e.response is not None:
print(f"ステータスコード: {e.response.status_code}")
try:
# エラーレスポンスの内容を表示試行
error_content = e.response.json()
print(f"エラー内容: {error_content}")
except json.JSONDecodeError:
print(f"エラーレスポンス (テキスト): {e.response.text}")
else:
print(f"詳細: {e}")
return None
except json.JSONDecodeError as e:
print(f"エラー: Ollama APIからのレスポンスのJSON解析に失敗しました。")
print(f"レスポンス内容: {response.text}")
print(f"詳細: {e}")
return None
if __name__ == "__main__":
# プロンプトの例
user_prompt = "日本の首都はどこですか?簡潔に答えてください。"
print(f"モデル '{MODEL_NAME}' にプロンプトを送信します...")
print(f"プロンプト: {user_prompt}")
print("-" * 30)
# テキスト生成を実行
generated_response = generate_text_with_ollama(user_prompt)
if generated_response:
print("モデルからの応答:")
print(generated_response)
else:
print("テキスト生成に失敗しました。")
ollama-python
ライブラリを使用したサンプル
2. この方法は、Ollama公式(またはコミュニティ)が提供しているPythonクライアントライブラリ ollama-python
を使用します。APIの詳細を意識することなく、より簡単にOllamaと連携できます。
実行前の準備:
ollama-python
ライブラリがインストールされていない場合は、ターミナルまたはコマンドプロンプトで以下のコマンドを実行してインストールしてください。
pip install ollama
サンプルコード (ollama_client_example.py):
import ollama
from ollama import Client, ResponseError, RequestError
# Ollamaサーバーの情報
OLLAMA_HOST = "10.200.100.150"
OLLAMA_PORT = 11343 # 指定されたポート番号
OLLAMA_BASE_URL = f"http://{OLLAMA_HOST}:{OLLAMA_PORT}"
MODEL_NAME = "gemma3-12b" # 指定されたモデル名
def generate_text_with_ollama_client(prompt: str) -> str | None:
"""
ollama-pythonライブラリを使用してテキスト生成を行う関数。
Args:
prompt: モデルへの入力プロンプト。
Returns:
生成されたテキスト、またはエラー時にNone。
"""
try:
# Ollamaクライアントを初期化
# hostパラメータでOllamaサーバーのURLを指定
client = Client(host=OLLAMA_BASE_URL)
# generateメソッドを使用してテキスト生成を実行
# stream=Falseで一度に応答を取得
response = client.generate(model=MODEL_NAME, prompt=prompt, stream=False)
# 応答から生成されたテキストを取得
generated_text = response.get('response')
if generated_text:
return generated_text.strip()
else:
print("エラー: レスポンスに 'response' キーが含まれていません。")
print("レスポンス内容:", response)
return None
except RequestError as e:
# 接続エラーなど、リクエスト自体の問題
print(f"エラー: Ollamaサーバー ({OLLAMA_BASE_URL}) への接続またはリクエスト中にエラーが発生しました。")
print(f"詳細: {e}")
print("Ollamaサーバーが起動しているか、ネットワーク設定(ファイアウォール等)を確認してください。")
return None
except ResponseError as e:
# Ollamaサーバーからのエラー応答 (例: モデルが見つからない)
print(f"エラー: Ollamaサーバーからエラー応答がありました。")
print(f"ステータスコード: {e.status_code}")
print(f"エラー内容: {e.error}")
return None
except Exception as e:
# その他の予期せぬエラー
print(f"予期せぬエラーが発生しました: {e}")
return None
if __name__ == "__main__":
# プロンプトの例
user_prompt = "AIと機械学習の違いを簡単に説明してください。"
print(f"モデル '{MODEL_NAME}' にプロンプトを送信します...")
print(f"プロンプト: {user_prompt}")
print("-" * 30)
# テキスト生成を実行
generated_response = generate_text_with_ollama_client(user_prompt)
if generated_response:
print("モデルからの応答:")
print(generated_response)
else:
print("テキスト生成に失敗しました。")
共通の注意点
-
Ollamaサーバーの起動: これらのスクリプトを実行する前に、指定したIPアドレス (
10.200.100.150
) とポート (11343
) でOllamaサーバーが起動しており、gemma3-12b
モデルが利用可能になっていることを確認してください。 -
ネットワーク接続: スクリプトを実行するマシンからOllamaサーバー (
10.200.100.150:11343
) へのネットワーク接続が可能であることを確認してください。ファイアウォールなどが通信をブロックしていないか確認が必要な場合があります。 -
モデル名: 指定されたモデル名
gemma3-12b
がOllamaサーバー上で正確に登録されている必要があります。ollama list
コマンドなどで確認してください。 - エラーハンドリング: 上記のサンプルコードには基本的なエラーハンドリングが含まれていますが、実際のアプリケーションでは、より詳細なエラー処理やリトライロジックを実装することを検討してください。
- Pythonバージョン: これらのコードはPython 3.11.3で動作するように書かれていますが、Python 3.8以降であれば問題なく動作するはずです。
どちらのサンプルも基本的な動作は同じですが、ollama-python
ライブラリを使用する方が、コードが簡潔になり、Ollamaの機能をより活用しやすくなるため、一般的には推奨されます。開発環境の要件に合わせて選択してください。

Okay, certainly. Here are the English versions of the sample Python programs for interacting with your Ollama setup.
requests
library
1. Sample using the This method uses the external requests
library to directly send HTTP requests to the Ollama API endpoint.
Prerequisites:
If you don't have the requests
library installed, run the following command in your terminal or command prompt:
pip install requests
Sample Code (requests_example_en.py):
import requests
import json
# Ollama Server Information
OLLAMA_HOST = "10.200.100.150"
OLLAMA_PORT = 11343 # Your specified port number
OLLAMA_BASE_URL = f"http://{OLLAMA_HOST}:{OLLAMA_PORT}"
MODEL_NAME = "gemma3-12b" # Your specified model name
# API Endpoint
GENERATE_API_URL = f"{OLLAMA_BASE_URL}/api/generate"
def generate_text_with_ollama(prompt: str) -> str | None:
"""
Sends a request to the Ollama API and retrieves the generated text (no streaming).
Args:
prompt: The input prompt for the model.
Returns:
The generated text, or None if an error occurs.
"""
payload = {
"model": MODEL_NAME,
"prompt": prompt,
"stream": False # Get the full response at once
}
headers = {"Content-Type": "application/json"}
try:
# Send POST request
# Set a reasonable timeout (in seconds)
response = requests.post(GENERATE_API_URL, headers=headers, json=payload, timeout=60)
response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
# Parse the JSON response
response_data = response.json()
# Get the generated text
generated_text = response_data.get("response")
if generated_text:
return generated_text.strip()
else:
print("Error: 'response' key not found in the response.")
print("Response content:", response_data)
return None
except requests.exceptions.ConnectionError as e:
print(f"Error: Could not connect to the Ollama server ({OLLAMA_BASE_URL}).")
print(f"Details: {e}")
print("Please ensure the Ollama server is running and check network settings (firewall, etc.).")
return None
except requests.exceptions.Timeout as e:
print(f"Error: Request to the Ollama server timed out.")
print(f"Details: {e}")
return None
except requests.exceptions.RequestException as e:
print(f"Error: An error occurred during the request to the Ollama API.")
print(f"URL: {e.request.url if e.request else 'N/A'}")
if e.response is not None:
print(f"Status Code: {e.response.status_code}")
try:
# Attempt to print the error content from the response
error_content = e.response.json()
print(f"Error Content: {error_content}")
except json.JSONDecodeError:
print(f"Error Response (text): {e.response.text}")
else:
print(f"Details: {e}")
return None
except json.JSONDecodeError as e:
print(f"Error: Failed to parse JSON response from the Ollama API.")
print(f"Response content: {response.text}")
print(f"Details: {e}")
return None
if __name__ == "__main__":
# Example prompt
user_prompt = "What is the capital of France? Answer concisely."
print(f"Sending prompt to model '{MODEL_NAME}'...")
print(f"Prompt: {user_prompt}")
print("-" * 30)
# Execute text generation
generated_response = generate_text_with_ollama(user_prompt)
if generated_response:
print("Response from model:")
print(generated_response)
else:
print("Failed to generate text.")
ollama-python
library
2. Sample using the This method uses the official (or community-provided) Python client library ollama-python
, which simplifies interaction with the Ollama API.
Prerequisites:
If you don't have the ollama-python
library installed, run the following command in your terminal or command prompt:
pip install ollama
Sample Code (ollama_client_example_en.py):
import ollama
from ollama import Client, ResponseError, RequestError
# Ollama Server Information
OLLAMA_HOST = "10.200.100.150"
OLLAMA_PORT = 11343 # Your specified port number
OLLAMA_BASE_URL = f"http://{OLLAMA_HOST}:{OLLAMA_PORT}"
MODEL_NAME = "gemma3-12b" # Your specified model name
def generate_text_with_ollama_client(prompt: str) -> str | None:
"""
Generates text using the ollama-python library.
Args:
prompt: The input prompt for the model.
Returns:
The generated text, or None if an error occurs.
"""
try:
# Initialize the Ollama client
# Specify the Ollama server URL using the 'host' parameter
client = Client(host=OLLAMA_BASE_URL)
# Use the generate method for text generation
# stream=False gets the entire response at once
response = client.generate(model=MODEL_NAME, prompt=prompt, stream=False)
# Extract the generated text from the response dictionary
generated_text = response.get('response')
if generated_text:
return generated_text.strip()
else:
print("Error: 'response' key not found in the response.")
print("Response content:", response)
return None
except RequestError as e:
# Handles connection errors, request issues, etc.
print(f"Error: Could not connect or send request to the Ollama server ({OLLAMA_BASE_URL}).")
print(f"Details: {e}")
print("Please ensure the Ollama server is running and check network settings (firewall, etc.).")
return None
except ResponseError as e:
# Handles error responses from the Ollama server (e.g., model not found)
print(f"Error: Received an error response from the Ollama server.")
print(f"Status Code: {e.status_code}")
print(f"Error Content: {e.error}")
return None
except Exception as e:
# Catches other unexpected errors
print(f"An unexpected error occurred: {e}")
return None
if __name__ == "__main__":
# Example prompt
user_prompt = "Briefly explain the difference between AI and machine learning."
print(f"Sending prompt to model '{MODEL_NAME}'...")
print(f"Prompt: {user_prompt}")
print("-" * 30)
# Execute text generation
generated_response = generate_text_with_ollama_client(user_prompt)
if generated_response:
print("Response from model:")
print(generated_response)
else:
print("Failed to generate text.")
Common Notes
-
Ollama Server Running: Before running these scripts, ensure your Ollama server is running at the specified IP address (
10.200.100.150
) and port (11343
), and that thegemma3-12b
model is available. -
Network Connectivity: Verify that the machine running the script can reach the Ollama server (
10.200.100.150:11343
) over the network. Check for any firewalls or network configurations that might block the connection. -
Model Name: The model name
gemma3-12b
must exactly match the name registered on your Ollama server. You can usually check available models with a command likeollama list
. - Error Handling: The sample code includes basic error handling. For production applications, consider implementing more robust error checking, logging, and potentially retry mechanisms.
- Python Version: These scripts are written for Python 3.11.3 but should work fine with Python 3.8 and newer.
Both samples achieve the same basic goal. Using the ollama-python
library is generally recommended as it provides a cleaner interface and abstracts away the direct HTTP request details. Choose the one that best fits your development environment and preferences.

LangChainを使用したサンプル (日本語版)
実行前の準備:
LangChain関連のライブラリがインストールされていない場合は、ターミナルまたはコマンドプロンプトで以下のコマンドを実行してインストールしてください。
pip install langchain langchain-community # または新しい推奨パッケージ `langchain-ollama` を使う場合: pip install langchain langchain-ollama
注: langchain-community
または新しい langchain-ollama
のどちらかに Ollama 連携クラスが含まれます。ここではより一般的な langchain-community
を使いますが、最新のLangChainドキュメントに従って langchain-ollama
を使うことも推奨されます。コード例は langchain_community
を使用します。もし langchain-ollama
を使う場合は from langchain_ollama import Ollama
のように変更してください。
サンプルコード (langchain_example_jp.py):
# langchain_communityを使用する場合
from langchain_community.llms import Ollama
# langchain_ollamaを使用する場合 (推奨される場合あり):
# from langchain_ollama import Ollama
# Ollamaサーバーの情報
OLLAMA_HOST = "10.200.100.150"
OLLAMA_PORT = 11343 # 指定されたポート番号
OLLAMA_BASE_URL = f"http://{OLLAMA_HOST}:{OLLAMA_PORT}"
MODEL_NAME = "gemma3-12b" # 指定されたモデル名
def generate_text_with_langchain(prompt: str) -> str | None:
"""
LangChainを使用してOllamaでテキスト生成を行う関数。
Args:
prompt: モデルへの入力プロンプト。
Returns:
生成されたテキスト、またはエラー時にNone。
"""
try:
# Ollamaクラスのインスタンスを作成
# base_url でOllamaサーバーのURLを指定
# model で使用するモデル名を指定
llm = Ollama(base_url=OLLAMA_BASE_URL, model=MODEL_NAME)
print(f"LangChain経由でモデル '{MODEL_NAME}' にプロンプトを送信します...")
print(f"プロンプト: {prompt}")
print("-" * 30)
# invokeメソッドでテキスト生成を実行
response = llm.invoke(prompt)
return response.strip()
except Exception as e:
# LangChainは内部でエラーをラップすることがあるため、汎用的なExceptionで捕捉
print(f"エラー: LangChain経由でのOllama呼び出し中にエラーが発生しました。")
print(f"詳細: {e}")
print(f"Ollamaサーバー ({OLLAMA_BASE_URL}) が起動しており、モデル '{MODEL_NAME}' が利用可能か確認してください。")
print("ネットワーク接続やライブラリのバージョンも確認してください。")
return None
if __name__ == "__main__":
# プロンプトの例
user_prompt = "LangChainとは何ですか?簡単に説明してください。"
# テキスト生成を実行
generated_response = generate_text_with_langchain(user_prompt)
if generated_response:
print("モデルからの応答:")
print(generated_response)
else:
print("テキスト生成に失敗しました。")
LangChain Sample (English Version)
Prerequisites:
If you haven't installed the necessary LangChain libraries, run the following command in your terminal or command prompt:
pip install langchain langchain-community # Or, if using the newer recommended package: pip install langchain langchain-ollama
Note: The Ollama integration class is usually in langchain-community
or the newer langchain-ollama
. This example uses langchain_community
. If you opt for langchain-ollama
, change the import statement accordingly (e.g., from langchain_ollama import Ollama
).
Sample Code (langchain_example_en.py):
# Using langchain_community
from langchain_community.llms import Ollama
# Using langchain_ollama (if preferred/recommended):
# from langchain_ollama import Ollama
# Ollama Server Information
OLLAMA_HOST = "10.200.100.150"
OLLAMA_PORT = 11343 # Your specified port number
OLLAMA_BASE_URL = f"http://{OLLAMA_HOST}:{OLLAMA_PORT}"
MODEL_NAME = "gemma3-12b" # Your specified model name
def generate_text_with_langchain(prompt: str) -> str | None:
"""
Generates text using Ollama via LangChain.
Args:
prompt: The input prompt for the model.
Returns:
The generated text, or None if an error occurs.
"""
try:
# Instantiate the Ollama class from LangChain
# Specify the Ollama server URL with 'base_url'
# Specify the model name with 'model'
llm = Ollama(base_url=OLLAMA_BASE_URL, model=MODEL_NAME)
print(f"Sending prompt to model '{MODEL_NAME}' via LangChain...")
print(f"Prompt: {prompt}")
print("-" * 30)
# Use the invoke method for text generation
response = llm.invoke(prompt)
return response.strip()
except Exception as e:
# Catching a general Exception as LangChain might wrap specific errors
print(f"Error: An error occurred during the Ollama call via LangChain.")
print(f"Details: {e}")
print(f"Please ensure the Ollama server ({OLLAMA_BASE_URL}) is running and the model '{MODEL_NAME}' is available.")
print("Also check network connectivity and library versions.")
return None
if __name__ == "__main__":
# Example prompt
user_prompt = "What is LangChain? Explain briefly."
# Execute text generation
generated_response = generate_text_with_langchain(user_prompt)
if generated_response:
print("Response from model:")
print(generated_response)
else:
print("Failed to generate text.")
LangChainを使用する利点
-
抽象化: Ollama APIの直接的な呼び出しを意識せず、統一されたインターフェース (
invoke
など) でLLMを操作できます。 - 連携: LangChainの他のコンポーネント(プロンプトテンプレート、アウトプットパーサー、メモリ、エージェントなど)と簡単に組み合わせることができます。
- エコシステム: LangChainがサポートする他の多くのツールやデータソースとの連携が容易になります。
基本的なテキスト生成だけであれば requests
や ollama-python
でも十分ですが、より複雑なアプリケーションを構築する場合はLangChainの利用が非常に効果的です。