[ChatStream] Llama2 対応の ChatPrompt実装

[ChatStream] Llama2 対応の ChatPrompt実装

こんにちは! (株)Qualiteg プロダクト開発部 です!

本稿では、 ChatStream にLlama2 対応の ChatPrompt を同梱いたしましたのでご紹介いたします!

現在の ChatPrompt は以下とおりとなっております。旧バージョンのChatStreamをご利用の場合も、以下コードにて Llama2対応可能です。(もちろん最新バージョンのChatStreamには同梱済です)

from chatstream import AbstractChatPrompt
from chatstream.chat_prompt.role_type import RoleType

SYSTEM_PROMPT = """\
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.\
"""


class ChatPromptMetaLlamaLlama2Chat(AbstractChatPrompt):
    """
    meta-llama/Llama-2-7b-chat

    Prompt Guide from
    https://huggingface.co/blog/llama2
    """

    def __init__(self):
        super().__init__()  # Call the initialization of the base class
        self.set_system(f"<s>[INST] <<SYS>>\n{SYSTEM_PROMPT}\n<</SYS>>\n\n")
        self.set_requester("")
        self.set_responder("")

    def get_stop_strs(self):
        if not self.chat_mode:
            return None
        return []

    def get_custom_skip_echo_len(self, skip_echo_len):
        # modify skip_echo_len when using llama2
        num_turn = self.get_turn()
        if num_turn >= 2:
            modified_skip_echo_len = skip_echo_len + 1 * self.get_turn()
            return modified_skip_echo_len
        return skip_echo_len

    def get_replacement_when_input(self):
        return None

    def get_replacement_when_output(self):  # replace when response_text gotten
        return None

    def create_prompt(self, opts={}):
        if self.chat_mode == False:
            return self.get_requester_last_msg()

        # Chat Mode == True の場合のプロンプトを構築する
        ret = self.system

        for chat_content in self.get_contents(opts):

            chat_content_role_type = chat_content.get_role_type()
            chat_content_message = chat_content.get_message()

            if chat_content_message:
                merged_message = ""
                if chat_content_role_type == RoleType.REQUESTER:
                    merged_message = f"{chat_content_message} [/INST] "
                elif chat_content_role_type == RoleType.RESPONDER:
                    merged_message = f"{chat_content_message} </s><s>[INST] "
                ret += merged_message
            else:
                pass

        return ret

    def build_initial_prompt(self, chat_prompt):
        # 初期プロンプトは実装しない
        pass


本実装については、1点だけトリッキーな実装を含んでいます。
というのも、ChatStreamはストリーミングチャットが基本ですので新たに生成された1トークン分を更新していくことでリアルタイムで流れるようなチャットを実現しています。そのため、出力が期待と1文字でもズレてしまうと、ストリーミング時に1文字かけたり、全体が1文字ずつズレてしまったりする現象が発生しやすいです。

Llama2の出力の場合、ターンごとに1文字ずつ出力に空白文字が発生する現象が確認されており、 なにがしかのSpecial Token や空トークン、またコード変換の影響を疑っていましたが根本原因の特定に至らず、現象をキャンセルするための実装を入れています。

現象としましては、

以下のプロンプトを入力プロンプトとしたとき、

<s>[INST] <<SYS>>
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.
<</SYS>>

Do you know the movie titanic [/INST] Hello! Yes, I'm familiar with the movie Titanic. It's a classic film directed by James Cameron, released in 1997, and starring Leonardo DiCaprio and Kate Winslet. The movie is based on the true story of the RMS Titanic, a British passenger liner that sank in the North Atlantic Ocean in 1912 after colliding with an iceberg. The film follows the story of Jack Dawson (played by DiCaprio) and Rose DeWitt Bukater (played by Winslet), who come from </s><s>[INST] Who is the director [/INST] The director of the movie "Titanic" is James Cameron. </s><s>[INST] Who is starred [/INST] ]  The movie "Titanic" features a star-studded cast, including:
* Leonardo DiCaprio as Jack Dawson
* Kate Winslet as Rose DeWitt Bukater
* Billy Zane as Cal Hockley
* Kathy Bates as Molly Brown
* Frances Fisher as Ruth DeWitt Bukater
* Bernard Hill as Captain Edward John Smith
* Jonathan Hyde as J. Bruce Ismay
* Eric Braeden as John Jacob Astor IV
* Gloria Stuart as Old Rose

