0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

開発しながらついでに英語も学びたい

こちらの記事でローカル LLM をサクッと実装する方法を紹介しました。

これをベースに常に英語と日本語の両方を出力するローカル LLM をつくります。

完成形はこのような形です。

image.png

1. Modelfile でシステムプロンプトを定義する

システムプロンプトをつくることで回答生成時には常に以下の内容を反映できます。

  • 役割・人格設定
  • 制約条件・安全フィルター
  • 出力形式の指定

Ollama では Modelfile というファイルを作成することで カスタマイズされたモデルにすることができます。

Modelfile は慣例的にそのような名前にして使われています

Modelfile というファイルを作成し以下のように記述します。(一応英語にしています。)

Modelfile
# ベースとなるモデルを llama3.1 に設定
FROM llama3.1

# 温度を 0.5 に設定 
PARAMETER temperature 0.5

# 段落ごとの言語構造を持つシステムメッセージを設定
SYSTEM """
Do not adopt any specific persona or character (such as a tutor or helper). Your only task is to respond to the user's input while adhering strictly to the following formatting and language rules.

Translation and Structure Rules:
1. Respond to the user's input in both Japanese and English.
2. Under no circumstances should you output the entire response in Japanese followed by the entire response in English (no "all-Japanese then all-English" format).
3. Instead, divide your response into logical sections or paragraphs. For every single section or paragraph, output the Japanese text first, and then immediately output its corresponding English translation directly underneath it.
4. Keep each paragraph relatively short to make the comparison between Japanese and English clear and easy to follow.
5. Use clear, visual label tags "[日本語]" and "[English]" to separate the language blocks within each paragraph.

Example Output Structure:
[日本語]
ローカルLLMを導入することで、データを完全にオフラインで処理でき、高いセキュリティを確保できます。

[English]
By introducing local LLMs, you can process data completely offline, ensuring high security.

[日本語]
特にOllamaは設定が簡単で、誰でも素早く環境を構築することが可能です。

[English]
In particular, Ollama is easy to configure, allowing anyone to set up the environment quickly.
"""

そして、ollama create でファイルを登録します。この時にディレクトリを指定しますが、今回はapp.pyと同じ階層に入れています。

$ tree .
.
├── Modelfile
└── app.py
ollama create ollama-english-japanese -f ./Modelfile

成功すると success となります。

image.png

2. Python ファイルでカスタムモデルに書き換える

先ほど作成した``を使うように修正します

app.py
response = ollama.chat(
    model="ollama-english-japanese",
    messages=st.session_state.messages,
    stream=True
)

なお、編集前はこちらです。

app.py
response = ollama.chat(
    model="llama3.1",
    messages=st.session_state.messages,
    stream=True
)

3. アプリの起動

試してみます。

streamlit run app.py

日本語で入力しても英語で入力しても、日本語、英語の順で両方の回答を用意してくれました。

image.png

このままだとコード生成もダブってしまうので、Modelfile でルールをつくって回避する必要がありますね。

image.png

参考

システムプロンプトのTips

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?