2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Llamaを使います。

Llamaでこのようなローカルアプリをつくっていきます。
image.png

1. Ollama のインストール

今回は Powershell を使います。

こちらに書いてあるコマンドを実行すれば OK です。

image.png

他の OS はこちらから

image.png

ダウンロード中...
image.png

2. モデルをダウンロード

Ollama が使えるようになったところで Llama を pull します。

モデルは 3.1 を指定しました。

ollama pull llama3.1

もしくは

ollama run llama3.1

スクリーンショット 2026-07-06 183824.png

image.png

モデルは他にも色々あるのでお好きなものを選んでください。

image.png

3. 必要な Python ライブラリのインストール

Python環境に、Web画面を構築するための Streamlitと、Ollama公式のライブラリをインストールします。

pip install streamlit ollama

3. サンプルコードの作成

任意の名前のファイル(ここでは app.py )を作成し、以下の Python コードを記述します。

app.py
import streamlit as st
import ollama

# 画面のタイトルを設定
st.title("ローカルLLM チャットアプリ")
# チャット履歴を保持するセッションの初期化
if "messages" not in st.session_state:
    st.session_state.messages = []
    
# 過去のチャット履歴を画面に表示
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])
        
# ユーザーからの入力があるか確認
if prompt := st.chat_input("Llama 3.1 に質問を入力してください"):

    # ユーザーの入力を画面に表示し、履歴に追加
    with st.chat_message("user"):
        st.markdown(prompt)
    st.session_state.messages.append({"role": "user", "content": prompt})

    # AIの回答を生成して表示
    with st.chat_message("assistant"):
        message_placeholder = st.empty()
        full_response = ""
        
        # Ollamaからストリーミング(逐次)形式で回答を取得
        response = ollama.chat(
            model="llama3.1",
            messages=st.session_state.messages,
            stream=True
        )
        
        for chunk in response:
            full_response += chunk['message']['content']
            message_placeholder.markdown(full_response + "")
            
        message_placeholder.markdown(full_response)
    
    # AIの回答を履歴に追加
    st.session_state.messages.append({"role": "assistant", "content": full_response})

4. アプリの起動

コマンドで streamlit を実行します。

streamlit run app.py

実自動的にブラウザが立ち上がり、http://localhost:8501 でチャットアプリが起動します。

image.png

ひとまず実装完了

会話を続けていくと日本語がほんの少し不自然だったり、当然実行環境によっては遅延が発生することもあります。
特に CPU 環境では軽量なモデルでもタイピングしているように文字が少しずつ出力されてきます。

ここからさらに「システムプロンプトを固定する」「RAGを組み込む」などをして自分の業務に合わせたモデルをつくることができます。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?