These actors brought the characters from the movie to life and </s><s>[INST] 

出力は以下のようになります

[INST] <<SYS>>
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.
<</SYS>>

Do you know the movie titanic [/INST] Hello! Yes, I'm familiar with the movie Titanic. It's a classic film directed by James Cameron, released in 1997, and starring Leonardo DiCaprio and Kate Winslet. The movie is based on the true story of the RMS Titanic, a British passenger liner that sank in the North Atlantic Ocean in 1912 after colliding with an iceberg. The film follows the story of Jack Dawson (played by DiCaprio) and Rose DeWitt Bukater (played by Winslet), who come from  [INST] Who is the director [/INST] The director of the movie "Titanic" is James Cameron.  [INST] Who is starred [/INST]

Input:
Do you know the movie titanic [/INST] Hello! Yes, I'm familiar with the movie Titanic. It's a classic film directed by James Cameron, released in 1997, and starring Leonardo DiCaprio and Kate Winslet. The movie is based on the true story of the RMS Titanic, a British passenger liner that sank in the North Atlantic Ocean in 1912 after colliding with an iceberg. The film follows the story of Jack Dawson (played by DiCaprio) and Rose DeWitt Bukater (played by Winslet), who come from [INST] Who is the director [/INST] The director of the movie "Titanic" is James Cameron. [INST] Who is starred [/INST] 

つまり入力プロンプトが [INST] つまり 半角スペース1つ[INST] でも出力で、 [INST]半角スペース2つ + [INST] となって戻ってくるため、新規生成文章の切り出しで1レスポンスにたいして1文字ズレの発生が観測されます。

それならばと、入力プロンプトを 半角スペース2つ[INST] で入力したが、その場合は出力生成文は 半角スペース3つ[INST]
となり、ズレが解消されないようです。

このとき、通常のテキスト処理で trim していく方法もありますが、当ChatPromptではなるべくもとの入力と出力を変形しないことをポリシーとして、

    def get_custom_skip_echo_len(self, skip_echo_len):
        # modify skip_echo_len when using llama2
        num_turn = self.get_turn()
        if num_turn >= 2:
            modified_skip_echo_len = skip_echo_len + 1 * self.get_turn()
            return modified_skip_echo_len
        return skip_echo_len

のように、 skip_echo_len をターンにあわせて調整することでピッタリの切り出しに対応しました。約1000通りの入出力において、問題なく切り出せているため、本手法を workaround として採用しています。ちょっとした見落としの可能性も高そうなので根治のために研究部側で引き続き原因調査しています。

Llama2 をベースモデルとして採用しているほかモデルも同様の現象が発生していますが、本手法にて解決できました。

Read more

日本語対応 LLMランキング2026 ~ベンチマーク分析レポート~(7月10日版)

日本語対応 LLMランキング2026 ~ベンチマーク分析レポート~(7月10日版)

はじめに 本レポートは、Nejumi Leaderboard 4のベンチマークデータ(2026/7/10版)に基づいて、日本語対応LLMの性能を総合的に分析したものです。 前回は 2026/3/6 版の分析レポート を公開しましたが、 約4か月ぶりとなる今回も、上位勢の顔ぶれが大きく入れ替わる激動の回となりました! (定期的に最新LLMランキングを更新してまいります。当社のX(旧Twitter)をフォローいただくことで更新情報を受け取り可能です) Nejumi Leaderboard 4は、日本語タスクにおけるLLMの性能を多角的に評価する信頼性の高いベンチマークとして知られています。汎用的言語性能(GLP)とアラインメント(ALT)の2軸で構成され、翻訳・要約・推論・コーディングから毒性・バイアス・真実性まで、幅広い観点をカバーしているのが特徴です。 本分析では、商用APIモデルとオープンモデルの両方を対象に、それぞれの特徴や傾向を詳しく見ていきます。まず、今回の3大トピックを先にご紹介します。 * Claude Opus 4.8がリーダーボード史上初の総合スコア0.8

