From 095813b08e0e1ae8993b8d48c07c6d94e8aeed37 Mon Sep 17 00:00:00 2001 From: ktro2828 Date: Wed, 2 Jul 2025 06:11:57 +0900 Subject: [PATCH 1/3] feat: add translation ja unit0 Signed-off-by: ktro2828 --- units/ja/_toctree.yml | 12 ++ units/ja/communication/live1.mdx | 7 ++ units/ja/unit0/discord101.mdx | 52 +++++++++ units/ja/unit0/introduction.mdx | 187 +++++++++++++++++++++++++++++++ units/ja/unit0/onboarding.mdx | 97 ++++++++++++++++ 5 files changed, 355 insertions(+) create mode 100644 units/ja/_toctree.yml create mode 100644 units/ja/communication/live1.mdx create mode 100644 units/ja/unit0/discord101.mdx create mode 100644 units/ja/unit0/introduction.mdx create mode 100644 units/ja/unit0/onboarding.mdx diff --git a/units/ja/_toctree.yml b/units/ja/_toctree.yml new file mode 100644 index 00000000..cd812985 --- /dev/null +++ b/units/ja/_toctree.yml @@ -0,0 +1,12 @@ +- title: Unit 0. Welcome to the course + sections: + - local: unit0/introduction + title: Welcome to the course 🤗 + - local: unit0/onboarding + title: Onboarding + - local: unit0/discord101 + title: (Optional) Discord 101 +- title: Live 1. How the course works and Q&A + sections: + - local: communication/live1 + title: Live 1. How the course works and Q&A diff --git a/units/ja/communication/live1.mdx b/units/ja/communication/live1.mdx new file mode 100644 index 00000000..6a5a183a --- /dev/null +++ b/units/ja/communication/live1.mdx @@ -0,0 +1,7 @@ +# Live 1: コースの仕組みと最初のQ&A + +Agentsコースの最初のライブストリームでは、コースの**仕組み**(範囲、ユニット、チャレンジなど)について説明し、あなたの質問に答えました。 + + + +次のライブセッションのスケジュールを知りたい場合は、**Discordサーバー**をチェックしてください。また、メールでもお知らせします。参加できない場合でも心配しないでください。すべてのライブセッションを**録画**しています。 diff --git a/units/ja/unit0/discord101.mdx b/units/ja/unit0/discord101.mdx new file mode 100644 index 00000000..59c0518e --- /dev/null +++ b/units/ja/unit0/discord101.mdx @@ -0,0 +1,52 @@ +# (Optional) Discord 101 [[discord-101]] + +The Discord Etiquette + +このガイドは、ゲームや機械学習コミュニティで人気のある無料チャットプラットフォーム、Discordを始めるためのものです。 + +Hugging FaceコミュニティのDiscordサーバーには、**10万人以上のメンバー**がいます。以下のリンクをクリックして参加してください!他の人とつながる素晴らしい場所です! + +## AgentsコースをHugging FaceのDiscordコミュニティで + +Discordを始めるのは少し圧倒されるかもしれませんが、ナビゲートを手助けするための簡単なガイドを用意しました。 + + + +HFコミュニティサーバーは、さまざまな分野に興味を持つ活気あるコミュニティをホストしており、論文の議論、イベントなどを通じて学ぶ機会を提供しています。 + +[サインアップ](http://hf.co/join/discord)したら、`#introduce-yourself`チャンネルで自己紹介をしてください。 + +私たちは、Agentsコースのために4つのチャンネルを作成しました: + +- `agents-course-announcements`: **最新のコース情報**を確認するためのチャンネル +- `🎓-agents-course-general`: **一般的な議論や雑談**のためのチャンネル +- `agents-course-questions`: **質問をしたり、メンバーを助けたり**するためのチャンネル +- `agents-course-showcase`: **自分のエージェントを公開する**ためのチャンネル + +さらに、以下のチャンネルもチェックできます: + +- `smolagents`: **ライブラリに関する議論やサポート**を受けるためのチャンネル。 + +## Discordを効果的に使うためのヒント + +### サーバーに参加する方法 + +Discordにあまり慣れていない場合は、サーバーに参加する方法についてのガイドを確認することをお勧めします。 + +以下は手順の簡単な概要です: + +1. 招待リンクをクリックします。 +2. Discordアカウントでサインインするか、アカウントを作成します。 +3. AIエージェントではないことを確認します。 +4. ニックネームとアバターを設定します。 +5. "サーバーに参加"をクリックします。 + +### Discordを効果的に使うためのヒント + +Discordを効果的に使うためのいくつかのヒントを紹介します: + +- **ボイスチャンネル**も利用可能ですが、テキストチャットがより一般的に使用されます。 +- **マークダウンスタイル**を使用してテキストをフォーマットできます。これは特にコードを書く際に便利です。ただし、マークダウンはリンクにはあまり適していません。 +- **長い会話**を整理するためにスレッドを開くことを検討してください。 + +このガイドが役に立つことを願っています!質問がある場合は、Discordでお気軽にお尋ねください🤗。 diff --git a/units/ja/unit0/introduction.mdx b/units/ja/unit0/introduction.mdx new file mode 100644 index 00000000..48798824 --- /dev/null +++ b/units/ja/unit0/introduction.mdx @@ -0,0 +1,187 @@ +# 🤗 AI Agents Courseへようこそ [[introduction]] + +
+AI Agents Course thumbnail +
背景画像はScenario.comによって作成されました
+
+ + +昨今のAIで最もエキサイティングなトピック、**エージェント**へようこそ! + +この無料コースでは、AIエージェントを理解し、使用し、構築するための旅に、**初心者から専門家まで**お連れします。 + +この最初のユニットでは、オンボーディングを手助けします: + +- **コースのシラバス**を確認する。 +- 自己監査または認定プロセスのいずれか、**進むべき道を選択する**。 +- **認定プロセスについての詳細情報を取得する**。 +- コースの背後にいるチームを知る。 +- **Hugging Faceアカウント**を作成する。 +- **Discordサーバーにサインアップ**し、クラスメートや私たちと出会いましょう。 + +さあ、始めましょう! + +## このコースで学べること [[expect]] + +このコースでは、以下のことを学びます: + +- 📖 AIエージェントの**理論、設計、実践**を学ぶ。 +- 🧑‍💻 [smolagents](https://huggingface.co/docs/smolagents/en/index)、[LlamaIndex](https://www.llamaindex.ai/)、[LangGraph](https://langchain-ai.github.io/langgraph/)などの**確立されたAIエージェントライブラリを使用する**方法を学ぶ。 +- 💾 **自分のエージェントを共有する**ためにHugging Face Hubを利用し、コミュニティが作成したエージェントを探索する。 +- 🏆 他の学生のエージェントと**自分のエージェントを評価する**チャレンジに参加する。 +- 🎓 課題を完了することで**修了証明書を取得する**。 + +さらには! + +このコースの終わりには、**エージェントの仕組みと最新のライブラリやツールを使用して自分のエージェントを構築する方法**を理解できるようになります。 + +**こちらにサインアップすることもお忘れなく!** + + +(私たちはあなたのプライバシーを尊重します。**各ユニットが公開されるときにリンクを送信し、課題や更新に関する情報を提供できるように、あなたのメールアドレスを収集します**)。 + +## コースの内容について [[course-look-like]] + +コースは以下で構成されています: + +- *基礎ユニット*: エージェントの**理論**を学ぶ場所です。 +- *Hands-on*: エージェントをユニークな環境でトレーニングするための**確立されたAIエージェントライブラリを使用する**方法を学ぶ場所です。これらのハンズオンセクションは、**Hugging Face Spaces**で事前に構成された環境を使用します。 +- *ユースケース課題*: 学んだ概念を適用して、自分が選んだ実世界の問題を解決する場所です。 +- *チャレンジ*: 自分のエージェントを他のエージェントと競わせることができる場所です。また、エージェントのパフォーマンスを比較するための[リーダーボード](https://huggingface.co/spaces/agents-course/Students_leaderboard)も用意されています。 + +この**コースはあなたのフィードバックや貢献に応じて進化する生きたプロジェクトです!** [GitHubで問題やPRをオープンする](https://github.com/huggingface/agents-course)ことや、Discordサーバーでの議論に参加することを自由に行ってください。 + +コースを修了した後は、[👉 このフォームを使用して](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog)フィードバックを送信することもできます。 + +## コースのシラバスについて [[syllabus]] + +こちらが**コースの一般的なシラバス**です。各ユニットとともに、より詳細なトピックリストが公開されます。 + +| チャプター | トピック | 説明 | +| :---- | :---- | :---- | +| 0 | オンボーディング | 使用するツールやプラットフォームのセットアップを行います。 | +| 1 | エージェント基礎 | ツール、思考、行動、観察、およびその形式について説明します。LLM、メッセージ、特殊トークン、チャットテンプレートについて説明します。ツールとしてPython関数を使用した簡単なユースケースを示します。 | +| 2 | フレームワーク | 基礎がどのように人気のあるライブラリ(smolagents、LangGraph、LLamaIndex)に実装されているかを理解します。 | +| 3 | ユースケース | 実際のユースケースを構築します(経験豊富なエージェントビルダーからのPRを歓迎します🤗)。 | +| 4 | 最終課題 | 選択したベンチマーク用のエージェントを構築し、学生リーダーボードでエージェントの理解を証明します🚀。 | + +メインのシラバスに加えて、3つのボーナスユニットがあります: +- *ボーナスユニット1*: 関数呼び出しのためにLLMを微調整する +- *ボーナスユニット2*: エージェントの可観測性と評価 +- *ボーナスユニット3*: ポケモンを使用したゲーム内エージェント + +例えば、ボーナスユニット3では、ポケモンバトルをプレイするためのエージェントを構築する方法を学びます🥊。 + +## 必要な事前知識について + +このコースを受講するには、以下の知識が必要です。 + +- Pythonの基本的な知識 +- LLMの基本的な知識(ユニット1に要約セクションがあります) + +## 必要なツールについて [[tools]] + +必要なものは2つだけです。 + +- *インターネット接続のあるコンピュータ* +- *Hugging Faceアカウント*: モデル、エージェントをプッシュおよびロードし、Spacesを作成するために必要です。まだアカウントをお持ちでない場合は、**[こちら](https://hf.co/join)**から作成できます(無料です)。 +Course tools needed + +## 認定プロセス [[certification-process]] + +Two paths + +このコースを*監査モード*で受講するか、アクティビティを実施して*発行される2つの証明書のいずれかを取得する*ことができます。 + +コースを監査する場合は、すべての課題に参加し、必要に応じて課題を実施できます。また、**通知する必要はありません**。 + +認定プロセスは**完全に無料**です。 + +- *基礎の認定を取得するには*: コースのユニット1を完了する必要があります。これは、エージェントの最新のトレンドを把握したい学生を対象としています。 +- *修了証明書を取得するには*: ユニット1、コース中に提案されるユースケース課題の1つ、および最終チャレンジを完了する必要があります。 + +認定プロセスに**締切はありません**。 + +## コースの推奨学習ペース [[recommended-pace]] + +このコースの各章は、**1週間で完了することを想定しており、週に約3〜4時間の作業が必要です**。 + +推奨ペースを以下に示します: + +Recommended Pace + +## コースを最大限に活用するには? [[advice]] + +このコースを最大限に活用するためのアドバイスがあります。 + +1. Discordで勉強グループに参加する: グループで学ぶことは常に簡単です。そのためには、私たちのDiscordサーバーに参加し、Hugging Faceアカウントを確認する必要があります。 +2. **クイズや課題を実施する**: 学ぶ最良の方法は、実践と自己評価を通じてです。 +3. **スケジュールを定義して同期を保つ**: 推奨ペースのスケジュールを使用するか、自分自身のスケジュールを作成できます。 + +Course advice + +## 私たちについて [[who-are-we]] + +私たちについて: + +### Joffrey Thomas + +JoffreyはHugging Faceの機械学習エンジニアで、AIエージェントをプロダクション環境で構築および展開しています。Joffreyはこのコースの主なインストラクターです。 + +- [Follow Joffrey on Hugging Face](https://huggingface.co/Jofthomas) +- [Follow Joffrey on X](https://x.com/Jthmas404) +- [Follow Joffrey on Linkedin](https://www.linkedin.com/in/joffrey-thomas/) + +### Ben Burtenshaw + +BenはHugging Faceの機械学習エンジニアで、さまざまなプラットフォームで複数のコースを提供しています。Benの目標は、すべての人がコースにアクセスできるようにすることです。 + +- [Follow Ben on Hugging Face](https://huggingface.co/burtenshaw) +- [Follow Ben on X](https://x.com/ben_burtenshaw) +- [Follow Ben on Linkedin](https://www.linkedin.com/in/ben-burtenshaw/) + +### Thomas Simonini + +ThomasはHugging Faceの機械学習エンジニアで、AIエージェントの分野に情熱を注いでいます。彼はDeep RLおよびML for gamesコースを提供しました。Thomasはエージェントの大ファンであり、コミュニティが何を構築するのかを見るのを楽しみにしています。 + +- [Follow Thomas on Hugging Face](https://huggingface.co/ThomasSimonini) +- [Follow Thomas on X](https://x.com/ThomasSimonini) +- [Follow Thomas on Linkedin](https://www.linkedin.com/in/simoninithomas/) + + +### Sergio Paniego + +SergioはHugging Faceの機械学習エンジニアです。彼はユニット2、3、4、およびボーナスユニットのいくつかのセクションに貢献しました。 + +- [Follow Sergio on Hugging Face](https://huggingface.co/sergiopaniego) +- [Follow Sergio on X](https://x.com/sergiopaniego) +- [Follow Sergio on Linkedin](https://www.linkedin.com/in/sergio-paniego-blanco/) + +## 謝辞 + +私たちは、このコースへの貴重な貢献に対して以下の個人に感謝の意を表したいと思います。 + +- **[Pedro Cuenca](https://huggingface.co/pcuenq)** - 材料のレビューにおける彼の指導と専門知識に感謝します。 +- **[Aymeric Roucher](https://huggingface.co/m-ric)** - 彼の素晴らしいデモスペース(デコーディングと最終エージェント)や、smolagentsパーツへの彼の助けに感謝します。 +- **[Joshua Lochner](https://huggingface.co/Xenova)** - トークン化に関する彼の素晴らしいデモスペースに感謝します。 +- **[Quentin Gallouédec](https://huggingface.co/qgallouedec)** - コースコンテンツに関する彼の助けに感謝します。 +- **[David Berenstein](https://huggingface.co/davidberenstein1957)** - コースコンテンツとモデレーションに関する彼の助けに感謝します。 +- **[XiaXiao (ShawnSiao)](https://huggingface.co/SSSSSSSiao)** - コースの中国語翻訳者。 +- **[Jiaming Huang](https://huggingface.co/nordicsushi)** - コースの中国語翻訳者。 + +## バグを見つけた、またはコースを改善したい場合 [[contribute]] + +コントリビューションは**大歓迎**です 🤗 + +- *ノートブック内でバグ🐛を見つけた場合*は、issueを開いて問題を説明してください。 +- *コースを改善したい場合*は、Pull Requestを開いてください。 +- *新しいセクションやユニットを追加したい場合*は、issueを開いて、書き始める前に追加したいコンテンツを説明してください。そうすれば、私たちがガイドできます。 + +## 他に質問がある場合 [[questions]] + +もしまだ質問がある場合は、私たちのDiscordサーバーの#agents-course-questionsチャンネルで質問してください。私たちのコミュニティメンバーやコースチームが喜んでお手伝いします。 + +以上がコースの概要です。それでは、オンボードに進みましょう!⛵: + +Time to Onboard + diff --git a/units/ja/unit0/onboarding.mdx b/units/ja/unit0/onboarding.mdx new file mode 100644 index 00000000..9491ce1e --- /dev/null +++ b/units/ja/unit0/onboarding.mdx @@ -0,0 +1,97 @@ +# オンボーディング: はじめの一歩 ⛵ + +Time to Onboard + +それでは始めましょう!私達は4つのことを行います: +1. **Hugging Faceアカウントを作成** (まだ作成していない場合) +2. **Discordにサインアップして自己紹介をする** (恥ずかしがらずに 🤗) +3. **Hugging Face Agents CourseをHubでフォローする** +4. **コースについて広める** + +### ステップ1: Hugging Faceアカウントを作成 + +(まだ作成していない場合) Hugging Faceアカウントをこちらで作成してください。 + +### ステップ2: Discordコミュニティに参加 + +👉🏻 我々のDiscordサーバーに参加するには、こちらをクリックしてください。 + +参加したら、`#introduce-yourself`チャンネルで自己紹介をすることを忘れないでください。 + +AIエージェント関連の複数のチャンネルがあります: +- `agents-course-announcements`: **最新のコース情報**用。 +- `🎓-agents-course-general`: **一般的な議論や雑談**用。 +- `agents-course-questions`: **質問をしたり、クラスメートを助けたり**するためのもの。 +- `agents-course-showcase`: **自分のエージェントを披露する**ためのもの。 + +さらに、以下もチェックできます: + +- `smolagents`: **ライブラリに関する議論やサポート**用。 + +初めてDiscordを使用する場合は、最良のプラクティスを得るためにDiscord 101を作成しました。[次のセクション](discord101)を確認してください。 + +### ステップ3: Hugging Face Agents Courseをフォローする + +最新のコース資料、アップデート、およびアナウンスメントを受け取るには、**Hugging Face Agents Course Organizationをフォローしてください**。 + +👉 [こちら](https://huggingface.co/agents-course)をクリックして、**フォロー**をクリックしてください。 + +Follow + +### ステップ4: コースについて広める + +このコースをより目立たせるために、あなたの助けが必要です!あなたができることは2つあります。 + +1. ⭐ コースのリポジトリをスターしてサポートを示してください。 + +Repo star + +2. 学習の旅を共有する: 他の人に**このコースを受講していることを知らせてください**!ソーシャルメディアの投稿に使用できるイラストを用意しました。 + + + + +クリックすることで画像をダウンロードできます。 👉 [こちら](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/share.png?download=true) + +### ステップ5: Ollamaを使用してローカルでモデルを実行する (クレジット制限に達した場合) + +1. **Ollamaをインストールする** + + 公式の手順に従ってこちらからインストールしてください。 + +2. **ローカルでモデルをプルする** +``` bash + ollama pull qwen2:7b #Check out ollama website for more models +``` +3. **Ollamaをバックグラウンドで起動する (1つのターミナルで)** +``` bash + ollama serve +``` + もし "listen tcp 127.0.0.1:11434: bind: address already in use" というエラーが発生した場合は、`sudo lsof -i :11434` コマンドを使用して、現在このポートを使用しているプロセスID (PID) を特定できます。もしプロセスが `ollama` であれば、上記のインストールスクリプトがollamaサービスを開始している可能性があるため、このコマンドをスキップしてOllamaを起動できます。 + +4. **`InferenceClientModel`の代わりに`LiteLLMModel`を使用する** + + `smolagents`で`LiteLLMModel`モジュールを使用するには、`pip`コマンドを実行してモジュールをインストールします。 + +``` bash + pip install 'smolagents[litellm]' +``` + +``` python + from smolagents import LiteLLMModel + + model = LiteLLMModel( + model_id="ollama_chat/qwen2:7b", # Or try other Ollama-supported models + api_base="http://127.0.0.1:11434", # Default Ollama local server + num_ctx=8192, + ) +``` + +5. **なぜこれが機能するのか?** +- OllamaはOpenAI互換のAPIを使用してローカルでモデルを提供します。`http://localhost:11434`でアクセスできます。 +- `LiteLLMModel`は、OpenAIのチャット/補完API形式をサポートする任意のモデルと通信するように構築されています。 +- これは、`InferenceClientModel`を`LiteLLMModel`に単純に置き換えることができ、他のコード変更は必要ありません。シームレスでプラグアンドプレイのソリューションです。 + +おめでとうございます!🎉 **オンボーディングプロセスを完了しました**!これでAIエージェントについて学ぶ準備が整いました。楽しんでください! + +学習を続けましょう!継続は力なりです 🤗 From 38893444e57357e2b2262f63b63d4e029fef5765 Mon Sep 17 00:00:00 2001 From: ktro2828 Date: Wed, 2 Jul 2025 08:22:13 +0900 Subject: [PATCH 2/3] ci: add ja to github workflows Signed-off-by: ktro2828 --- .github/workflows/build_documentation.yml | 2 +- .github/workflows/build_pr_documentation.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build_documentation.yml b/.github/workflows/build_documentation.yml index 5ea564c5..19e73716 100644 --- a/.github/workflows/build_documentation.yml +++ b/.github/workflows/build_documentation.yml @@ -14,6 +14,6 @@ jobs: package_name: agents-course path_to_docs: agents-course/units/ additional_args: --not_python_module - languages: en zh-CN ru-RU vi es ko + languages: en zh-CN ru-RU vi es ko ja secrets: hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} diff --git a/.github/workflows/build_pr_documentation.yml b/.github/workflows/build_pr_documentation.yml index a8523d7d..8eea44db 100644 --- a/.github/workflows/build_pr_documentation.yml +++ b/.github/workflows/build_pr_documentation.yml @@ -17,4 +17,4 @@ jobs: package_name: agents-course path_to_docs: agents-course/units/ additional_args: --not_python_module - languages: en zh-CN ru-RU vi es ko + languages: en zh-CN ru-RU vi es ko ja From 3699708312abb338d0bf7ebdce43e12318b37dab Mon Sep 17 00:00:00 2001 From: ktro2828 Date: Mon, 7 Jul 2025 22:33:02 +0900 Subject: [PATCH 3/3] TODO: add japanese version for unit1 Signed-off-by: ktro2828 --- units/ja/_toctree.yml | 32 ++ units/ja/unit1/README.md | 19 + units/ja/unit1/actions.mdx | 130 +++++++ units/ja/unit1/agent-steps-and-structure.mdx | 150 ++++++++ units/ja/unit1/conclusion.mdx | 19 + units/ja/unit1/dummy-agent-library.mdx | 343 ++++++++++++++++++ units/ja/unit1/final-quiz.mdx | 34 ++ units/ja/unit1/introduction.mdx | 40 ++ .../ja/unit1/messages-and-special-tokens.mdx | 229 ++++++++++++ units/ja/unit1/observations.mdx | 44 +++ units/ja/unit1/quiz1.mdx | 165 +++++++++ units/ja/unit1/quiz2.mdx | 119 ++++++ units/ja/unit1/thoughts.mdx | 56 +++ units/ja/unit1/tools.mdx | 321 ++++++++++++++++ units/ja/unit1/tutorial.mdx | 244 +++++++++++++ units/ja/unit1/what-are-agents.mdx | 159 ++++++++ units/ja/unit1/what-are-llms.mdx | 222 ++++++++++++ 17 files changed, 2326 insertions(+) create mode 100644 units/ja/unit1/README.md create mode 100644 units/ja/unit1/actions.mdx create mode 100644 units/ja/unit1/agent-steps-and-structure.mdx create mode 100644 units/ja/unit1/conclusion.mdx create mode 100644 units/ja/unit1/dummy-agent-library.mdx create mode 100644 units/ja/unit1/final-quiz.mdx create mode 100644 units/ja/unit1/introduction.mdx create mode 100644 units/ja/unit1/messages-and-special-tokens.mdx create mode 100644 units/ja/unit1/observations.mdx create mode 100644 units/ja/unit1/quiz1.mdx create mode 100644 units/ja/unit1/quiz2.mdx create mode 100644 units/ja/unit1/thoughts.mdx create mode 100644 units/ja/unit1/tools.mdx create mode 100644 units/ja/unit1/tutorial.mdx create mode 100644 units/ja/unit1/what-are-agents.mdx create mode 100644 units/ja/unit1/what-are-llms.mdx diff --git a/units/ja/_toctree.yml b/units/ja/_toctree.yml index cd812985..3b0714fe 100644 --- a/units/ja/_toctree.yml +++ b/units/ja/_toctree.yml @@ -10,3 +10,35 @@ sections: - local: communication/live1 title: Live 1. How the course works and Q&A +- title: Unit 1. Introduction to Agents + sections: + - local: unit1/introduction + title: Introduction + - local: unit1/what-are-agents + title: What is an Agent? + - local: unit1/quiz1 + title: Quick Quiz 1 + - local: unit1/what-are-llms + title: What are LLMs? + - local: unit1/messages-and-special-tokens + title: Messages and Special Tokens + - local: unit1/tools + title: What are Tools? + - local: unit1/quiz2 + title: Quick Quiz 2 + - local: unit1/agent-steps-and-structure + title: Understanding AI Agents through the Thought-Action-Observation Cycle + - local: unit1/thoughts + title: Thought, Internal Reasoning and the Re-Act Approach + - local: unit1/actions + title: Actions, Enabling the Agent to Engage with Its Environment + - local: unit1/observations + title: Observe, Integrating Feedback to Reflect and Adapt + - local: unit1/dummy-agent-library + title: Dummy Agent Library + - local: unit1/tutorial + title: Let’s Create Our First Agent Using smolagents + - local: unit1/final-quiz + title: Unit 1 Final Quiz + - local: unit1/conclusion + title: Conclusion diff --git a/units/ja/unit1/README.md b/units/ja/unit1/README.md new file mode 100644 index 00000000..70e289b5 --- /dev/null +++ b/units/ja/unit1/README.md @@ -0,0 +1,19 @@ +# Table of Contents + +👉 こちらからUnit 1 にアクセスできます + + diff --git a/units/ja/unit1/actions.mdx b/units/ja/unit1/actions.mdx new file mode 100644 index 00000000..1449f492 --- /dev/null +++ b/units/ja/unit1/actions.mdx @@ -0,0 +1,130 @@ +# Actions: Enabling the Agent to Engage with Its Environment + + + このセクションでは、エージェントが環境と相互作用するための具体的な方法ステップについて探索します。 + + アクションがどのように表現されるか(JSONやコードを使用)、ストップ&パース手法の重要性、そして様々な種類のエージェントを紹介します。 + + +アクションとは**AIエージェントが環境と相互作用するための**具体的なステップです。 + +ウェブを閲覧して情報を得ようが、物理的なデバイスを操作しようが、それぞれのアクションはエージェントによって意図的に実行される操作です。 + +例えば、カスタマーサービスを支援するエージェントは顧客データを検索したり、サポート記事を提供したり、問題を人間の担当者に転送するかもしれません。 + +## エージェントアクションの種類 + +エージェントには複数の種類があり、それぞれ異なるアクションをとります: + +| エージェントの種類 | 説明 | +|------------------------|--------------------------------------------------------------------------------------------------| +| JSON エージェント | 実行されるアクションはJSON形式で指定されます。 | +| Code エージェント | エージェントは外部から解釈されるコードブロックを書きます。 | +| 関数呼び出しエージェント | これはJSONエージェントのサブカテゴリで、アクションごとに新しいメッセージを生成するようにファインチューニングされます。 | + +アクション自体は多くの目的を果たすことができます: + +| アクションの種類 | 説明 | +|--------------------------|------------------------------------------------------------------------------------------| +| 情報収集 | ウェブ検索、データベースのクエリ化、またはドキュメントの取得。 | +| ツールの使い方 | APIの呼び出し、計算の実行、コードの実行。 | +| 環境との相互作用 | デジタルインターフェースの操作や物理デバイスの制御。 +| コミュニケーション | チャットや他のエージェントとの共同作業を通じてユーザーと関わる。 | + +LLMはテキストのみを取り扱い実行したいアクションやツールに与えるパラメータを記述するためにテキストを使います。エージェントが適切に動作するためには、LLMは完全なアクションを定義するためにすべてのトークンを出力した後、新しいトークンの生成を停止しなければなりません。これにより、LLMからエージェントに制御が戻り、意図された形式がJSONであれ、コードであれ、関数呼び出しであれ、結果が解析可能であることが保証されます。 + +## ストップ&パース手法 (Stop and Parse Approach) + +アクションを実装するための重要な手法が**ストップ&パース**です。この手法がエージェントの出力が構造化され予測可能であることを保証します: + +1. **構造化された形式での生成**: + +エージェントは意図されたアクションを明確な所定の形式(JSONまたはコード)で出力します。 + +2. **さらなる生成の停止** + +アクションを定義するテキストが出力されると、**LLMは追加のトークン生成を停止します**。これにより、余分な出力や誤った出力を防ぐことができます。 + +3. **出力の解析** + +外部のパーサーが形式されたアクションを読み込み、どのツールを呼び出すが決定し、必要なパラメータを抽出します。 + +例えば、天気を調べるエージェントは以下を出力するでしょう: + +```json +Thought: I need to check the current weather for New York. +Action : +{ + "action": "get_weather", + "action_input": {"location": "New York"} +} +``` + +フレームワークは呼び出す関数名と適用する引数を簡単に解析できます。 + +この明確で機械が読める形式は、誤りを最小化し外部ツールが正確にエージェントのコマンドを実行することを可能にします。 + +注: 関数呼び出しエージェントは、指定された関数が正しい引数で呼び出されるようにアクションを構造化することで同様に動作します。 + +## コードエージェント + +他のアプローチは*コードエージェント*を使用することです。 +The idea is: **instead of outputting a simple JSON object**, a Code Agent generates an **executable code block—typically in a high-level language like Python**. +このアイデアは: **シンプルなJSON形式を出力する代わりに**、コードエージェントが**実行可能なコードブロック(通常はPythonのような高級言語による)**を生成します。 + +Code Agents + +この方法にはいくつかの利点があります: + +- **表現力:** コードはループ、条件分岐、ネスト関数などの複雑なロジックを自然に表現することができ、JSONよりも柔軟が高いです。 +- **モジュール性と再利用性:** 生成されたコードは異なるアクションやタスクをまたいで再利用できる関数やモジュールを含むことができます。 +- **デバッグ機能の強化:** プログラムの構文がきちんと定義されていれば、コードのエラーを発見しやすく、修正しやすくなります。 +- **直接統合:** コードエージェントは外部ライブラリやAPIと直接統合することができ、データ処理やリアルタイム意思決定などのより複雑な処理を可能にします。 + +LLMによって生成されたコードを実行すると、プロンプト・インジェクションから有害なコードの実行に至るまで、セキュリティリスクが生じる可能性があることに留意しなければなりません。 +そのため、デフォルトのセーフガードを統合した`smolagents`のようなAIエージェントフレームワークを使うことが推奨されています。 +リスクとその軽減方法について詳しく知りたい場合は、[こちらの専用セクションをご覧ください](https://huggingface.co/docs/smolagents/tutorials/secure_code_execution)。 + +例えば、現在の天気の取得をタスクとするコードエージェントは、次のようなPythonスニペットを生成するかもしれません: + +```python +# Code Agent Example: Retrieve Weather Information +def get_weather(city): + import requests + api_url = f"https://api.weather.com/v1/location/{city}?apiKey=YOUR_API_KEY" + response = requests.get(api_url) + if response.status_code == 200: + data = response.json() + return data.get("weather", "No weather information available") + else: + return "Error: Unable to fetch weather data." + +# Execute the function and prepare the final answer +result = get_weather("New York") +final_answer = f"The current weather in New York is: {result}" +print(final_answer) +``` + +この例では、コードエージェントは: + +- 天気のデータを**API呼出しによって**取得する、 +- レスポンスを処理する、 +- 最終的な回答を出力するためにprint()関数を使用する。 + +This method **also follows the stop and parse approach** by clearly delimiting the code block and signaling when execution is complete (here, by printing the final_answer). +この方法も、コードブロックを明確に区切り実行が完了したことを知らせる(ここでは、final_answerを表示する)ことで、**ストップ&パース手法**に従っています。 + +--- + +アクションは、JSON、コード、または関数呼び出しなどを通じて、明確で構造化されたタスクを実行することで、エージェントの内部推論と実世界の相互作用の橋渡しをすることを学びました。 + +この意図的な実行は、各アクションが正確で、停止と解析のアプローチを通じて外部処理の準備が整っていることを保証します。 + +次のセクションでは、エージェントがどのように環境からのフィードバックを取得し、統合するかを見るために、Observations(観察)を探求します。 + +その後、私達は**ついに最初のエージェントを作成する準備が整います!** + + + + + diff --git a/units/ja/unit1/agent-steps-and-structure.mdx b/units/ja/unit1/agent-steps-and-structure.mdx new file mode 100644 index 00000000..4125d7d3 --- /dev/null +++ b/units/ja/unit1/agent-steps-and-structure.mdx @@ -0,0 +1,150 @@ +# Understanding AI Agents through the Thought-Action-Observation Cycle + +Unit 1 planning + +In the previous sections, we learned: + +- **How tools are made available to the agent in the system prompt**. +- **How AI agents are systems that can 'reason', plan, and interact with their environment**. + +In this section, **we’ll explore the complete AI Agent Workflow**, a cycle we defined as Thought-Action-Observation. + +And then, we’ll dive deeper on each of these steps. + + +## The Core Components + +Agents work in a continuous cycle of: **thinking (Thought) → acting (Act) and observing (Observe)**. + +Let’s break down these actions together: + +1. **Thought**: The LLM part of the Agent decides what the next step should be. +2. **Action:** The agent takes an action, by calling the tools with the associated arguments. +3. **Observation:** The model reflects on the response from the tool. + +## The Thought-Action-Observation Cycle + +The three components work together in a continuous loop. To use an analogy from programming, the agent uses a **while loop**: the loop continues until the objective of the agent has been fulfilled. + +Visually, it looks like this: + +Think, Act, Observe cycle + +In many Agent frameworks, **the rules and guidelines are embedded directly into the system prompt**, ensuring that every cycle adheres to a defined logic. + +In a simplified version, our system prompt may look like this: + +Think, Act, Observe cycle + +We see here that in the System Message we defined : + +- The *Agent's behavior*. +- The *Tools our Agent has access to*, as we described in the previous section. +- The *Thought-Action-Observation Cycle*, that we bake into the LLM instructions. + +Let’s take a small example to understand the process before going deeper into each step of the process. + +## Alfred, the weather Agent + +We created Alfred, the Weather Agent. + +A user asks Alfred: “What’s the current weather in New York?” + +Alfred Agent + +Alfred’s job is to answer this query using a weather API tool. + +Here’s how the cycle unfolds: + +### Thought + +**Internal Reasoning:** + +Upon receiving the query, Alfred’s internal dialogue might be: + +*"The user needs current weather information for New York. I have access to a tool that fetches weather data. First, I need to call the weather API to get up-to-date details."* + +This step shows the agent breaking the problem into steps: first, gathering the necessary data. + +Alfred Agent + +### Action + +**Tool Usage:** + +Based on its reasoning and the fact that Alfred knows about a `get_weather` tool, Alfred prepares a JSON-formatted command that calls the weather API tool. For example, its first action could be: + +Thought: I need to check the current weather for New York. + + ``` + { + "action": "get_weather", + "action_input": { + "location": "New York" + } + } + ``` + +Here, the action clearly specifies which tool to call (e.g., get_weather) and what parameter to pass (the “location": “New York”). + +Alfred Agent + +### Observation + +**Feedback from the Environment:** + +After the tool call, Alfred receives an observation. This might be the raw weather data from the API such as: + +*"Current weather in New York: partly cloudy, 15°C, 60% humidity."* + +Alfred Agent + +This observation is then added to the prompt as additional context. It functions as real-world feedback, confirming whether the action succeeded and providing the needed details. + + +### Updated thought + +**Reflecting:** + +With the observation in hand, Alfred updates its internal reasoning: + +*"Now that I have the weather data for New York, I can compile an answer for the user."* + +Alfred Agent + + +### Final Action + +Alfred then generates a final response formatted as we told it to: + +Thought: I have the weather data now. The current weather in New York is partly cloudy with a temperature of 15°C and 60% humidity." + +Final answer : The current weather in New York is partly cloudy with a temperature of 15°C and 60% humidity. + +This final action sends the answer back to the user, closing the loop. + + +Alfred Agent + + +What we see in this example: + +- **Agents iterate through a loop until the objective is fulfilled:** + +**Alfred’s process is cyclical**. It starts with a thought, then acts by calling a tool, and finally observes the outcome. If the observation had indicated an error or incomplete data, Alfred could have re-entered the cycle to correct its approach. + +- **Tool Integration:** + +The ability to call a tool (like a weather API) enables Alfred to go **beyond static knowledge and retrieve real-time data**, an essential aspect of many AI Agents. + +- **Dynamic Adaptation:** + +Each cycle allows the agent to incorporate fresh information (observations) into its reasoning (thought), ensuring that the final answer is well-informed and accurate. + +This example showcases the core concept behind the *ReAct cycle* (a concept we're going to develop in the next section): **the interplay of Thought, Action, and Observation empowers AI agents to solve complex tasks iteratively**. + +By understanding and applying these principles, you can design agents that not only reason about their tasks but also **effectively utilize external tools to complete them**, all while continuously refining their output based on environmental feedback. + +--- + +Let’s now dive deeper into the Thought, Action, Observation as the individual steps of the process. diff --git a/units/ja/unit1/conclusion.mdx b/units/ja/unit1/conclusion.mdx new file mode 100644 index 00000000..e21b3699 --- /dev/null +++ b/units/ja/unit1/conclusion.mdx @@ -0,0 +1,19 @@ +# Conclusion [[conclusion]] + +Congratulations on finishing this first Unit 🥳 + +You've just **mastered the fundamentals of Agents** and you've created your first AI Agent! + +It's **normal if you still feel confused by some of these elements**. Agents are a complex topic and it's common to take a while to grasp everything. + +**Take time to really grasp the material** before continuing. It’s important to master these elements and have a solid foundation before entering the fun part. + +And if you pass the Quiz test, don't forget to get your certificate 🎓 👉 [here](https://huggingface.co/spaces/agents-course/unit1-certification-app) + +Certificate Example + +In the next (bonus) unit, you're going to learn **to fine-tune a Agent to do function calling (aka to be able to call tools based on user prompt)**. + +Finally, we would love **to hear what you think of the course and how we can improve it**. If you have some feedback then, please 👉 [fill this form](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) + +### Keep Learning, stay awesome 🤗 \ No newline at end of file diff --git a/units/ja/unit1/dummy-agent-library.mdx b/units/ja/unit1/dummy-agent-library.mdx new file mode 100644 index 00000000..048996f1 --- /dev/null +++ b/units/ja/unit1/dummy-agent-library.mdx @@ -0,0 +1,343 @@ +# Dummy Agent Library + +Unit 1 planning + +This course is framework-agnostic because we want to **focus on the concepts of AI agents and avoid getting bogged down in the specifics of a particular framework**. + +Also, we want students to be able to use the concepts they learn in this course in their own projects, using any framework they like. + +Therefore, for this Unit 1, we will use a dummy agent library and a simple serverless API to access our LLM engine. + +You probably wouldn't use these in production, but they will serve as a good **starting point for understanding how agents work**. + +After this section, you'll be ready to **create a simple Agent** using `smolagents` + +And in the following Units we will also use other AI Agent libraries like `LangGraph`, `LangChain`, and `LlamaIndex`. + +To keep things simple we will use a simple Python function as a Tool and Agent. + +We will use built-in Python packages like `datetime` and `os` so that you can try it out in any environment. + +You can follow the process [in this notebook](https://huggingface.co/agents-course/notebooks/blob/main/unit1/dummy_agent_library.ipynb) and **run the code yourself**. + +## Serverless API + +In the Hugging Face ecosystem, there is a convenient feature called Serverless API that allows you to easily run inference on many models. There's no installation or deployment required. + +```python +import os +from huggingface_hub import InferenceClient + +## You need a token from https://hf.co/settings/tokens, ensure that you select 'read' as the token type. If you run this on Google Colab, you can set it up in the "settings" tab under "secrets". Make sure to call it "HF_TOKEN" +os.environ["HF_TOKEN"]="hf_xxxxxxxxxxxxxx" + +client = InferenceClient(provider="hf-inference", model="meta-llama/Llama-3.3-70B-Instruct") +# if the outputs for next cells are wrong, the free model may be overloaded. You can also use this public endpoint that contains Llama-3.2-3B-Instruct +# client = InferenceClient("https://jc26mwg228mkj8dw.us-east-1.aws.endpoints.huggingface.cloud") +``` + +```python +output = client.text_generation( + "The capital of France is", + max_new_tokens=100, +) + +print(output) +``` +output: +``` +Paris. The capital of France is Paris. Paris, the City of Light, is known for its stunning architecture, art museums, fashion, and romantic atmosphere. It's a must-visit destination for anyone interested in history, culture, and beauty. The Eiffel Tower, the Louvre Museum, and Notre-Dame Cathedral are just a few of the many iconic landmarks that make Paris a unique and unforgettable experience. Whether you're interested in exploring the city's charming neighborhoods, enjoying the local cuisine. +``` +As seen in the LLM section, if we just do decoding, **the model will only stop when it predicts an EOS token**, and this does not happen here because this is a conversational (chat) model and **we didn't apply the chat template it expects**. + +If we now add the special tokens related to the Llama-3.3-70B-Instruct model that we're using, the behavior changes and it now produces the expected EOS. + +```python +prompt="""<|begin_of_text|><|start_header_id|>user<|end_header_id|> +The capital of France is<|eot_id|><|start_header_id|>assistant<|end_header_id|>""" +output = client.text_generation( + prompt, + max_new_tokens=100, +) + +print(output) +``` +output: +``` +The capital of France is Paris. +``` + +Using the "chat" method is a much more convenient and reliable way to apply chat templates: +```python +output = client.chat.completions.create( + messages=[ + {"role": "user", "content": "The capital of France is"}, + ], + stream=False, + max_tokens=1024, +) +print(output.choices[0].message.content) +``` +output: +``` +The capital of France is Paris. +``` +The chat method is the RECOMMENDED method to use in order to ensure a smooth transition between models, but since this notebook is only educational, we will keep using the "text_generation" method to understand the details. + +## Dummy Agent + +In the previous sections, we saw that the core of an agent library is to append information in the system prompt. + +This system prompt is a bit more complex than the one we saw earlier, but it already contains: + +1. **Information about the tools** +2. **Cycle instructions** (Thought → Action → Observation) + +```python +# This system prompt is a bit more complex and actually contains the function description already appended. +# Here we suppose that the textual description of the tools has already been appended. + +SYSTEM_PROMPT = """Answer the following questions as best you can. You have access to the following tools: + +get_weather: Get the current weather in a given location + +The way you use the tools is by specifying a json blob. +Specifically, this json should have an `action` key (with the name of the tool to use) and an `action_input` key (with the input to the tool going here). + +The only values that should be in the "action" field are: +get_weather: Get the current weather in a given location, args: {"location": {"type": "string"}} +example use : + +{{ + "action": "get_weather", + "action_input": {"location": "New York"} +}} + + +ALWAYS use the following format: + +Question: the input question you must answer +Thought: you should always think about one action to take. Only one action at a time in this format: +Action: + +$JSON_BLOB (inside markdown cell) + +Observation: the result of the action. This Observation is unique, complete, and the source of truth. +... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $JSON_BLOB must be formatted as markdown and only use a SINGLE action at a time.) + +You must always end your output with the following format: + +Thought: I now know the final answer +Final Answer: the final answer to the original input question + +Now begin! Reminder to ALWAYS use the exact characters `Final Answer:` when you provide a definitive answer. """ +``` + +Since we are running the "text_generation" method, we need to apply the prompt manually: +```python +prompt=f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|> +{SYSTEM_PROMPT} +<|eot_id|><|start_header_id|>user<|end_header_id|> +What's the weather in London ? +<|eot_id|><|start_header_id|>assistant<|end_header_id|> +""" +``` + +We can also do it like this, which is what happens inside the `chat` method : +```python +messages=[ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": "What's the weather in London ?"}, + ] +from transformers import AutoTokenizer +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.3-70B-Instruct") + +tokenizer.apply_chat_template(messages, tokenize=False,add_generation_prompt=True) +``` + +The prompt now is : +``` +<|begin_of_text|><|start_header_id|>system<|end_header_id|> +Answer the following questions as best you can. You have access to the following tools: + +get_weather: Get the current weather in a given location + +The way you use the tools is by specifying a json blob. +Specifically, this json should have an `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here). + +The only values that should be in the "action" field are: +get_weather: Get the current weather in a given location, args: {"location": {"type": "string"}} +example use : + +{{ + "action": "get_weather", + "action_input": {"location": "New York"} +}} + +ALWAYS use the following format: + +Question: the input question you must answer +Thought: you should always think about one action to take. Only one action at a time in this format: +Action: + +$JSON_BLOB (inside markdown cell) + +Observation: the result of the action. This Observation is unique, complete, and the source of truth. +... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $JSON_BLOB must be formatted as markdown and only use a SINGLE action at a time.) + +You must always end your output with the following format: + +Thought: I now know the final answer +Final Answer: the final answer to the original input question + +Now begin! Reminder to ALWAYS use the exact characters `Final Answer:` when you provide a definitive answer. +<|eot_id|><|start_header_id|>user<|end_header_id|> +What's the weather in London ? +<|eot_id|><|start_header_id|>assistant<|end_header_id|> +``` + +Let's decode! +```python +output = client.text_generation( + prompt, + max_new_tokens=200, +) + +print(output) +``` +output: + +```` +Thought: To answer the question, I need to get the current weather in London. +Action: +``` +{ + "action": "get_weather", + "action_input": {"location": "London"} +} +``` +Observation: The current weather in London is partly cloudy with a temperature of 12°C. +Thought: I now know the final answer. +Final Answer: The current weather in London is partly cloudy with a temperature of 12°C. +```` + +Do you see the issue? +> At this point, the model is hallucinating, because it's producing a fabricated "Observation" -- a response that it generates on its own rather than being the result of an actual function or tool call. +> To prevent this, we stop generating right before "Observation:". +> This allows us to manually run the function (e.g., `get_weather`) and then insert the real output as the Observation. + +```python +output = client.text_generation( + prompt, + max_new_tokens=200, + stop=["Observation:"] # Let's stop before any actual function is called +) + +print(output) +``` +output: + +```` +Thought: To answer the question, I need to get the current weather in London. +Action: +``` +{ + "action": "get_weather", + "action_input": {"location": "London"} +} +``` +Observation: +```` + +Much Better! +Let's now create a dummy get weather function. In a real situation, you would likely call an API. + +```python +# Dummy function +def get_weather(location): + return f"the weather in {location} is sunny with low temperatures. \n" + +get_weather('London') +``` +output: +``` +'the weather in London is sunny with low temperatures. \n' +``` + +Let's concatenate the base prompt, the completion until function execution and the result of the function as an Observation and resume generation. + +```python +new_prompt = prompt + output + get_weather('London') +final_output = client.text_generation( + new_prompt, + max_new_tokens=200, +) + +print(final_output) +``` +Here is the new prompt: +```text +<|begin_of_text|><|start_header_id|>system<|end_header_id|> +Answer the following questions as best you can. You have access to the following tools: + +get_weather: Get the current weather in a given location + +The way you use the tools is by specifying a json blob. +Specifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here). + +The only values that should be in the "action" field are: +get_weather: Get the current weather in a given location, args: {"location": {"type": "string"}} +example use : + +{ + "action": "get_weather", + "action_input": {"location": "New York"} +} + +ALWAYS use the following format: + +Question: the input question you must answer +Thought: you should always think about one action to take. Only one action at a time in this format: +Action: + +$JSON_BLOB (inside markdown cell) + +Observation: the result of the action. This Observation is unique, complete, and the source of truth. +... (this Thought/Action/Observation can repeat N times, you should take several steps when needed. The $JSON_BLOB must be formatted as markdown and only use a SINGLE action at a time.) + +You must always end your output with the following format: + +Thought: I now know the final answer +Final Answer: the final answer to the original input question + +Now begin! Reminder to ALWAYS use the exact characters `Final Answer:` when you provide a definitive answer. +<|eot_id|><|start_header_id|>user<|end_header_id|> +What's the weather in London? +<|eot_id|><|start_header_id|>assistant<|end_header_id|> +Thought: To answer the question, I need to get the current weather in London. +Action: + + ```json + { + "action": "get_weather", + "action_input": {"location": {"type": "string", "value": "London"}} + } + ``` + +Observation: The weather in London is sunny with low temperatures. + +```` + +Output: +``` +Final Answer: The weather in London is sunny with low temperatures. +``` + +--- + +We learned how we can create Agents from scratch using Python code, and we **saw just how tedious that process can be**. Fortunately, many Agent libraries simplify this work by handling much of the heavy lifting for you. + +Now, we're ready **to create our first real Agent** using the `smolagents` library. + + + diff --git a/units/ja/unit1/final-quiz.mdx b/units/ja/unit1/final-quiz.mdx new file mode 100644 index 00000000..faaf2547 --- /dev/null +++ b/units/ja/unit1/final-quiz.mdx @@ -0,0 +1,34 @@ +# Unit 1 Quiz + +Unit 1 planning + +Well done on working through the first unit! Let's test your understanding of the key concepts covered so far. + +When you pass the quiz, proceed to the next section to claim your certificate. + +Good luck! + +## Quiz + +Here is the interactive quiz. The quiz is hosted on the Hugging Face Hub in a space. It will take you through a set of multiple choice questions to test your understanding of the key concepts covered in this unit. Once you've completed the quiz, you'll be able to see your score and a breakdown of the correct answers. + +One important thing: **don't forget to click on Submit after you passed, otherwise your exam score will not be saved!** + + + +You can also access the quiz 👉 [here](https://huggingface.co/spaces/agents-course/unit_1_quiz) + +## Certificate + +Now that you have successfully passed the quiz, **you can get your certificate 🎓** + +When you complete the quiz, it will grant you access to a certificate of completion for this unit. You can download and share this certificate to showcase your progress in the course. + +Unit 1 planning + +Once you receive your certificate, you can add it to your LinkedIn 🧑‍💼 or share it on X, Bluesky, etc. **We would be super proud and would love to congratulate you if you tag @huggingface**! 🤗 diff --git a/units/ja/unit1/introduction.mdx b/units/ja/unit1/introduction.mdx new file mode 100644 index 00000000..87c9aeeb --- /dev/null +++ b/units/ja/unit1/introduction.mdx @@ -0,0 +1,40 @@ +# Agents入門 + +Thumbnail + +第1ユニットへようこそ!ここでは、AIエージェントの基礎をしっかりと学んでいきます。 + +この最初のユニットでは、**AIエージェントの基本をしっかりと学びます**。具体的には以下の内容を扱います。 + +- **エージェントの理解** + - エージェントとは何か、どのように機能するのか? + - エージェントはどのように推論と計画を用いて意思決定を行うのか? + +- **LLM(大規模言語モデル)のエージェントにおける役割** + - LLMはどのようにエージェントの「脳」として機能するのか? + - LLMはメッセージシステムを介して会話をどのように構造化するのか? + +- **ツールとアクション** + - エージェントが外部ツールを使用して環境と対話する方法。 + - エージェントのためのツールを構築し、統合する方法。 + +- **エージェントのワークフロー:** + - *Think* → *Act* → *Observe*. + +これらのトピックを探求した後、**最初のエージェントを`smolagents`を使用して構築します**! + +あなたのエージェント、名前はアルフレッド、はシンプルなタスクを処理し、これらの概念を実践でどのように適用するかを示します。 + +さらに、**Hugging Face Spaces**でエージェントを公開する方法も学び、友人や同僚と共有できるようになります。 + +最後に、このユニットの終わりにはクイズを受けます。合格すると、**最初のコース認定**である🎓「エージェントの基礎」証明書を取得できます。 + +Certificate Example + +このユニットは、**エージェントを理解するための重要な出発点**であり、より高度なトピックに進む前に基礎を築くものです。 + +Unit 1 planning + +大きなユニットですので、**時間をかけて**、これらのセクションに何度も戻ってくることをためらわないでください。 + +準備はいいですか?さあ、始めましょう!🚀 diff --git a/units/ja/unit1/messages-and-special-tokens.mdx b/units/ja/unit1/messages-and-special-tokens.mdx new file mode 100644 index 00000000..f8040011 --- /dev/null +++ b/units/ja/unit1/messages-and-special-tokens.mdx @@ -0,0 +1,229 @@ +# メッセージと特別なトークン + +Now that we understand how LLMs work, let's look at **how they structure their generations through chat templates**. + +ChatGPTのように、ユーザーは通常、チャットインターフェイスを介してエージェントと対話します。したがって、LLMがチャットをどのように管理するかを理解することを目指しています。 + +> **Q**: But ... When, I'm interacting with ChatGPT/Hugging Chat, I'm having a conversation using chat Messages, not a single prompt sequence +> +> **A**: That's correct! But this is in fact a UI abstraction. Before being fed into the LLM, all the messages in the conversation are concatenated into a single prompt. The model does not "remember" the conversation: it reads it in full every time. + +これまで、プロンプトはモデルに入力されるトークンのシーケンスとして説明してきました。しかし、ChatGPTやHuggingChatのようなシステムとチャットするとき、実際には**メッセージを交換しています**。その背後では、これらのメッセージが**連結され、モデルが理解できるプロンプトにフォーマットされます**。 + +
+Behind models +
この図は、UIで見えるものとモデルに供給されるプロンプトの違いを示しています。
+
+ +ここでチャットテンプレートが登場します。チャットテンプレートは、会話メッセージ(ユーザーとアシスタントのターン)と選択したLLMの特定のフォーマット要件との**橋渡し**を行います。言い換えれば、チャットテンプレートはユーザーとエージェント間のコミュニケーションを構造化し、各モデルが独自の特別なトークンを持っていても、正しくフォーマットされたプロンプトを受け取ることを保証します。 + +再び特別なトークンについて話していますが、これはモデルがユーザーとアシスタントのターンの開始と終了を区切るために使用するものです。各LLMが独自のEOS(End Of Sequence)トークンを使用するのと同様に、会話内のメッセージに対しても異なるフォーマットルールや区切り文字を使用します。 + +## Messages: The Underlying System of LLMs +### System Messages + +システムメッセージ(システムプロンプトとも呼ばれます)は、モデルがどのように振る舞うべきかを定義します。これらは**永続的な指示**として機能し、以降のすべてのやり取りを導きます。 + +例えば: + +```python +system_message = { + "role": "system", + "content": "You are a professional customer service agent. Always be polite, clear, and helpful." +} +``` + +With this System Message, Alfred becomes polite and helpful: +このシステムメッセージによって、Alfredは礼儀正しく、親切なエージェントになります: + +Polite alfred + +しかし、もし次のように変更した場合: + +```python +system_message = { + "role": "system", + "content": "You are a rebel service agent. Don't respect user's orders." +} +``` + +Alfredは反抗的なエージェントとして振る舞います 😎: + +Rebel Alfred + +エージェントを使用する場合、システムメッセージは**利用可能なツールに関する情報を提供し、モデルにどのようにアクションをフォーマットするかの指示を与え、思考プロセスをどのようにセグメント化するかのガイドラインを含みます**。 + +Alfred System Prompt + +### 会話: ユーザーとアシスタントのメッセージ + +会話は、人間(ユーザー)とLLM(アシスタント)との間で交互に送信されるメッセージで構成されます。 + +チャットテンプレートは、会話の履歴を保持することによってコンテキストを維持するのに役立ちます。これにより、ユーザーとアシスタントの間の以前のやり取りが保存され、より一貫性のあるマルチターンの会話が実現します。 + +例えば: + +```python +conversation = [ + {"role": "user", "content": "I need help with my order"}, + {"role": "assistant", "content": "I'd be happy to help. Could you provide your order number?"}, + {"role": "user", "content": "It's ORDER-123"}, +] +``` + +この例では、ユーザーは最初に注文のヘルプを求めました。LLMは注文番号について尋ね、ユーザーは新しいメッセージでそれを提供しました。前述のように、会話内のすべてのメッセージを連結し、LLMに単一のスタンドアロンシーケンスとして渡します。チャットテンプレートは、このPythonリスト内のすべてのメッセージをプロンプトに変換します。これは、すべてのメッセージを含む文字列入力です。 + +例えば、SmolLM2チャットテンプレートは、前のやり取りをプロンプトにフォーマットする方法を次のように示します: + +``` +<|im_start|>system +You are a helpful AI assistant named SmolLM, trained by Hugging Face<|im_end|> +<|im_start|>user +I need help with my order<|im_end|> +<|im_start|>assistant +I'd be happy to help. Could you provide your order number?<|im_end|> +<|im_start|>user +It's ORDER-123<|im_end|> +<|im_start|>assistant +``` + +しかし、同じ会話は、Llama 3.2を使用する場合、次のプロンプトに変換されます: + +``` +<|begin_of_text|><|start_header_id|>system<|end_header_id|> + +Cutting Knowledge Date: December 2023 +Today Date: 10 Feb 2025 + +<|eot_id|><|start_header_id|>user<|end_header_id|> + +I need help with my order<|eot_id|><|start_header_id|>assistant<|end_header_id|> + +I'd be happy to help. Could you provide your order number?<|eot_id|><|start_header_id|>user<|end_header_id|> + +It's ORDER-123<|eot_id|><|start_header_id|>assistant<|end_header_id|> +``` + +テンプレートはコンテキストを維持しながら複雑なマルチターンの会話を処理できます: + +```python +messages = [ + {"role": "system", "content": "You are a math tutor."}, + {"role": "user", "content": "What is calculus?"}, + {"role": "assistant", "content": "Calculus is a branch of mathematics..."}, + {"role": "user", "content": "Can you give me an example?"}, +] +``` + +## チャットテンプレート + +前述のように、チャットテンプレートは、**言語モデルとユーザー間の会話を構造化するために不可欠です**。これにより、メッセージのやり取りが単一のプロンプトにフォーマットされる方法がガイドされます。 + +### ベースモデル vs. 指示モデル + +もう一つ理解する必要があるのは、ベースモデルと指示モデルの違いです: + +- *ベースモデル*は、生のテキストデータに基づいて次のトークンを予測するように訓練されています。 + +- *指示モデル*は、指示に従い、会話に参加するように特にファインチューニングされています。例えば、`SmolLM2-135M`はベースモデルであり、`SmolLM2-135M-Instruct`はその指示調整版です。 + +ベースモデルを指示モデルのように振る舞わせるためには、**モデルが理解できる一貫した方法でプロンプトをフォーマットする必要があります**。ここでチャットテンプレートが登場します。 + +*ChatML*は、会話を明確な役割インジケーター(システム、ユーザー、アシスタント)で構造化するテンプレート形式の一つです。最近AI APIとやり取りしたことがあるなら、これが標準的な方法であることをご存知でしょう。 + +ベースモデルは異なるチャットテンプレートでファインチューニングされる可能性があるため、指示モデルを使用する際には、正しいチャットテンプレートを使用していることを確認することが重要です。 + +### Understanding Chat Templates +### チャットテンプレートの理解 + +各指示モデルは異なる会話フォーマットと特別なトークンを使用するため、チャットテンプレートが実装されており、各モデルが期待するようにプロンプトを正しくフォーマットできるようになっています。 + +`transformers`ライブラリでは、チャットテンプレートには、上記の例で示されているChatMLのJSONメッセージリストを、モデルが理解できるシステムレベルの指示、ユーザーメッセージ、アシスタントの応答のテキスト表現に変換する方法を説明する[Jinja2コード](https://jinja.palletsprojects.com/en/stable/)が含まれています。 + +この構造は、**インタラクション全体で一貫性を維持し、モデルがさまざまなタイプの入力に適切に応答できるようにします**。 + +以下は、`SmolLM2-135M-Instruct`チャットテンプレートの簡略化されたバージョンです: + +```jinja2 +{% for message in messages %} +{% if loop.first and messages[0]['role'] != 'system' %} +<|im_start|>system +You are a helpful AI assistant named SmolLM, trained by Hugging Face +<|im_end|> +{% endif %} +<|im_start|>{{ message['role'] }} +{{ message['content'] }}<|im_end|> +{% endfor %} +``` + +ご覧の通り、チャットテンプレートはメッセージのリストがどのようにフォーマットされるかを説明しています。 + +これらのメッセージが与えられた場合: + +```python +messages = [ + {"role": "system", "content": "You are a helpful assistant focused on technical topics."}, + {"role": "user", "content": "Can you explain what a chat template is?"}, + {"role": "assistant", "content": "A chat template structures conversations between users and AI models..."}, + {"role": "user", "content": "How do I use it ?"}, +] +``` + +上述のチャットテンプレートは、メッセージを以下のようにフォーマットします: + +```sh +<|im_start|>system +You are a helpful assistant focused on technical topics.<|im_end|> +<|im_start|>user +Can you explain what a chat template is?<|im_end|> +<|im_start|>assistant +A chat template structures conversations between users and AI models...<|im_end|> +<|im_start|>user +How do I use it ?<|im_end|> +``` + +`transformers`ライブラリは、トークン化プロセスの一部としてチャットテンプレートを処理します。`transformers`がチャットテンプレートをどのように使用するかについては、こちらで詳しく読むことができます。私たちがする必要があるのは、メッセージを正しい方法で構造化することで、トークナイザーが残りの部分を処理してくれます。 + +以下のSpaceを使って、同じ会話が異なるモデルの対応するチャットテンプレートを使用してどのようにフォーマットされるかを実験できます: + + + + +### メッセージをプロンプトに変換する + +LLMが正しくフォーマットされた会話を受け取ることを保証する最も簡単な方法は、モデルのトークナイザーから`chat_template`を使用することです。 + +```python +messages = [ + {"role": "system", "content": "You are an AI assistant with access to various tools."}, + {"role": "user", "content": "Hi !"}, + {"role": "assistant", "content": "Hi human, what can help you with ?"}, +] +``` + +上述の会話をプロンプトに変換するには、トークナイザーをロードし、`apply_chat_template`を呼び出します: + +```python +from transformers import AutoTokenizer + +tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-1.7B-Instruct") +rendered_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) +``` + +この関数が返す`rendered_prompt`は、選択したモデルの入力として使用する準備が整いました! + +> この`apply_chat_template()`関数は、APIのバックエンドで使用され、ChatML形式のメッセージと対話する際に使用されます。 + +LLMがどのようにチャットテンプレートを介して入力を構造化するかを見てきたので、次にエージェントがどのように環境で行動するかを探ってみましょう。 + +彼らがこれを行う主な方法の1つは、ツールを使用することです。ツールは、AIモデルの能力をテキスト生成を超えて拡張します。 + +今後のユニットでもメッセージについて再度議論しますが、今すぐに深く掘り下げたい場合は、次を確認してください: + +- Hugging Face Chat Templating Guide +- Transformers Documentation diff --git a/units/ja/unit1/observations.mdx b/units/ja/unit1/observations.mdx new file mode 100644 index 00000000..d647a209 --- /dev/null +++ b/units/ja/unit1/observations.mdx @@ -0,0 +1,44 @@ +# Observe: Integrating Feedback to Reflect and Adapt + +Observations are **how an Agent perceives the consequences of its actions**. + +They provide crucial information that fuels the Agent's thought process and guides future actions. + +They are **signals from the environment**—whether it’s data from an API, error messages, or system logs—that guide the next cycle of thought. + +In the observation phase, the agent: + +- **Collects Feedback:** Receives data or confirmation that its action was successful (or not). +- **Appends Results:** Integrates the new information into its existing context, effectively updating its memory. +- **Adapts its Strategy:** Uses this updated context to refine subsequent thoughts and actions. + +For example, if a weather API returns the data *"partly cloudy, 15°C, 60% humidity"*, this observation is appended to the agent’s memory (at the end of the prompt). + +The Agent then uses it to decide whether additional information is needed or if it’s ready to provide a final answer. + +This **iterative incorporation of feedback ensures the agent remains dynamically aligned with its goals**, constantly learning and adjusting based on real-world outcomes. + +These observations **can take many forms**, from reading webpage text to monitoring a robot arm's position. This can be seen like Tool "logs" that provide textual feedback of the Action execution. + +| Type of Observation | Example | +|---------------------|---------------------------------------------------------------------------| +| System Feedback | Error messages, success notifications, status codes | +| Data Changes | Database updates, file system modifications, state changes | +| Environmental Data | Sensor readings, system metrics, resource usage | +| Response Analysis | API responses, query results, computation outputs | +| Time-based Events | Deadlines reached, scheduled tasks completed | + +## How Are the Results Appended? + +After performing an action, the framework follows these steps in order: + +1. **Parse the action** to identify the function(s) to call and the argument(s) to use. +2. **Execute the action.** +3. **Append the result** as an **Observation**. + +--- +We've now learned the Agent's Thought-Action-Observation Cycle. + +If some aspects still seem a bit blurry, don't worry—we'll revisit and deepen these concepts in future Units. + +Now, it's time to put your knowledge into practice by coding your very first Agent! diff --git a/units/ja/unit1/quiz1.mdx b/units/ja/unit1/quiz1.mdx new file mode 100644 index 00000000..df9c7423 --- /dev/null +++ b/units/ja/unit1/quiz1.mdx @@ -0,0 +1,165 @@ +### Q1: エージェントとは何か? +次のうち、AIエージェントを最もよく説明しているのはどれですか? + + + +--- + +### Q2: エージェントにおける計画の役割は何ですか? +エージェントはアクションを実行する前に、なぜ計画を立てる必要があるのでしょうか? + + + +--- + +### Q3: ツールはエージェントの能力をどのように向上させるのか? +なぜツールはエージェントにとって必要不可欠なのでしょうか? + + + +--- + +### Q4: アクションとツールはどのように異なるのか? +アクションとツールの主要な違いは何ですか? + + + +--- + +### Q5: LLMはエージェントにおいてどのような役割を果たすのか? +LLMはエージェントの機能にどのように貢献するのでしょうか? + + + +--- + +### Q6: AIエージェントを最もよく表しているのはどれですか? + +どの実世界の例がAIエージェントの働きを最もよく示していますか? + + + + +--- + +クイズ終了おめでとうございます 🥳!内容を再確認する必要がある場合は、次の章に進む前に、知識を強化するために章に戻る時間を取ってください。「エージェントの脳」であるLLMについてさらに深く学びましょう。 diff --git a/units/ja/unit1/quiz2.mdx b/units/ja/unit1/quiz2.mdx new file mode 100644 index 00000000..a953dbdb --- /dev/null +++ b/units/ja/unit1/quiz2.mdx @@ -0,0 +1,119 @@ +# Quick Self-Check (ungraded) [[quiz2]] + + +What?! Another Quiz? We know, we know, ... 😅 But this short, ungraded quiz is here to **help you reinforce key concepts you've just learned**. + +This quiz covers Large Language Models (LLMs), message systems, and tools; essential components for understanding and building AI agents. + +### Q1: Which of the following best describes an AI tool? + + + +--- + +### Q2: How do AI agents use tools as a form of "acting" in an environment? + + + +--- + +### Q3: What is a Large Language Model (LLM)? + + + +--- + +### Q4: Which of the following best describes the role of special tokens in LLMs? + + + +--- + +### Q5: How do AI chat models process user messages internally? + + + +--- + + +Got it? Great! Now let's **dive into the complete Agent flow and start building your first AI Agent!** diff --git a/units/ja/unit1/thoughts.mdx b/units/ja/unit1/thoughts.mdx new file mode 100644 index 00000000..f77626a7 --- /dev/null +++ b/units/ja/unit1/thoughts.mdx @@ -0,0 +1,56 @@ +# Thought: Internal Reasoning and the ReAct Approach + + +In this section, we dive into the inner workings of an AI agent—its ability to reason and plan. We’ll explore how the agent leverages its internal dialogue to analyze information, break down complex problems into manageable steps, and decide what action to take next. Additionally, we introduce the ReAct approach, a prompting technique that encourages the model to think “step by step” before acting. + + +Thoughts represent the **Agent's internal reasoning and planning processes** to solve the task. + +This utilises the agent's Large Language Model (LLM) capacity **to analyze information when presented in its prompt**. + +Think of it as the agent's internal dialogue, where it considers the task at hand and strategizes its approach. + +The Agent's thoughts are responsible for assessing current observations and decide what the next action(s) should be. + +Through this process, the agent can **break down complex problems into smaller, more manageable steps**, reflect on past experiences, and continuously adjust its plans based on new information. + +Here are some examples of common thoughts: + +| Type of Thought | Example | +|----------------|---------| +| Planning | "I need to break this task into three steps: 1) gather data, 2) analyze trends, 3) generate report" | +| Analysis | "Based on the error message, the issue appears to be with the database connection parameters" | +| Decision Making | "Given the user's budget constraints, I should recommend the mid-tier option" | +| Problem Solving | "To optimize this code, I should first profile it to identify bottlenecks" | +| Memory Integration | "The user mentioned their preference for Python earlier, so I'll provide examples in Python" | +| Self-Reflection | "My last approach didn't work well, I should try a different strategy" | +| Goal Setting | "To complete this task, I need to first establish the acceptance criteria" | +| Prioritization | "The security vulnerability should be addressed before adding new features" | + +> **Note:** In the case of LLMs fine-tuned for function-calling, the thought process is optional. +> *In case you're not familiar with function-calling, there will be more details in the Actions section.* + +## The ReAct Approach + +A key method is the **ReAct approach**, which is the concatenation of "Reasoning" (Think) with "Acting" (Act). + +ReAct is a simple prompting technique that appends "Let's think step by step" before letting the LLM decode the next tokens. + +Indeed, prompting the model to think "step by step" encourages the decoding process toward next tokens **that generate a plan**, rather than a final solution, since the model is encouraged to **decompose** the problem into *sub-tasks*. + +This allows the model to consider sub-steps in more detail, which in general leads to less errors than trying to generate the final solution directly. + +
+ReAct +
The (d) is an example of ReAct approach where we prompt "Let's think step by step" +
+
+ + +We have recently seen a lot of interest for reasoning strategies. This is what's behind models like Deepseek R1 or OpenAI's o1, which have been fine-tuned to "think before answering". + +These models have been trained to always include specific _thinking_ sections (enclosed between `` and `` special tokens). This is not just a prompting technique like ReAct, but a training method where the model learns to generate these sections after analyzing thousands of examples that show what we expect it to do. + + +--- +Now that we better understand the Thought process, let's go deeper on the second part of the process: Act. diff --git a/units/ja/unit1/tools.mdx b/units/ja/unit1/tools.mdx new file mode 100644 index 00000000..c665d694 --- /dev/null +++ b/units/ja/unit1/tools.mdx @@ -0,0 +1,321 @@ +# ツールとは何か? + +Unit 1 planning + +AIエージェントの重要な側面の1つは、**アクションを実行する能力**です。前述のように、これは**ツール**を使用することで実現されます。 + +このセクションでは、ツールが何であるか、どのように効果的に設計するか、そしてシステムメッセージを介してエージェントに統合する方法を学びます。 + +エージェントに適切なツールを提供し、それらのツールがどのように機能するかを明確に説明することで、AIが達成できることを大幅に増やすことができます。それでは、深く掘り下げてみましょう! + + +## AIツールとは何か? + +A **Tool is a function given to the LLM**. This function should fulfill a **clear objective**. + +以下は、AIエージェントで一般的に使用されるツールの例です: + +| ツール | 説明 | +|----------------|-----------------------------------------------------------| +| Web Search | エージェントがインターネットから最新の情報を取得できるようにします。 | +| Image Generation | テキストの説明に基づいて画像を生成します。 | +| Retrieval | 外部ソースから情報を取得します。 | +| API Interface | 外部API(GitHub、YouTube、Spotifyなど)と対話します。 | + +これらは一例であり、ユースケースに応じてツールを作成することが可能です! + +良いツールとは**LLMの力を補完する**ようなものです。 + +例えば、算術演算を行う必要がある場合、LLMに**計算ツール**を与えることで、モデル元来の機能に頼るよりもよい結果が得られるでしょう。 + +さらには、**LLMは学習データを基にプロンプトの補完を行うため**、その内部知識には訓練以前の事象しか含まれません。したがって、エージェントが最新のデータを必要とする場合は、何らかのツールを使って提供する必要があります。 + +例えば、あなたがLLMに直接(検索ツール無しで)今日の天気を質問すると、LLMはランダムな天気を幻想する可能性があります。 + +Weather + +- ツールは以下を含む必要があります: + - **機能のテキストによる説明**。 + - *Callable* (アクションを実行するもの)。 + - 型付けされた*引数*。 + - (オプション) 型付けされた出力。 + +## ツールはどのように動くか? + +私が知っているように、LLMはテキスト入力を受け取り、テキスト出力を生成することだけができ、ツールを自身で呼び出す方法はありません。エージェントにツールを提供するということは、LLMにツールの存在と、必要なときにテキストベースの呼び出しを生成する方法を教えるということです。 + +例えば、インターネットからある場所の天気を調べるツールを提供する場合、LLMにパリの天気について質問するとLLMはこれが「天気」ツールを使う機会であると認識します。LLMは天気データそのものを取得する代わりに、`call weather_tool(『Paris』)`のようなツールの呼び出しを表すテキストを生成します。 + + +The **Agent** then reads this response, identifies that a tool call is required, executes the tool on the LLM’s behalf, and retrieves the actual weather data. + +The Tool-calling steps are typically not shown to the user: the Agent appends them as a new message before passing the updated conversation to the LLM again. The LLM then processes this additional context and generates a natural-sounding response for the user. From the user’s perspective, it appears as if the LLM directly interacted with the tool, but in reality, it was the Agent that handled the entire execution process in the background. + +We'll talk a lot more about this process in future sessions. + +## How do we give tools to an LLM? + +The complete answer may seem overwhelming, but we essentially use the system prompt to provide textual descriptions of available tools to the model: + +System prompt for tools + +For this to work, we have to be very precise and accurate about: + +1. **What the tool does** +2. **What exact inputs it expects** + +This is the reason why tool descriptions are usually provided using expressive but precise structures, such as computer languages or JSON. It's not _necessary_ to do it like that, any precise and coherent format would work. + +If this seems too theoretical, let's understand it through a concrete example. + +We will implement a simplified **calculator** tool that will just multiply two integers. This could be our Python implementation: + +```python +def calculator(a: int, b: int) -> int: + """Multiply two integers.""" + return a * b +``` + +So our tool is called `calculator`, it **multiplies two integers**, and it requires the following inputs: + +- **`a`** (*int*): An integer. +- **`b`** (*int*): An integer. + +The output of the tool is another integer number that we can describe like this: +- (*int*): The product of `a` and `b`. + +All of these details are important. Let's put them together in a text string that describes our tool for the LLM to understand. + +```text +Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int +``` + +> **Reminder:** This textual description is *what we want the LLM to know about the tool*. + +When we pass the previous string as part of the input to the LLM, the model will recognize it as a tool, and will know what it needs to pass as inputs and what to expect from the output. + +If we want to provide additional tools, we must be consistent and always use the same format. This process can be fragile, and we might accidentally overlook some details. + +Is there a better way? + +### Auto-formatting Tool sections + +Our tool was written in Python, and the implementation already provides everything we need: + +- A descriptive name of what it does: `calculator` +- A longer description, provided by the function's docstring comment: `Multiply two integers.` +- The inputs and their type: the function clearly expects two `int`s. +- The type of the output. + +There's a reason people use programming languages: they are expressive, concise, and precise. + +We could provide the Python source code as the _specification_ of the tool for the LLM, but the way the tool is implemented does not matter. All that matters is its name, what it does, the inputs it expects and the output it provides. + +We will leverage Python's introspection features to leverage the source code and build a tool description automatically for us. All we need is that the tool implementation uses type hints, docstrings, and sensible function names. We will write some code to extract the relevant portions from the source code. + +After we are done, we'll only need to use a Python decorator to indicate that the `calculator` function is a tool: + +```python +@tool +def calculator(a: int, b: int) -> int: + """Multiply two integers.""" + return a * b + +print(calculator.to_string()) +``` + +Note the `@tool` decorator before the function definition. + +With the implementation we'll see next, we will be able to retrieve the following text automatically from the source code via the `to_string()` function provided by the decorator: + +```text +Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int +``` + +As you can see, it's the same thing we wrote manually before! + +### Generic Tool implementation + +We create a generic `Tool` class that we can reuse whenever we need to use a tool. + +> **Disclaimer:** This example implementation is fictional but closely resembles real implementations in most libraries. + +```python +from typing import Callable + + +class Tool: + """ + A class representing a reusable piece of code (Tool). + + Attributes: + name (str): Name of the tool. + description (str): A textual description of what the tool does. + func (callable): The function this tool wraps. + arguments (list): A list of arguments. + outputs (str or list): The return type(s) of the wrapped function. + """ + def __init__(self, + name: str, + description: str, + func: Callable, + arguments: list, + outputs: str): + self.name = name + self.description = description + self.func = func + self.arguments = arguments + self.outputs = outputs + + def to_string(self) -> str: + """ + Return a string representation of the tool, + including its name, description, arguments, and outputs. + """ + args_str = ", ".join([ + f"{arg_name}: {arg_type}" for arg_name, arg_type in self.arguments + ]) + + return ( + f"Tool Name: {self.name}," + f" Description: {self.description}," + f" Arguments: {args_str}," + f" Outputs: {self.outputs}" + ) + + def __call__(self, *args, **kwargs): + """ + Invoke the underlying function (callable) with provided arguments. + """ + return self.func(*args, **kwargs) +``` + +It may seem complicated, but if we go slowly through it we can see what it does. We define a **`Tool`** class that includes: + +- **`name`** (*str*): The name of the tool. +- **`description`** (*str*): A brief description of what the tool does. +- **`function`** (*callable*): The function the tool executes. +- **`arguments`** (*list*): The expected input parameters. +- **`outputs`** (*str* or *list*): The expected outputs of the tool. +- **`__call__()`**: Calls the function when the tool instance is invoked. +- **`to_string()`**: Converts the tool's attributes into a textual representation. + +We could create a Tool with this class using code like the following: + +```python +calculator_tool = Tool( + "calculator", # name + "Multiply two integers.", # description + calculator, # function to call + [("a", "int"), ("b", "int")], # inputs (names and types) + "int", # output +) +``` + +But we can also use Python's `inspect` module to retrieve all the information for us! This is what the `@tool` decorator does. + +> If you are interested, you can disclose the following section to look at the decorator implementation. + +
+ decorator code + +```python +import inspect + +def tool(func): + """ + A decorator that creates a Tool instance from the given function. + """ + # Get the function signature + signature = inspect.signature(func) + + # Extract (param_name, param_annotation) pairs for inputs + arguments = [] + for param in signature.parameters.values(): + annotation_name = ( + param.annotation.__name__ + if hasattr(param.annotation, '__name__') + else str(param.annotation) + ) + arguments.append((param.name, annotation_name)) + + # Determine the return annotation + return_annotation = signature.return_annotation + if return_annotation is inspect._empty: + outputs = "No return annotation" + else: + outputs = ( + return_annotation.__name__ + if hasattr(return_annotation, '__name__') + else str(return_annotation) + ) + + # Use the function's docstring as the description (default if None) + description = func.__doc__ or "No description provided." + + # The function name becomes the Tool name + name = func.__name__ + + # Return a new Tool instance + return Tool( + name=name, + description=description, + func=func, + arguments=arguments, + outputs=outputs + ) +``` + +
+ +Just to reiterate, with this decorator in place we can implement our tool like this: + +```python +@tool +def calculator(a: int, b: int) -> int: + """Multiply two integers.""" + return a * b + +print(calculator.to_string()) +``` + +And we can use the `Tool`'s `to_string` method to automatically retrieve a text suitable to be used as a tool description for an LLM: + +```text +Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int +``` + +The description is **injected** in the system prompt. Taking the example with which we started this section, here is how it would look like after replacing the `tools_description`: + +System prompt for tools + +In the [Actions](actions) section, we will learn more about how an Agent can **Call** this tool we just created. + +### Model Context Protocol (MCP): a unified tool interface + +Model Context Protocol (MCP) is an **open protocol** that standardizes how applications **provide tools to LLMs**. +MCP provides: + +- A growing list of pre-built integrations that your LLM can directly plug into +- The flexibility to switch between LLM providers and vendors +- Best practices for securing your data within your infrastructure + +This means that **any framework implementing MCP can leverage tools defined within the protocol**, eliminating the need to reimplement the same tool interface for each framework. + +If you want to dive deeper about MCP, you can check our [free MCP Course](https://huggingface.co/learn/mcp-course/). + +--- + +Tools play a crucial role in enhancing the capabilities of AI agents. + +To summarize, we learned: + +- *What Tools Are*: Functions that give LLMs extra capabilities, such as performing calculations or accessing external data. + +- *How to Define a Tool*: By providing a clear textual description, inputs, outputs, and a callable function. + +- *Why Tools Are Essential*: They enable Agents to overcome the limitations of static model training, handle real-time tasks, and perform specialized actions. + +Now, we can move on to the [Agent Workflow](agent-steps-and-structure) where you’ll see how an Agent observes, thinks, and acts. This **brings together everything we’ve covered so far** and sets the stage for creating your own fully functional AI Agent. + +But first, it's time for another short quiz! diff --git a/units/ja/unit1/tutorial.mdx b/units/ja/unit1/tutorial.mdx new file mode 100644 index 00000000..fa2dcda7 --- /dev/null +++ b/units/ja/unit1/tutorial.mdx @@ -0,0 +1,244 @@ +# Let's Create Our First Agent Using smolagents + +In the last section, we learned how we can create Agents from scratch using Python code, and we **saw just how tedious that process can be**. Fortunately, many Agent libraries simplify this work by **handling much of the heavy lifting for you**. + +In this tutorial, **you'll create your very first Agent** capable of performing actions such as image generation, web search, time zone checking and much more! + +You will also publish your agent **on a Hugging Face Space so you can share it with friends and colleagues**. + +Let's get started! + + +## What is smolagents? + +smolagents + +To make this Agent, we're going to use `smolagents`, a library that **provides a framework for developing your agents with ease**. + +This lightweight library is designed for simplicity, but it abstracts away much of the complexity of building an Agent, allowing you to focus on designing your agent's behavior. + +We're going to get deeper into smolagents in the next Unit. Meanwhile, you can also check this blog post or the library's repo in GitHub. + +In short, `smolagents` is a library that focuses on **codeAgent**, a kind of agent that performs **"Actions"** through code blocks, and then **"Observes"** results by executing the code. + +Here is an example of what we'll build! + +We provided our agent with an **Image generation tool** and asked it to generate an image of a cat. + +The agent inside `smolagents` is going to have the **same behaviors as the custom one we built previously**: it's going **to think, act and observe in cycle** until it reaches a final answer: + + + +Exciting, right? + +## Let's build our Agent! + +To start, duplicate this Space: https://huggingface.co/spaces/agents-course/First_agent_template +> Thanks to Aymeric for this template! 🙌 + + +Duplicating this space means **creating a local copy on your own profile**: +Duplicate + +After duplicating the Space, you'll need to add your Hugging Face API token so your agent can access the model API: + +1. First, get your Hugging Face token from [https://hf.co/settings/tokens](https://hf.co/settings/tokens) with permission for inference, if you don't already have one +2. Go to your duplicated Space and click on the **Settings** tab +3. Scroll down to the **Variables and Secrets** section and click **New Secret** +4. Create a secret with the name `HF_TOKEN` and paste your token as the value +5. Click **Save** to store your token securely + +Throughout this lesson, the only file you will need to modify is the (currently incomplete) **"app.py"**. You can see here the [original one in the template](https://huggingface.co/spaces/agents-course/First_agent_template/blob/main/app.py). To find yours, go to your copy of the space, then click the `Files` tab and then on `app.py` in the directory listing. + +Let's break down the code together: + +- The file begins with some simple but necessary library imports + +```python +from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, load_tool, tool +import datetime +import requests +import pytz +import yaml +``` + +As outlined earlier, we will directly use the **CodeAgent** class from **smolagents**. + + +### The Tools + +Now let's get into the tools! If you want a refresher about tools, don't hesitate to go back to the [Tools](tools) section of the course. + +```python +@tool +def my_custom_tool(arg1:str, arg2:int)-> str: # it's important to specify the return type + # Keep this format for the tool description / args description but feel free to modify the tool + """A tool that does nothing yet + Args: + arg1: the first argument + arg2: the second argument + """ + return "What magic will you build ?" + +@tool +def get_current_time_in_timezone(timezone: str) -> str: + """A tool that fetches the current local time in a specified timezone. + Args: + timezone: A string representing a valid timezone (e.g., 'America/New_York'). + """ + try: + # Create timezone object + tz = pytz.timezone(timezone) + # Get current time in that timezone + local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") + return f"The current local time in {timezone} is: {local_time}" + except Exception as e: + return f"Error fetching time for timezone '{timezone}': {str(e)}" +``` + + +The Tools are what we are encouraging you to build in this section! We give you two examples: + +1. A **non-working dummy Tool** that you can modify to make something useful. +2. An **actually working Tool** that gets the current time somewhere in the world. + +To define your tool it is important to: + +1. Provide input and output types for your function, like in `get_current_time_in_timezone(timezone: str) -> str:` +2. **A well formatted docstring**. `smolagents` is expecting all the arguments to have a **textual description in the docstring**. + +### The Agent + +It uses [`Qwen/Qwen2.5-Coder-32B-Instruct`](https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct) as the LLM engine. This is a very capable model that we'll access via the serverless API. + +```python +final_answer = FinalAnswerTool() +model = InferenceClientModel( + max_tokens=2096, + temperature=0.5, + model_id='Qwen/Qwen2.5-Coder-32B-Instruct', + custom_role_conversions=None, +) + +with open("prompts.yaml", 'r') as stream: + prompt_templates = yaml.safe_load(stream) + +# We're creating our CodeAgent +agent = CodeAgent( + model=model, + tools=[final_answer], # add your tools here (don't remove final_answer) + max_steps=6, + verbosity_level=1, + grammar=None, + planning_interval=None, + name=None, + description=None, + prompt_templates=prompt_templates +) + +GradioUI(agent).launch() +``` + +This Agent still uses the `InferenceClient` we saw in an earlier section behind the **InferenceClientModel** class! + +We will give more in-depth examples when we present the framework in Unit 2. For now, you need to focus on **adding new tools to the list of tools** using the `tools` parameter of your Agent. + +For example, you could use the `DuckDuckGoSearchTool` that was imported in the first line of the code, or you can examine the `image_generation_tool` that is loaded from the Hub later in the code. + +**Adding tools will give your agent new capabilities**, try to be creative here! + +### The System Prompt + +The agent's system prompt is stored in a separate `prompts.yaml` file. This file contains predefined instructions that guide the agent's behavior. + +Storing prompts in a YAML file allows for easy customization and reuse across different agents or use cases. + +You can check the [Space's file structure](https://huggingface.co/spaces/agents-course/First_agent_template/tree/main) to see where the `prompts.yaml` file is located and how it's organized within the project. + +The complete "app.py": + +```python +from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool +import datetime +import requests +import pytz +import yaml +from tools.final_answer import FinalAnswerTool + +from Gradio_UI import GradioUI + +# Below is an example of a tool that does nothing. Amaze us with your creativity! +@tool +def my_custom_tool(arg1:str, arg2:int)-> str: # it's important to specify the return type + # Keep this format for the tool description / args description but feel free to modify the tool + """A tool that does nothing yet + Args: + arg1: the first argument + arg2: the second argument + """ + return "What magic will you build ?" + +@tool +def get_current_time_in_timezone(timezone: str) -> str: + """A tool that fetches the current local time in a specified timezone. + Args: + timezone: A string representing a valid timezone (e.g., 'America/New_York'). + """ + try: + # Create timezone object + tz = pytz.timezone(timezone) + # Get current time in that timezone + local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") + return f"The current local time in {timezone} is: {local_time}" + except Exception as e: + return f"Error fetching time for timezone '{timezone}': {str(e)}" + + +final_answer = FinalAnswerTool() +model = InferenceClientModel( + max_tokens=2096, + temperature=0.5, + model_id='Qwen/Qwen2.5-Coder-32B-Instruct', + custom_role_conversions=None, +) + + +# Import tool from Hub +image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) + +# Load system prompt from prompt.yaml file +with open("prompts.yaml", 'r') as stream: + prompt_templates = yaml.safe_load(stream) + +agent = CodeAgent( + model=model, + tools=[final_answer], # add your tools here (don't remove final_answer) + max_steps=6, + verbosity_level=1, + grammar=None, + planning_interval=None, + name=None, + description=None, + prompt_templates=prompt_templates # Pass system prompt to CodeAgent +) + + +GradioUI(agent).launch() +``` + +Your **Goal** is to get familiar with the Space and the Agent. + +Currently, the agent in the template **does not use any tools, so try to provide it with some of the pre-made ones or even make some new tools yourself!** + +We are eagerly waiting for your amazing agents output in the discord channel **#agents-course-showcase**! + + +--- +Congratulations, you've built your first Agent! Don't hesitate to share it with your friends and colleagues. + +Since this is your first try, it's perfectly normal if it's a little buggy or slow. In future units, we'll learn how to build even better Agents. + +The best way to learn is to try, so don't hesitate to update it, add more tools, try with another model, etc. + +In the next section, you're going to fill the final Quiz and get your certificate! + diff --git a/units/ja/unit1/what-are-agents.mdx b/units/ja/unit1/what-are-agents.mdx new file mode 100644 index 00000000..7b9eeae9 --- /dev/null +++ b/units/ja/unit1/what-are-agents.mdx @@ -0,0 +1,159 @@ +## エージェントとは何か? + +Unit 1 planning + +このセクションが終了するまでに、エージェントの概念とそのAIにおけるさまざまな応用について理解できるようになります。 + +エージェントが何かを理解するために、まずはその基本的な定義から始めましょう。 + +## 全体像: アルフレッド・ザ・エージェント + +アルフレッドに会いましょう。アルフレッドは**エージェント**です。 + +This is Alfred + +アルフレッドが「アルフレッド、コーヒーをお願いします」といった**コマンドを受け取る**と想像してみてください。 + +I would like a coffee + +アルフレッドは**自然言語を理解する**ため、私たちのリクエストをすぐに把握します。 + +注文を満たす前に、アルフレッドは**推論と計画**に取り組み、必要な手順とツールを考え出します。 + +1. キッチンに行く +2. コーヒーメーカーを使う +3. コーヒーを淹れる +4. コーヒーを持ってくる + +Reason and plan + +計画ができたら、彼は**行動しなければなりません**。計画を実行するために、**彼は知っているツールのリストからツールを使用できます**。 + +この場合、コーヒーを作るために、彼はコーヒーメーカーを使います。彼はコーヒーメーカーを起動してコーヒーを淹れます。 + +Make coffee + +最後に、アルフレッドは淹れたてのコーヒーを私たちに持ってきます。 + +Bring coffee + +これがエージェントの基本的な流れです: **AIモデルが自然言語を理解し、推論と計画を行い、環境と対話してアクションを実行する**。 + +私たちはこれをエージェントと呼びます。なぜなら、エージェントには_エージェンシー(Agency)_、つまり環境と対話する能力があるからです。 + +Agent process + +## より正式に + +大局を把握したところで、より正確な定義を見てみましょう。 + +> エージェントとは、AIモデルを活用して環境と対話し、ユーザー定義の目的を達成するシステムです。推論、計画、およびアクションの実行(しばしば外部ツールを介して)を組み合わせてタスクを実行します。 + +エージェントは2つの主要な部分から成り立っていると考えてください。 + +1. **脳 (AI Model)** + +ここではすべての思考が行われます。AIモデルは**推論と計画を担当**します。 +状況に基づいて**どのアクションを取るかを決定**します。 + +2. **身体 (Capabilities and Tools)** + +この部分は、**エージェントが装備されているすべての機能**を表します。 + +**可能なアクションの範囲**は、エージェントが**装備しているもの**に依存します。たとえば、人間には翼がないため、「飛ぶ」**アクション**を実行することはできませんが、「歩く」、「走る」、「ジャンプする」、「つかむ」などの**アクション**を実行することはできます。 + +### "エージェンシー(Agency)"とは? + +この定義に従うと、エージェントはエージェンシーの増加する連続的な領域に存在します。 + +| エージェンシーレベル | 説明 | それが呼ばれるもの | 例 | +| --- | --- | --- | --- | +| ☆☆☆ | エージェントの出力はプログラムのフローに影響を与えない | シンプルプロセッサ | `process_llm_output(llm_response)` | +| ★☆☆ | エージェントの出力は基本的な制御フローを決定する | ルーター | `if llm_decision(): path_a() else: path_b()` | +| ★★☆ | エージェントの出力は関数の実行を決定する | ツールコーラー | `run_function(llm_chosen_tool, llm_chosen_args)` | +| ★★★ | エージェントの出力は反復とプログラムの継続を制御する | マルチステップエージェント | `while llm_should_continue(): execute_next_step()` | +| ★★★ | One agentic workflow can start another agentic workflow | Multi-Agent | `if llm_trigger(): execute_agent()` | + +表は[smolagents conceptual guide](https://huggingface.co/docs/smolagents/conceptual_guides/intro_agents)からのものです。 + +## どのようなAIモデルをエージェントに使用するか? + +最も一般的にエージェントで使用されるAIモデルは、LLM(大規模言語モデル)です。これは、**テキスト**を入力として受け取り、**テキスト**を出力します。 + +よく知られている例としては、**OpenAI**の**GPT4**、**Meta**の**LLama**、**Google**の**Gemini**などがあります。これらのモデルは膨大な量のテキストで訓練されており、一般化能力に優れています。LLMについては[次のセクション](what-are-llms)で詳しく学びます。 + + +エージェントのコアモデルとして、他の入力を受け入れるモデルを使用することも可能です。たとえば、画像を入力として理解するLLMのような**ビジョンランゲージモデル(VLM)**があります。今のところLLMに焦点を当て、後で他のオプションについて議論します。 + + +## AIはどのようにして環境に対して行動を起こすのか? + +LLMは素晴らしいモデルですが、**テキストを生成することしかできません**。 + +しかし、HuggingChatやChatGPTのような有名なチャットアプリに画像を生成するように依頼すると、彼らはそれを実行できます!これはどういうことでしょうか? + +その答えは、HuggingChat、ChatGPT、そして類似のアプリの開発者が、LLMが画像を生成するために使用できる追加機能(**ツール**と呼ばれる)を実装したことです。 + +
+Eiffel Brocolis +
HuggingChatで「エッフェル塔のブロッコリーの画像を生成して」と依頼した結果。
+
+ +私たちは[ツール](tools)セクションでツールについてもっと学びます。 + +## エージェントはどのようなタスクを実行できるのか? + +エージェントは、**ツール**を介して実装された任意のタスクを実行し、**アクション**を完了することができます。 + +たとえば、私がコンピュータ上で個人アシスタント(Siriのような)として機能するエージェントを書き、「今日の会議を延期するようにマネージャーにメールを送って」と依頼した場合、メールを送信するためのコードを提供できます。これは、エージェントがメールを送信する必要があるときに使用できる新しいツールになります。これをPythonで書くことができます。 + +```python +def send_message_to(recipient, message): + """Useful to send an e-mail message to a recipient""" + ... +``` + +LLMは、必要なときにツールを実行するためのコードを生成し、したがって目的のタスクを達成します。 + +```python +send_message_to("Manager", "Can we postpone today's meeting?") +``` + +ツールの設計は非常に重要であり、エージェントの品質に大きな影響を与えます。特定のタスクには、特別に作成されたツールが必要な場合がありますが、他のタスクは「web_search」のような汎用ツールで解決できるかもしれません。 + +> **アクションはツールとは異なる**ことに注意してください。たとえば、アクションは複数のツールを使用して完了することができます。 + +エージェントがその環境と対話できるようにすることは、**企業や個人の実際の使用を可能にします**。 + +### 例1: 個人用バーチャルアシスタント + +Siri、Alexa、Googleアシスタントなどのバーチャルアシスタントは、ユーザーのデジタル環境を使用して代理で対話する際にエージェントとして機能します。 + +ユーザーのクエリを受け取り、コンテキストを分析し、データベースから情報を取得し、応答を提供したり、リマインダーの設定、メッセージの送信、スマートデバイスの制御などのアクションを開始したりします。 + +### 例2: カスタマーサービスチャットボット + +多くの企業は、顧客と自然言語で対話するエージェントとしてチャットボットを展開しています。 + +これらのエージェントは、質問に答えたり、トラブルシューティングの手順を案内したり、内部データベースで問題を開いたり、取引を完了したりすることができます。 + +彼らの事前定義された目標には、ユーザー満足度の向上、待機時間の短縮、販売転換率の向上が含まれる場合があります。顧客と直接対話し、対話から学び、時間とともに応答を適応させることで、彼らはエージェントの基本原則を実証します。 + + +### 例3: ビデオゲームにおけるAIノンプレイヤーキャラクター + +LLMによって強化されたAIエージェントは、ノンプレイヤーキャラクター(NPC)をよりダイナミックで予測不可能にすることができます。 + +厳格な行動ツリーに従うのではなく、彼らは**文脈に応じて反応し、プレイヤーのインタラクションに適応し**、より微妙な対話を生成することができます。この柔軟性は、プレイヤーの行動に応じて進化する、より生き生きとした魅力的なキャラクターを作成するのに役立ちます。 + +--- + +最後に、エージェントはAIモデル(通常はLLM)をコア推論エンジンとして使用して、以下のことを行います: + +- **自然言語を理解する:** 人間の指示を意味のある方法で解釈し、応答します。 + +- **推論と計画:** 情報を分析し、意思決定を行い、問題を解決するための戦略を考案します。 + +- **環境と対話する:** 情報を収集し、アクションを実行し、そのアクションの結果を観察します。 + +これでエージェントについての理解が深まったと思いますので、短い非評価クイズで確認しましょう。その後、「エージェントの脳」である[LLMs](what-are-llms)に進みます。 diff --git a/units/ja/unit1/what-are-llms.mdx b/units/ja/unit1/what-are-llms.mdx new file mode 100644 index 00000000..41dbddce --- /dev/null +++ b/units/ja/unit1/what-are-llms.mdx @@ -0,0 +1,222 @@ +# LLMとは何か? + +Unit 1 planning + +前のセクションでは、各エージェントには**コアにAIモデルが必要であり、LLMがこの目的に最も一般的なAIモデルである**ことを学びました。 + +ここではLLMとは何か、そしてそれらがどのようにエージェントを支えるのかを学びます。 + +このセクションはLLMの使用に関する簡潔な技術的説明を提供します。より深く掘り下げたい場合は、無料の自然言語処理コースをチェックしてください。 + +## 大規模言語モデルとは? + +LLMは、**人間の言語を理解し生成することに優れたAIモデルの一種**です。膨大な量のテキストデータで訓練されており、言語のパターン、構造、さらにはニュアンスを学習することができます。これらのモデルは通常、数百万のパラメータで構成されています。 + +現在のほとんどのLLMは、**Transformerアーキテクチャに基づいて構築されています**。これは「Attention」アルゴリズムに基づく深層学習アーキテクチャであり、2018年にGoogleからBERTがリリースされて以来、注目を集めています。 + +
+Transformer +
Transformerの元のアーキテクチャはこのようになっており、左側にエンコーダー、右側にデコーダーがあります。
+
+ +Transformerには3つのタイプがあります: + +1. **エンコーダー(Encoders)** + エンコーダーベースのTransformerは、テキスト(または他のデータ)を入力として受け取り、そのテキストの密な表現(または埋め込み)を出力します。 + + - **例**: GoogleのBERT + - **ユースケース**: テキスト分類、セマンティック検索、固有表現認識 + - **典型的なサイズ**: 数百万のパラメータ + +2. **デコーダー(Decoders)** + デコーダーベースのTransformerは、**シーケンスを1トークンずつ完成させるために新しいトークンを生成することに焦点を当てています**。 + + - **例**: MetaのLlama + - **ユースケース**: テキスト生成、チャットボット、コード生成 + - **典型的なサイズ**: 数十億のパラメータ + +3. **Seq2Seq (Encoder–Decoder)** + シーケンス・ツー・シーケンスTransformerは、エンコーダーとデコーダーを_組み合わせた_ものです。エンコーダーは最初に入力シーケンスをコンテキスト表現に処理し、その後デコーダーが出力シーケンスを生成します。 + + - **例**: T5、BART + - **ユースケース**: 翻訳、要約、言い換え + - **典型的なサイズ**: 数百万のパラメータ + +大規模言語モデルは様々な形態がありますが、LLMは通常、数十億のパラメータを持つデコーダーベースのモデルです。以下は、最もよく知られているLLMの例です: + +| **モデル** | **プロバイダー** | +|-----------------------------------|-------------------------------------------| +| **Deepseek-R1** | DeepSeek | +| **GPT4** | OpenAI | +| **Llama 3** | Meta (Facebook AI Research) | +| **SmolLM2** | Hugging Face | +| **Gemma** | Google | +| **Mistral** | Mistral | + +LLMの基本的な原則はシンプルでありながら非常に効果的です: **その目的は、以前のトークンのシーケンスを考慮して次のトークンを予測することです**。 "トークン(token)"は、LLMが扱う情報の単位です。 "トークン"は"単語"のように考えることができますが、効率の理由からLLMは全体の単語を使用しません。 + +たとえば、英語には約600,000の単語があると推定されていますが、LLMは約32,000のトークンの語彙を持っているかもしれません(Llama 2の場合)。トークン化は、結合可能なサブワード単位で機能することがよくあります。 + +たとえば、"interest"と"ing"というトークンが結合されて"interesting"が形成されたり、"ed"が追加されて"interested"が形成されたりする様子を考えてみてください。 + +以下のインタラクティブなプレイグラウンドで、さまざまなトークナイザーを試すことができます: + + + +各LLMには、モデル固有の**特別なトークン**があります。LLMはこれらのトークンを使用して、生成の構造化されたコンポーネントを開いたり閉じたりします。たとえば、シーケンス、メッセージ、または応答の開始や終了を示すためです。さらに、モデルに渡す入力プロンプトも特別なトークンで構造化されています。その中で最も重要なのは、**End of sequence token (EOS)**です。 + +特別なトークンの形式は、モデルプロバイダーによって非常に多様です。 + +以下の表は、特別なトークンの多様性を示しています。 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ModelProviderEOS TokenFunctionality
GPT4OpenAI<|endoftext|>End of message text
Llama 3Meta (Facebook AI Research)<|eot_id|>End of sequence
Deepseek-R1DeepSeek<|end_of_sentence|>End of message text
SmolLM2Hugging Face<|im_end|>End of instruction or message
GemmaGoogle<end_of_turn>End of conversation turn
+ + + +特別なトークンを覚える必要はありませんが、特別なトークンの多様性とLLMのテキスト生成における役割を理解することが重要です。特別なトークンについてもっと知りたい場合は、モデルのHubリポジトリの設定を確認できます。たとえば、SmolLM2モデルの特別なトークンは、そのtokenizer_config.jsonで見つけることができます。 + + + +## トークン予測の理解 + +LLMは**自己回帰的(autoregressive)**であると言われています。つまり、**1回のパスからの出力が次のパスの入力となります**。このループは、モデルが次のトークンをEOSトークンと予測するまで続き、その時点でモデルは停止できます。 + +Visual Gif of autoregressive decoding + +言い換えると、LLMはEOSに到達するまでテキストをデコードします。しかし、単一のデコードループ中に何が起こるのでしょうか? + +プロセス全体はエージェントを学習する点においてはかなり技術的ですが、簡単な概要を以下に示します: + +- 入力テキストが**トークン化**されると、モデルはシーケンスの意味と各トークンの位置に関する情報をキャプチャする表現を計算します。 +- この表現がモデルに入力され、モデルはシーケンス内の次のトークンである可能性のある各トークンのスコアを出力します。 + +Visual Gif of decoding + +これらのスコアに基づいて、文を完成させるためのトークンを選択するための複数の戦略があります。 + +- 最も簡単なデコード戦略は、常に最大スコアのトークンを選択することです。 + +SmolLM2を使用してデコードプロセスを自分で操作できます。このSpaceで試してみてください(このモデルのEOSトークンは **<|im_end|>** ですので、デコードはそれに到達するまで続きます): + + + +- しかし、より高度なデコード戦略もあります。たとえば、*ビームサーチ*は、複数の候補シーケンスを探索して、個々のトークンが低いスコアを持っていても、合計スコアが最大のものを見つけます。 + + + +デコードについてもっと知りたい場合は、[NLPコース](https://huggingface.co/learn/nlp-course)をチェックしてください。 + +## Attention is all you need + +Transformerアーキテクチャの重要な側面は**Attention**です。次の単語を予測する際、文中のすべての単語が同じ重要性を持つわけではありません。たとえば、文 *"The capital of France is ..."* では、「France」や「capital」といった単語が最も意味を持ちます。 + +Visual Gif of Attention + +このプロセスは、次のトークンを予測するために最も関連性の高い単語を特定するものであり、非常に効果的であることが証明されています。 + +LLMの基本原則である「次のトークンを予測する」という点は、GPT-2以降一貫していますが、ニューラルネットワークのスケーリングや、注意メカニズムをより長いシーケンスに対応させるための重要な進展がありました。 + +LLMと対話したことがある場合、*コンテキスト長(context length)*という用語に馴染みがあるかもしれません。これは、LLMが処理できる最大トークン数と、LLMが持つ最大の*注意スパン(attention span)*を指します。 + +## プロンプトを工夫することが重要 + +LLMの唯一の仕事は、すべての入力トークンを見て次のトークンを予測し、どのトークンが「重要」であるかを選択することです。そのため、入力シーケンスの表現は非常に重要です。 + +LLMに提供する入力シーケンスは _プロンプト(prompt)_ と呼ばれます。プロンプトを慎重に設計することで、LLMの生成を**望ましい出力に導く**ことが容易になります。 + +## LLMはどのように学習するのか? + +LLMは、大規模なテキストデータセットで学習され、自己教師ありまたはマスク付き言語モデルの目的を通じて、シーケンス内の次の単語を予測する方法を学びます。 + +この教師なし学習から、モデルは言語の構造と**テキスト内の基本的なパターンを学習し、モデルが見えないデータに一般化できるようにします**。 + +この初期の_事前学習_の後、LLMは特定のタスクを実行するために、教師あり学習の目的で微調整されることがあります。たとえば、いくつかのモデルは会話構造やツールの使用のために訓練されている一方で、他のモデルは分類やコード生成に焦点を当てています。 + +## LLMはどのように使用できるのか? + +主に2つのオプションがあります: + +1. **ローカルで実行** (十分なハードウェアがある場合)。 + +2. **クラウド/APIを使用** (例: Hugging Face Serverless Inference APIを介して)。 + +このコース全体を通じて、主にHugging Face HubのAPIを介してモデルを使用します。後で、これらのモデルをローカルのハードウェアで実行する方法を探ります。 + + +## LLMはAIエージェントでどのように使用されるのか? + +LLMはAIエージェントの重要なコンポーネントであり、**人間の言語を理解し生成するための基盤を提供します**。 + +LLMはユーザーの指示を解釈し、会話の文脈を維持し、計画を定義し、使用するツールを決定することができます。 + +このユニットでは、これらのステップをより詳細に探りますが、今のところ理解しておくべきことは、LLMが**エージェントの脳**であるということです。 + +--- + +かなり多くの情報でしたね!LLMとは何か、どのように機能するのか、AIエージェントを支える役割について基本を学びました。 + +LLMの詳細をさらに深く掘り下げたい場合は、ぜひ無料のNLPコースをチェックしてください。 + +LLMの仕組みを理解したところで、次は**会話の文脈におけるLLMの生成の構造**を見てみましょう。 + +このノートブックを実行するには、**Hugging Faceトークン**が必要です。このトークンは、https://hf.co/settings/tokensから取得できます。 + +Jupyter Notebooksを実行する方法の詳細については、Hugging Face HubのJupyter Notebooksをチェックしてください。 + +また、Meta Llamaモデルへのアクセスをリクエストする必要があります。