はじめに
モバイルPCでOllamaを動かした記録です。
windowsで作業をしています。
インストール
ollamaをインストールします。
scoopというwindowsで使用可能な管理ツールでインストールします。
scoop install ollam
インストーラからだとGUIが使えます
https://ollama.com/download/windows
実行
qwen3.5という日本語に強いらしいモデルを使用します。
https://ollama.com/library/qwen3.5
他のモデルを使用したい場合は以下のリンクから検索ができます。
起動
CUIから
ollama runで指定したモデルが起動します。
ローカルに指定したモデルがなければ自動的にインストールしてくれます。
今回は容量が6.6GBで、普通のPCで使えると思われるqwen3.5:4bを使用します。
ollama run qwen3.5:4b
上記のコマンド実施後はチャット形式で会話が始まります。
APIから
CUIから呼び出したので次はAPIから呼び出しましょう。
curlを使用すると以下のように呼び出せます。
time curl http://localhost:11434/api/chat -d '{"model": "qwen3:0.6b","messages": [{ "role": "user", "content": "Hello!" }]}'
ストリーム形式で実行したい場合は以下のようにパラメータを指定してください。
curl http://localhost:11434/api/chat -d '{"model": "qwen3:0.6b","messages": [{ "role": "user", "content": "Hello!" }],"stream": true}'
もしollamaの実行がされていないなら応答は返ってこないので以下のコマンドで起動しましょう。
ollama serve
プログラムから
pythonからollamaの呼び出しを行います。
ライブラリ管理ツールのuvを使用するのであらかじめuvをインストールしておきます。
scoop install uv
ライブラリインストール
uv init
uv add openai
openai_ollam
from openai import OpenAI
client = OpenAI(
api_key="",
base_url="http://localhost:11434/v1"
)
response = client.chat.completions.create(
model="qwen3:8b",
messages=[{"role":"user","content":"こんにちは"}],
temperature=0
)
print(response)
print(response.choices[0].message.content)
Ollama公式ライブラリだとさらに簡素な実装となります。
uv add ollama
ollama_lib.py
import ollama
response = ollama.chat(
model="qwen3:8b",
messages=[{"role": "user", "content": "LLMについて"}]
)
print(response.message.content)
最後にページから情報を取ってきて、要約を行ったり、ブログの情報に基づいて回答を行うプログラムを実行しましょう。
ますhtto通信を行うためのライブラリインストールしましょう
uv add requests
以下がページを取得して、LLMに読み込ませ、ページの要約をし、質問を受け付けるプログラムです。
import sys
import requests
import json
from html.parser import HTMLParser
OLLAMA_URL = "http://127.0.0.1:11434/api/chat"
class ArticleTextExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.text_parts = []
self._skip_tags = {"script", "style", "nav", "header", "footer"}
self._current_skip = 0
def handle_starttag(self, tag, attrs):
if tag in self._skip_tags:
self._current_skip += 1
def handle_endtag(self, tag):
if tag in self._skip_tags and self._current_skip > 0:
self._current_skip -= 1
def handle_data(self, data):
if self._current_skip == 0:
text = data.strip()
if text:
self.text_parts.append(text)
def get_text(self):
return "\n".join(self.text_parts)
def fetch_article(url: str) -> str:
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
parser = ArticleTextExtractor()
parser.feed(response.text)
return parser.get_text()
def chat(messages: list) -> str:
payload = {
"model": "qwen3:0.6b",
"messages": messages,
"stream": True,
}
reply = []
with requests.post(OLLAMA_URL, json=payload, stream=True) as r:
for line in r.iter_lines(decode_unicode=True):
if not line:
continue
try:
data = json.loads(line)
if "message" in data and "content" in data["message"]:
chunk = data["message"]["content"]
print(chunk, end="", flush=True)
reply.append(chunk)
except json.JSONDecodeError:
continue
print()
return "".join(reply)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("使い方: python summarize_article.py <URL>")
sys.exit(1)
url = sys.argv[1]
print(f"記事を取得中: {url}")
article_text = fetch_article(url)
print(f"取得完了 ({len(article_text)}文字)\n")
messages = [
{
"role": "system",
"content": f"あなたは記事についての質問に答えるアシスタントです。以下の記事を参照して回答してください。\n\n{article_text}",
},
{
"role": "user",
"content": "この記事を日本語で簡潔に要約してください。 /no_think",
},
]
print("=== 要約 ===")
summary = chat(messages)
messages.append({"role": "assistant", "content": summary})
print("\n(終了するには 'q' または 'quit' を入力)\n")
while True:
try:
user_input = input("質問: ").strip()
except (EOFError, KeyboardInterrupt):
print("\n終了します")
break
if not user_input:
continue
if user_input.lower() in ("q", "quit"):
print("終了します")
break
messages.append({"role": "user", "content": user_input + " /no_think"})
print("回答: ", end="", flush=True)
reply = chat(messages)
messages.append({"role": "assistant", "content": reply})
print()
使用方法
python main.py <記事のURL>
以上で、CLI、API、プログラムからのLLMの簡単な使用した記録となります。