By Qualiteg プロダクト開発部
Claude Fable5 完全ガイド — 公式ドキュメントから読み解くモデル仕様とClaude Code運用ポイント

Claude Fable5 完全ガイド — 公式ドキュメントから読み解くモデル仕様とClaude Code運用ポイント

こんにちは! 2026年6月に登場した Claude Fable 5 は、公開直後の輸出規制による一時停止、グローバル再展開、そしてサブスクリプション枠からの離脱と、わずか1か月でめまぐるしい動きを見せています。 当ブログでもその時々の状況を追ってきました。 まず全体像は ついに一般公開、Claude Mythos 5 / Fable 5 を実務視点で読み解く で、公開直後の停止騒動は 公開から3日で停止──Fable 5/Mythos 5 をめぐる米政府指令が示した、AI の新しい可用性リスク で、料金と今後の見通しは Claude Fable 5 はこれからどうなる? 経緯・コスト・今後の見通し で扱っています。 本記事は、それらを踏まえた「実務で使うための決定版ガイド」です。 とくに 2026年7月12日(日本時間7月13日)を境にサブスクリプション枠から外れ、使用クレジットを有効化しないと使えなくなる (この期限は当初2026年7月7日とされていましたが、のちに5日間延長されて7月12日になりました。

By Qualiteg プロダクト開発部
AI時代のデータ漏洩防止の要諦とテクノロジー:第2回 従来型DLPを超えて、AI-DLPが解決すべき本質的課題

AI時代のデータ漏洩防止の要諦とテクノロジー:第2回 従来型DLPを超えて、AI-DLPが解決すべき本質的課題

こんにちは! 前回の記事では、AI時代のデータ漏洩防止における技術的な基礎として、HTTPSインターセプトの仕組みと限界について詳しく解説しました。プロキシサーバーによるSSL/TLS通信の復号化、中間CA証明書の運用、そして証明書ピンニングという技術的制約まで、企業がWeb通信を監視する際の技術的な現実を明らかにしました。 しかし、これらのプロキシ技術は、実は既存のDLP製品でも広く採用されている一般的な手法です。メール監視、ファイル転送の制御、Webアクセスの監査など、従来型のデータ漏洩防止においても、HTTPSインターセプトは中核的な役割を果たしてきました。 では、なぜAI時代において新たにDLPを考え直す必要があるのでしょうか。 前回にひきつづき、従来型DLPでは対応できないAI固有の課題と、AI-DLPとして新たに考慮すべき要素に焦点を当て、より本質的な議論を展開していきます。 1. AI時代が要求する新たなDLP要件 従来のDLP製品は、クレジットカード番号や社会保障番号といった定型的なパターンの検出において優れた実績を持っています。これらの技術は今後も重要な

By Qualiteg プロダクト開発部, Qualiteg コンサルティング
Claude Fable 5はこれからどうなる? 経緯・コスト・今後の見通しをファクトベースで整理する

Claude Fable 5はこれからどうなる? 経緯・コスト・今後の見通しをファクトベースで整理する

こんにちは! 2026年7月2日(日本時間)、日本からもClaude Fable 5が再び利用できるようになりました。 2026年6月に大きな注目を集めて登場し、わずか3日で米政府の指令により停止、そして7月1日(米国時間)に復活したAnthropicの最上位モデル「Claude Fable 5」。 復活と同時に 「サブスクで使えるのは7月7日まで」 という条件が付いたことで、利用者の間ではコストへの懸念の声も見られます。 本記事では、憶測と事実を切り分けながら、 (1)これまでの経緯、 (2)確定している料金体系、 (3)実際のコスト試算、 (4)今後の見通し、 の4点を整理します。確定情報(ファクト)と筆者の推測は明確に区別して書きます。 ※本記事の日付は、特記のない限りAnthropicの発表に基づく米国時間を基準としています。 なお当ブログでは、Fable 5 / Mythos 5についてリリース直後の技術解説、米政府指令による停止が示した可用性リスクの考察、Fable 5の安全分類器がClaude Code上で実際にどう振る舞ったかの体験記を公開してきました。

By Qualiteg コンサルティング