サイトアイコン アマチュア無線局JS2IIU

【Streamlit】LangChainでClaude 3.5 Haikuを使ったチャットアプリ

こんにちは、JS2IIUです。

近年、OpenAIのChatGPTをはじめとする大規模言語モデルが注目を集めています。そんな中、AnthropicはAIの安全性と研究に焦点を当てた企業として、独自の強力な言語モデルClaudeを提供しています。

Anthropicは、Googleと提携し、倫理的で責任あるAI開発を重視しています。Claudeは、ChatGPTと同様に、テキスト生成、翻訳、質疑応答など、様々なタスクに優れた能力を発揮します。

Anthropicの特徴

Not Found - Claude Docs
Page not found

ClaudeのAPI呼び出し方法

PythonでClaudeのAPIを呼び出すには、anthropicライブラリを使用します。事前にAnthropicのWEBサイトでAPI KEYを入手しておきましょう。

Home \ Anthropic
Anthropic is an AI safety and research company that's working to build reliable, interpretable, and steerable AI systems.
Python
import anthropic

client = anthropic.Client("YOUR_API_KEY")
response = client.completions.create(
    model="claude-2",
    prompt="こんにちは!",
)

print(response.completion)

StreamlitでClaudeを使ったチャットシステムを構築

では、StreamlitとLangChainを使って、Claudeと対話できるチャットシステムを構築してみましょう。コードの下に、実際に動作している時のスクリーンショットを載せています。

コード

Python
import streamlit as st
from langchain_anthropic import ChatAnthropic
from langchain.schema import HumanMessage, AIMessage, SystemMessage

# Anthropicクライアントを生成
chat = ChatAnthropic(
    model="claude-3-5-haiku-20241022",  # 適切なClaudeモデル名を指定してください
    temperature=0.7,
    streaming=True,
    anthropic_api_key="YOUR_KEY_HERE"  # ここにあなたのAPIキーを入力してください
)

# title
st.subheader('Chat with Anthropic claude-3-5-haiku-20241022')

# セッションステートを初期化
if "messages" not in st.session_state:
    st.session_state.messages = [SystemMessage(content="You are a helpful assistant.")]

# メッセージ履歴を表示
for message in st.session_state.messages:
    if isinstance(message, HumanMessage):
        with st.chat_message("user"):
            st.markdown(message.content)
    elif isinstance(message, AIMessage):
        with st.chat_message("assistant"):
            st.markdown(message.content)

# ユーザーからの入力を受け取る
if prompt := st.chat_input("What is up?"):
    # ユーザーのメッセージを履歴に追加
    user_message = HumanMessage(content=prompt)
    st.session_state.messages.append(user_message)

    # チャットメッセージとして表示
    with st.chat_message("user"):
        st.markdown(prompt)

    # Anthropic APIを使ってAIからの応答をストリーミングで生成
    with st.chat_message("assistant"):
        full_response = ""
        placeholder = st.empty()  # プレースホルダーを作成
        for chunk in chat.stream(st.session_state.messages):
            content = chunk.content
            if content:
                full_response += content
                placeholder.markdown(full_response + "")  # 途中経過を表示
        placeholder.markdown(full_response)  # 最終的な応答を表示

    # AIのメッセージを履歴に追加
    ai_message = AIMessage(content=full_response)
    st.session_state.messages.append(ai_message)
https://js2iiu.com/wp-content/uploads/2025/01/anthropic_01.mov

コードの説明

このコードは、Streamlitアプリケーションを使用して、Anthropic APIを介してAIモデル(Claude-3.5)とリアルタイムにチャットする機能を提供します。

1. 必要なライブラリのインポート

Python
import streamlit as st
from langchain_anthropic import ChatAnthropic
from langchain.schema import HumanMessage, AIMessage, SystemMessage

2. Anthropicクライアントの生成

Python
chat = ChatAnthropic(
    model="claude-3-5-haiku-20241022",
    temperature=0.7,
    streaming=True,
    anthropic_api_key="YOUR_KEY_HERE"
)
Not Found - Claude Docs
Page not found

3. アプリケーションのヘッダー

Python
st.subheader('Chat with Anthropic claude-3-5-haiku-20241022')

Streamlitのsubheader関数を使い、アプリケーションのヘッダーを表示します。

4. セッションステートの初期化

Python
if "messages" not in st.session_state:
    st.session_state.messages = [SystemMessage(content="You are a helpful assistant.")]

5. メッセージ履歴の表示

Python
for message in st.session_state.messages:
    if isinstance(message, HumanMessage):
        with st.chat_message("user"):
            st.markdown(message.content)
    elif isinstance(message, AIMessage):
        with st.chat_message("assistant"):
            st.markdown(message.content)

6. ユーザー入力の受け取り

Python
if prompt := st.chat_input("What is up?"):
    user_message = HumanMessage(content=prompt)
    st.session_state.messages.append(user_message)

    with st.chat_message("user"):
        st.markdown(prompt)

7. Anthropic APIでの応答生成

Python
with st.chat_message("assistant"):
    full_response = ""
    placeholder = st.empty()
    for chunk in chat.stream(st.session_state.messages):
        content = chunk.content
        if content:
            full_response += content
            placeholder.markdown(full_response + "")
    placeholder.markdown(full_response)

8. AIメッセージの履歴への追加

Python
ai_message = AIMessage(content=full_response)
st.session_state.messages.append(ai_message)

生成されたAIの応答をAIMessageとして作成し、セッションステートに追加します。

まとめ

このコードは、以下の主要な機能を実現しています:

  1. Anthropic社のAIモデルを利用したチャットシステムの構築。
  2. Streamlitを使ったリアルタイムチャットUIの実装。
  3. ユーザー入力とAI応答をセッションステートで管理し、履歴を保持。

注意点:

実行時エラー

以下のエラーはapi-keyを入手したものの、APIのクレジットを購入していない、もしくは月額プランに登録していないときに返ってくるエラーです。最低$5のクレジットを入れないとAPIが使えないので注意が必要です。

Plaintext
anthropic.BadRequestError: Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error', 'message': 'Your credit balance is too low to access the Anthropic API. Please go to Plans & Billing to upgrade or purchase credits.'}}

以下のエラーはAPI KEYの設定ミスをしている場合に返ってくるエラーです。本当はお勧めできないのですが、今回のサンプルコード、10行目に正しくapi-keyを設定して下さい。可能なら環境変数に設定して下さい。

Plaintext
TypeError: "Could not resolve authentication method. Expected either api_key or auth_token to be set. Or for one of the `X-Api-Key` or `Authorization` headers to be explicitly omitted"

参考リンク

同様に、OpenAIのgpt-o4やGoogleのGeminiを使ったアプリの構築についてはこちらの記事を参照して下さい。

最後に、書籍のPRです。

最新のOpenAIのチャットAPIの使い方もしっかりと解説されている良書です。2024年11月初版発行、「LangChainとLangGraphによるRAG・AIエージェント[実践]入門」西見、吉田、大嶋著。

最後まで読んでいただきありがとうございます。73

モバイルバージョンを終了