text
stringlengths
55
456k
metadata
dict
# Overview This repository contains a lightweight library for evaluating language models. We are open sourcing it so we can be transparent about the accuracy numbers we're publishing alongside our latest models. ## Benchmark Results | Model | Prompt | MMLU | GPQA | MATH | HumanEval | MGSM[^5] | DROP[^5]<br>(F1, 3-shot) | SimpleQA |:----------------------------:|:-------------:|:------:|:------:|:------:|:---------:|:------:|:--------------------------:|:---------:| | **o1** | | | | MATH-500[^6] | | | | | o1-preview | n/a[^7] | 90.8 | 73.3 | 85.5 | **`92.4`** | 90.8 | 74.8 | **`42.4`** | | o1-mini | n/a | 85.2 | 60.0 | 90.0 | **`92.4`** | 89.9 | 83.9 | 7.6 | | o1 (work in progress) | n/a | **`92.3`** | **`77.3`** | **`94.8`** | n/a | n/a | n/a | n/a | **GPT-4o** | | | | | | | | | gpt-4o-2024-08-06 | assistant[^2] | 88.7 | 53.1 | 75.9 | 90.2 | 90.0 | 79.8 | 40.1 | | gpt-4o-2024-05-13 | assistant | 87.2 | 49.9 | 76.6 | 91.0 | 89.9 | 83.7 | 39.0 | | gpt-4o-mini-2024-07-18 | assistant | 82.0 | 40.2 | 70.2 | 87.2 | 87.0 | 79.7 | 9.5 | | **GPT-4 Turbo and GPT-4** | | | | | | | | | gpt-4-turbo-2024-04-09 | assistant | 86.7 | 49.3 | 73.4 | 88.2 | 89.6 | 86.0 | 24.2 | | gpt-4-0125-preview | assistant | 85.4 | 41.4 | 64.5 | 86.6 | 85.1 | 81.5 | n/a | gpt-4-1106-preview | assistant | 84.7 | 42.5 | 64.3 | 83.7 | 87.1 | 83.2 | n/a | **Other Models (Reported)** | | | | | | | | | [Claude 3.5 Sonnet](https://www.anthropic.com/news/claude-3-5-sonnet) | unknown | 88.3 | 59.4 | 71.1 | 92.0 | **`91.6`** | **`87.1`** | 28.9 | | [Claude 3 Opus](https://www.anthropic.com/news/claude-3-family) | unknown | 86.8 | 50.4 | 60.1 | 84.9 | 90.7 | 83.1 | 23.5 | | [Llama 3.1 405b](https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/MODEL_CARD.md) | unknown | 88.6 | 50.7 | 73.8 | 89.0 | **`91.6`** | 84.8 | n/a | [Llama 3.1 70b](https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/MODEL_CARD.md) | unknown | 82.0 | 41.7 | 68.0 | 80.5 | 86.9 | 79.6 | n/a | [Llama 3.1 8b](https://github.com/meta-llama/llama-models/blob/main/models/llama3_1/MODEL_CARD.md) | unknown | 68.4 | 30.4 | 51.9 | 72.6 | 68.9 | 59.5 | n/a | [Grok 2](https://x.ai/blog/grok-2) | unknown | 87.5 | 56.0 | 76.1 | 88.4 | n/a | n/a | n/a | [Grok 2 mini](https://x.ai/blog/grok-2) | unknown | 86.2 | 51.0 | 73.0 | 85.7 | n/a | n/a | n/a | [Gemini 1.0 Ultra](https://goo.gle/GeminiV1-5) | unknown | 83.7 | n/a | 53.2 | 74.4 | 79.0 | 82.4 | n/a | [Gemini 1.5 Pro](https://goo.gle/GeminiV1-5) | unknown | 81.9 | n/a | 58.5 | 71.9 | 88.7 | 78.9 | n/a | [Gemini 1.5 Flash](https://goo.gle/GeminiV1-5) | unknown | 77.9 | 38.6 | 40.9 | 71.5 | 75.5 | 78.4 | n/a ## Background Evals are sensitive to prompting, and there's significant variation in the formulations used in recent publications and libraries. Some use few-shot prompts or role playing prompts ("You are an expert software programmer..."). These approaches are carryovers from evaluating *base models* (rather than instruction/chat-tuned models) and from models that were worse at following instructions. For this library, we are emphasizing the *zero-shot, chain-of-thought* setting, with simple instructions like "Solve the following multiple choice problem". We believe that this prompting technique is a better reflection of the models' performance in realistic usage. **We will not be actively maintaining this repository and monitoring PRs and Issues.** In particular, we're not accepting new evals. Here are the changes we might accept. - Bug fixes (hopefully not needed!) - Adding adapters for new models - Adding new rows to the table below with eval results, given new models and new system prompts. This repository is NOT intended as a replacement for https://github.com/openai/evals, which is designed to be a comprehensive collection of a large number of evals. ## Evals This repository currently contains the following evals: - MMLU: Measuring Massive Multitask Language Understanding, reference: https://arxiv.org/abs/2009.03300, https://github.com/hendrycks/test, [MIT License](https://github.com/hendrycks/test/blob/master/LICENSE) - MATH: Measuring Mathematical Problem Solving With the MATH Dataset, reference: https://arxiv.org/abs/2103.03874, https://github.com/hendrycks/math, [MIT License](https://github.com/idavidrein/gpqa/blob/main/LICENSE) - GPQA: A Graduate-Level Google-Proof Q&A Benchmark, reference: https://arxiv.org/abs/2311.12022, https://github.com/idavidrein/gpqa/, [MIT License](https://github.com/idavidrein/gpqa/blob/main/LICENSE) - DROP: A Reading Comprehension Benchmark Requiring Discrete Reasoning Over Paragraphs, reference: https://arxiv.org/abs/1903.00161, https://allenai.org/data/drop, [Apache License 2.0](https://github.com/allenai/allennlp-models/blob/main/LICENSE) - MGSM: Multilingual Grade School Math Benchmark (MGSM), Language Models are Multilingual Chain-of-Thought Reasoners, reference: https://arxiv.org/abs/2210.03057, https://github.com/google-research/url-nlp, [Creative Commons Attribution 4.0 International Public License (CC-BY)](https://github.com/google-research/url-nlp/blob/main/LICENSE) - HumanEval: Evaluating Large Language Models Trained on Code, reference https://arxiv.org/abs/2107.03374, https://github.com/openai/human-eval, [MIT License](https://github.com/openai/human-eval/blob/master/LICENSE) ## Samplers We have implemented sampling interfaces for the following language model APIs: - OpenAI: https://platform.openai.com/docs/overview - Claude: https://www.anthropic.com/api Make sure to set the `*_API_KEY` environment variables before using these APIs. ## Setup Due to the optional dependencies, we're not providing a unified setup mechanism. Instead, we're providing instructions for each eval and sampler. For [HumanEval](https://github.com/openai/human-eval/) (python programming) ```bash git clone https://github.com/openai/human-eval pip install -e human-eval ``` For the [OpenAI API](https://pypi.org/project/openai/): ```bash pip install openai ``` For the [Anthropic API](https://docs.anthropic.com/claude/docs/quickstart-guide): ```bash pip install anthropic ``` ## Demo ```bash python -m simple-evals.demo ``` This will launch evaluations through the OpenAI API. ## Notes [^1]:chatgpt system message: "You are ChatGPT, a large language model trained by OpenAI, based on the GPT-4 architecture.\nKnowledge cutoff: 2023-12\nCurrent date: 2024-04-01" [^2]:assistant system message in [OpenAI API doc](https://platform.openai.com/docs/api-reference/introduction): "You are a helpful assistant." . [^3]:claude-3 empty system message: suggested by Anthropic API doc, and we have done limited experiments due to [rate limit](https://docs.anthropic.com/claude/reference/rate-limits) issues, but we welcome PRs with alternative choices. [^4]:claude-3 lmsys system message: system message in LMSYS [Fast-chat open source code](https://github.com/lm-sys/FastChat/blob/7899355ebe32117fdae83985cf8ee476d2f4243f/fastchat/conversation.py#L894): "The assistant is Claude, created by Anthropic. The current date is {{currentDateTime}}. Claude's knowledge base was last updated ... ". We have done limited experiments due to [rate limit](https://docs.anthropic.com/claude/reference/rate-limits) issues, but we welcome PRs with alternative choices. [^5]:We believe these evals are saturated for our newer models, but are reporting them for completeness. [^6]:For o1 models, we evaluate on [MATH-500](https://github.com/openai/prm800k/tree/main/prm800k/math_splits), which is a newer, IID version of MATH. [^7]:o1 models do not support using a system prompt. ## Legal Stuff By contributing to evals, you are agreeing to make your evaluation logic and data under the same MIT license as this repository. You must have adequate rights to upload any data used in an eval. OpenAI reserves the right to use this data in future service improvements to our product. Contributions to OpenAI evals will be subject to our usual Usage Policies: https://platform.openai.com/docs/usage-policies.
{ "source": "xjdr-alt/entropix", "title": "evals/README.md", "url": "https://github.com/xjdr-alt/entropix/blob/main/evals/README.md", "date": "2024-10-03T01:02:51", "stars": 3320, "description": "Entropy Based Sampling and Parallel CoT Decoding ", "file_size": 9067 }
# Multilingual MMLU Benchmark Results To evaluate multilingual performance, we translated MMLU’s test set into 14 languages using professional human translators. Relying on human translators for this evaluation increases confidence in the accuracy of the translations, especially for low-resource languages like Yoruba. ## Results | Language | o1-preview | gpt-4o-2024-08-06 | o1-mini | gpt-4o-mini-2024-07-18 | | :----------------------: | :--------: | :---------------: | :--------: | :--------------------: | | Arabic | **0.8821** | 0.8155 | **0.7945** | 0.7089 | | Bengali | **0.8622** | 0.8007 | **0.7725** | 0.6577 | | Chinese (Simplified) | **0.8800** | 0.8335 | **0.8180** | 0.7305 | | English (not translated) | **0.9080** | 0.8870 | **0.8520** | 0.8200 | | French | **0.8861** | 0.8437 | **0.8212** | 0.7659 | | German | **0.8573** | 0.8292 | **0.8122** | 0.7431 | | Hindi | **0.8782** | 0.8061 | **0.7887** | 0.6916 | | Indonesian | **0.8821** | 0.8344 | **0.8174** | 0.7452 | | Italian | **0.8872** | 0.8435 | **0.8222** | 0.7640 | | Japanese | **0.8788** | 0.8287 | **0.8129** | 0.7255 | | Korean | **0.8815** | 0.8262 | **0.8020** | 0.7203 | | Portuguese (Brazil) | **0.8859** | 0.8427 | **0.8243** | 0.7677 | | Spanish | **0.8893** | 0.8493 | **0.8303** | 0.7737 | | Swahili | **0.8479** | 0.7708 | **0.7015** | 0.6191 | | Yoruba | **0.7373** | 0.6195 | **0.5807** | 0.4583 | These results can be reproduced by running ```bash python -m simple-evals.run_multilingual_mmlu ```
{ "source": "xjdr-alt/entropix", "title": "evals/multilingual_mmlu_benchmark_results.md", "url": "https://github.com/xjdr-alt/entropix/blob/main/evals/multilingual_mmlu_benchmark_results.md", "date": "2024-10-03T01:02:51", "stars": 3320, "description": "Entropy Based Sampling and Parallel CoT Decoding ", "file_size": 2135 }
# Frontend bun install bun run dev inspired by: https://github.com/anthropics/anthropic-quickstarts/tree/main/customer-support-agent trying to copy: claude.ai some inspiration from: https://github.com/Porter97/monaco-copilot-demo
{ "source": "xjdr-alt/entropix", "title": "ui/README.md", "url": "https://github.com/xjdr-alt/entropix/blob/main/ui/README.md", "date": "2024-10-03T01:02:51", "stars": 3320, "description": "Entropy Based Sampling and Parallel CoT Decoding ", "file_size": 233 }
# TODO I somewhat hastily removed a bunch of backend code to get this pushed, so the current repo is in kind of rough shape. It runs, but its all stubbed out with mock data. We more or less need to make everything all over again. This is the initial TODO list but we will add to it as we think of things. ## REPO - Clean up repo. I am not a front end developer and it shows. Update the ui folder to best practices while still using bun, shadcn, next and tailwind - Storybook, jest, etc? This is probably too much but a subset might be useful - automation, piplines, dockerfiles, etc ## UI - Markdown rendering in the MessageArea. Make sure we are using rehype and remark properly. Make sure we have the proper code theme based on the selected app theme - latex rendering - image rendering - Fix HTML / React Artifact rendering. Had to rip out the old code, so we need to mostly make this from scratch - Wire up right sidebar to properly handle the artifacts - For now hook up pyodide or something like https://github.com/cohere-ai/cohere-terrarium to run python code to start. I will port over the real code-interpreter at some point in the future - Hook up play button to python interpreter / HTML Viewer - Hook up CoT parsing and wire it up to the logs tab in the right sidebar OR repurpose the LeftSidebar for CoT viewing - Hook up Sidebar to either LocalDB, IndexDB or set up docker containers to run postgres (this probably means Drizzle, ughhhh....) to preserve chat history - Hook up Sidebar search - Port over or make new keyboard shortcuts - Create new conversation forking logic and UI. Old forking logic and UI were removed (modal editor was kept) but this is by far one of the most important things to get right - Visualize entropy / varent via shadcn charts / color the text on the screen - add shadcn dashboard-03 (the playground) back in for not Claude.ai style conversations ## Editor - I'm pretty sure i'm not doing Monaco as well as it can be done. Plugins, themes, etc - do something like https://github.com/Porter97/monaco-copilot-demo with base for completion - make it work like OAI canvas where you can ask for edits at point - Make sure Modal Editor and Artifact Code Editor both work but do not rely on eachother, cause ModalEditor needs to be simple ## Backend - Make a simple SSE client / server to hook up to Entropix generate loop - Create tool parser for: - Brave - iPython - Image
{ "source": "xjdr-alt/entropix", "title": "ui/TODO.md", "url": "https://github.com/xjdr-alt/entropix/blob/main/ui/TODO.md", "date": "2024-10-03T01:02:51", "stars": 3320, "description": "Entropy Based Sampling and Parallel CoT Decoding ", "file_size": 2430 }
# HumanEval: Hand-Written Evaluation Set This is an evaluation harness for the HumanEval problem solving dataset described in the paper "[Evaluating Large Language Models Trained on Code](https://arxiv.org/abs/2107.03374)". ## Installation Make sure to use python 3.7 or later: ``` $ conda create -n codex python=3.7 $ conda activate codex ``` Check out and install this repository: ``` $ git clone https://github.com/openai/human-eval $ pip install -e human-eval ``` ## Usage **This program exists to run untrusted model-generated code. Users are strongly encouraged not to do so outside of a robust security sandbox. The [execution call](https://github.com/openai/human-eval/blob/master/human_eval/execution.py#L48-L58) in `execution.py` is deliberately commented out to ensure users read this disclaimer before running code in a potentially unsafe manner. See the comment in `execution.py` for more information and instructions.** After following the above instructions to enable execution, generate samples and save them in the following JSON Lines (jsonl) format, where each sample is formatted into a single line like so: ``` {"task_id": "Corresponding HumanEval task ID", "completion": "Completion only without the prompt"} ``` We provide `example_problem.jsonl` and `example_solutions.jsonl` under `data` to illustrate the format and help with debugging. Here is nearly functional example code (you just have to provide `generate_one_completion` to make it work) that saves generated completions to `samples.jsonl`. ``` from human_eval.data import write_jsonl, read_problems problems = read_problems() num_samples_per_task = 200 samples = [ dict(task_id=task_id, completion=generate_one_completion(problems[task_id]["prompt"])) for task_id in problems for _ in range(num_samples_per_task) ] write_jsonl("samples.jsonl", samples) ``` To evaluate the samples, run ``` $ evaluate_functional_correctness samples.jsonl Reading samples... 32800it [00:01, 23787.50it/s] Running test suites... 100%|...| 32800/32800 [16:11<00:00, 33.76it/s] Writing results to samples.jsonl_results.jsonl... 100%|...| 32800/32800 [00:00<00:00, 42876.84it/s] {'pass@1': ..., 'pass@10': ..., 'pass@100': ...} ``` This script provides more fine-grained information in a new file ending in `<input_path>_results.jsonl`. Each row now contains whether the completion `passed` along with the execution `result` which is one of "passed", "timed out", or "failed". As a quick sanity-check, the example samples should yield 0.5 pass@1. ``` $ evaluate_functional_correctness data/example_samples.jsonl --problem_file=data/example_problem.jsonl Reading samples... 6it [00:00, 3397.11it/s] Running example suites... 100%|...| 6/6 [00:03<00:00, 1.96it/s] Writing results to data/example_samples.jsonl_results.jsonl... 100%|...| 6/6 [00:00<00:00, 6148.50it/s] {'pass@1': 0.4999999999999999} ``` Because there is no unbiased way of estimating pass@k when there are fewer samples than k, the script does not evaluate pass@k for these cases. To evaluate with other k values, pass `--k=<comma-separated-values-here>`. For other options, see ``` $ evaluate_functional_correctness --help ``` However, we recommend that you use the default values for the rest. ## Known Issues While evaluation uses very little memory, you might see the following error message when the system is running out of RAM. Since this may cause some correct programs to fail, we recommend that you free some memory and try again. ``` malloc: can't allocate region ``` ## Citation Please cite using the following bibtex entry: ``` @article{chen2021codex, title={Evaluating Large Language Models Trained on Code}, author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser and Mohammad Bavarian and Clemens Winter and Philippe Tillet and Felipe Petroski Such and Dave Cummings and Matthias Plappert and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain and William Saunders and Christopher Hesse and Andrew N. Carr and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba}, year={2021}, eprint={2107.03374}, archivePrefix={arXiv}, primaryClass={cs.LG} } ```
{ "source": "xjdr-alt/entropix", "title": "evals/human-eval/README.md", "url": "https://github.com/xjdr-alt/entropix/blob/main/evals/human-eval/README.md", "date": "2024-10-03T01:02:51", "stars": 3320, "description": "Entropy Based Sampling and Parallel CoT Decoding ", "file_size": 4847 }
# Microsoft Open Source Code of Conduct This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). Resources: - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) - Contact [[email protected]](mailto:[email protected]) with questions or concerns
{ "source": "microsoft/ai-agents-for-beginners", "title": "CODE_OF_CONDUCT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/CODE_OF_CONDUCT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 443 }
# AI Agents for Beginners - A Course ![Generative AI For Beginners](./images/repo-thumbnail.png) ## 10 Lessons teaching everything you need to know to start building AI Agents [![GitHub license](https://img.shields.io/github/license/microsoft/ai-agents-for-beginners.svg)](https://github.com/microsoft/ai-agents-for-beginners/blob/master/LICENSE?WT.mc_id=academic-105485-koreyst) [![GitHub contributors](https://img.shields.io/github/contributors/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/graphs/contributors/?WT.mc_id=academic-105485-koreyst) [![GitHub issues](https://img.shields.io/github/issues/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/issues/?WT.mc_id=academic-105485-koreyst) [![GitHub pull-requests](https://img.shields.io/github/issues-pr/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/pulls/?WT.mc_id=academic-105485-koreyst) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com?WT.mc_id=academic-105485-koreyst) [![GitHub watchers](https://img.shields.io/github/watchers/microsoft/ai-agents-for-beginners.svg?style=social&label=Watch)](https://GitHub.com/microsoft/ai-agents-for-beginners/watchers/?WT.mc_id=academic-105485-koreyst) [![GitHub forks](https://img.shields.io/github/forks/microsoft/ai-agents-for-beginners.svg?style=social&label=Fork)](https://GitHub.com/microsoft/ai-agents-for-beginners/network/?WT.mc_id=academic-105485-koreyst) [![GitHub stars](https://img.shields.io/github/stars/microsoft/ai-agents-for-beginners.svg?style=social&label=Star)](https://GitHub.com/microsoft/ai-agents-for-beginners/stargazers/?WT.mc_id=academic-105485-koreyst) [![Azure AI Discord](https://dcbadge.limes.pink/api/server/kzRShWzttr)](https://discord.gg/kzRShWzttr) ## 🌱 Getting Started This course has 10 lessons covering the fundamentals of building AI Agents. Each lesson covers its own topic so start wherever you like! There is multi-language support for this course. Go to our [available languages here](#-multi-language-support). If this is your first time building with Generative AI models, check out our [Generative AI For Beginners](https://aka.ms/genai-beginners) course, which includes 21 lessons on building with GenAI. Don't forget to [star (🌟) this repo](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars?WT.mc_id=academic-105485-koreyst) and [fork this repo](https://github.com/microsoft/ai-agents-for-beginners/fork) to run the code. ### What You Need Each lesson in this course includes code examples, which can be found in the code_samples folder. You can [fork this repo](https://github.com/microsoft/ai-agents-for-beginners/fork) to create your own copy. The code example in these exercise, utilise Azure AI Foundry and GitHub Model Catalogs for interacting with Language Models: - [Github Models](https://aka.ms/ai-agents-beginners/github-models) - Free / Limited - [Azure AI Foundry](https://aka.ms/ai-agents-beginners/ai-foundry) - Azure Account Required This course also uses the following AI Agent frameworks and services from Microsoft: - [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service) - [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) - [AutoGen](https://aka.ms/ai-agents/autogen) For more information on running the code for this course, go to the [Course Setup](./00-course-setup/README.md). ## 🙏 Want to help? Do you have suggestions or found spelling or code errors? [Raise an issue](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst) or [Create a pull request](https://github.com/microsoft/ai-agents-for-beginners/pulls?WT.mc_id=academic-105485-koreyst) If you get stuck or have any questions about bulding AI Agents, join our [Azure AI Community Discord](https://discord.gg/kzRShWzttr). ## 📂 Each lesson includes - A written lesson located in the README (Videos Coming March 2025) - Python code samples supporting Azure AI Foundry and Github Models (Free) - Links to extra resources to continue your learning ## 🗃️ Lessons | **Lesson** | **Link** | |----------------------------------------|--------------------------------------------| | Intro to AI Agents and Use Cases | [Link](./01-intro-to-ai-agents/README.md) | | Exploring Agentic Frameworks | [Link](./02-explore-agentic-frameworks/README.md) | | Understanding Agentic Design Patterns | [Link](./03-agentic-design-patterns/README.md) | | Tool Use Design Pattern | [Link](./04-tool-use/README.md) | | Agentic RAG | [Link](./05-agentic-rag/README.md) | | Building Trustworty AI Agents | [Link](./06-building-trustworthy-agents/README.md) | | Planning Design Pattern | [Link](./07-planning-design/README.md) | | Multi-Agent Design Pattern | [Link](./08-multi-agent/README.md) | | Metacognition Design Pattern | [Link](./09-metacognition/README.md) | | AI Agents in Production | [Link](./10-ai-agents-production/README.md) | ## 🌐 Multi-Language Support | Language | Code | Link to Translated README | Last Updated | |----------------------|------|---------------------------------------------------------|--------------| | Chinese (Simplified) | zh | [Chinese Translation](./translations/zh/README.md) | 2025-02-13 | | Chinese (Traditional)| tw | [Chinese Translation](./translations/tw/README.md) | 2025-02-13 | | Chinese (Hong Kong) | hk | [Chinese (Hong Kong) Translation](./translations/hk/README.md) | 2025-02-13 | | French | fr | [French Translation](./translations/fr/README.md) | 2025-02-13 | | Japanese | ja | [Japanese Translation](./translations/ja/README.md) | 2025-02-13 | | Korean | ko | [Korean Translation](./translations/ko/README.md) | 2025-02-13 | | Portuguese | pt | [Portuguese Translation](./translations/pt/README.md) | 2025-02-13 | | Spanish | es | [Spanish Translation](./translations/es/README.md) | 2025-02-13 | | German | de | [German Translation](./translations/de/README.md) | 2025-02-13 | ## 🎒 Other Courses Our team produces other courses! Check out: - [**NEW** Generative AI for Beginners using .NET](https://github.com/microsoft/Generative-AI-for-beginners-dotnet?WT.mc_id=academic-105485-koreyst) - [Generative AI for Beginners](https://github.com/microsoft/generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) - [ML for Beginners](https://aka.ms/ml-beginners?WT.mc_id=academic-105485-koreyst) - [Data Science for Beginners](https://aka.ms/datascience-beginners?WT.mc_id=academic-105485-koreyst) - [AI for Beginners](https://aka.ms/ai-beginners?WT.mc_id=academic-105485-koreyst) - [Cybersecurity for Beginners](https://github.com/microsoft/Security-101??WT.mc_id=academic-96948-sayoung) - [Web Dev for Beginners](https://aka.ms/webdev-beginners?WT.mc_id=academic-105485-koreyst) - [IoT for Beginners](https://aka.ms/iot-beginners?WT.mc_id=academic-105485-koreyst) - [XR Development for Beginners](https://github.com/microsoft/xr-development-for-beginners?WT.mc_id=academic-105485-koreyst) - [Mastering GitHub Copilot for AI Paired Programming](https://aka.ms/GitHubCopilotAI?WT.mc_id=academic-105485-koreyst) - [Mastering GitHub Copilot for C#/.NET Developers](https://github.com/microsoft/mastering-github-copilot-for-dotnet-csharp-developers?WT.mc_id=academic-105485-koreyst) - [Choose Your Own Copilot Adventure](https://github.com/microsoft/CopilotAdventures?WT.mc_id=academic-105485-koreyst) ## Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit <https://cla.opensource.microsoft.com>. When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [[email protected]](mailto:[email protected]) with any additional questions or comments. ## Trademarks This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft trademarks or logos is subject to and must follow [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general). Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. Any use of third-party trademarks or logos is subject to those third-parties' policies.
{ "source": "microsoft/ai-agents-for-beginners", "title": "README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 9462 }
<!-- BEGIN MICROSOFT SECURITY.MD V0.0.9 BLOCK --> # Security Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) and [Xamarin](https://github.com/xamarin). If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below. ## Reporting Security Issues **Please do not report security vulnerabilities through public GitHub issues.** Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report). If you prefer to submit without logging in, send email to [[email protected]](mailto:[email protected]). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp). You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) * Full paths of source file(s) related to the manifestation of the issue * The location of the affected source code (tag/branch/commit or direct URL) * Any special configuration required to reproduce the issue * Step-by-step instructions to reproduce the issue * Proof-of-concept or exploit code (if possible) * Impact of the issue, including how an attacker might exploit the issue This information will help us triage your report more quickly. If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs. ## Preferred Languages We prefer all communications to be in English. ## Policy Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd). <!-- END MICROSOFT SECURITY.MD BLOCK -->
{ "source": "microsoft/ai-agents-for-beginners", "title": "SECURITY.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/SECURITY.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 2640 }
# TODO: The maintainer of this repo has not yet edited this file **REPO OWNER**: Do you want Customer Service & Support (CSS) support for this product/project? - **No CSS support:** Fill out this template with information about how to file issues and get help. - **Yes CSS support:** Fill out an intake form at [aka.ms/onboardsupport](https://aka.ms/onboardsupport). CSS will work with/help you to determine next steps. - **Not sure?** Fill out an intake as though the answer were "Yes". CSS will help you decide. *Then remove this first heading from this SUPPORT.MD file before publishing your repo.* ## Support ## How to file issues and get help This project uses GitHub Issues to track bugs and feature requests. Please search the existing issues before filing new issues to avoid duplicates. For new issues, file your bug or feature request as a new Issue. For help and questions about using this project, please **REPO MAINTAINER: INSERT INSTRUCTIONS HERE FOR HOW TO ENGAGE REPO OWNERS OR COMMUNITY FOR HELP. COULD BE A STACK OVERFLOW TAG OR OTHER CHANNEL. WHERE WILL YOU HELP PEOPLE?**. ## Microsoft Support Policy Support for this **PROJECT or PRODUCT** is limited to the resources listed above.
{ "source": "microsoft/ai-agents-for-beginners", "title": "SUPPORT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/SUPPORT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1240 }
# Course Setup ## Introduction This lesson will cover how to run the code samples of this course. ## Requirements - A GitHub Account - Python 3.12+ ## Clone or Fork this Repo To begin, please clone or fork the GitHub Repository. This will make your own version of the course material so that you can run, test and tweak the code! This can be done by clicking link to <a href="https://github.com/microsoft/ai-agents-for-beginners/fork" target="_blank">fork the repo</a> You should now have your own forked version of this course in the following link: ![Forked Repo](./images/forked-repo.png) ## Retrieve Your GitHub Personal Access Token (PAT) Currently this course uses the Github Models Marketplace to offer free access to Large Language Models(LLMs) that will be used to create AI Agents. To access this service, you will need to create a GitHub Personal Access Token. This can be done by going to your <a href="https://github.com/settings/personal-access-tokens" target="_blank">Personal Access Tokens settings</a> in your GitHub Account. Select the `Fine-grained tokens` options on the left side of your screen. Then select `Generate new token`. ![Generate Token](./images/generate-token.png) Copy your new token that you have just created. You will now add this to your `.env` file included in this course. ## Add this to your Environment Variables To create your `.env` file run the following command in your terminal: ```bash cp .env.example .env ``` This will copy the example file and create a `.env` in your directory. Open that file and paste the token you created into the `GITHUB_TOKEN=` field of the .env file. ## Install Required Packages To ensure you have all the required Python packages to run the code, run the following command into your terminal. We recommend creating a Python virtual environment to avoid any conflicts and issues. ```bash pip install -r requirements.txt ``` This should install the required Python packages. You are now ready to run the code of this code, happy learning more about the world of AI Agents! If you have any issues running this setup, hop into our <a href="https://discord.gg/kzRShWzttr" target="_blank">Azure AI Community Discord</a> or <a href="https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst" target="_blank">create an issue</a>.
{ "source": "microsoft/ai-agents-for-beginners", "title": "00-course-setup/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/00-course-setup/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 2366 }
# Introduction to AI Agents and Agent Use Cases Welcome to the "AI Agents for Beginners" course! This course gives you fundamental knowledge and applied samples for building with AI Agents. Join the <a href="https://discord.gg/kzRShWzttr" target="_blank">Azure AI Discord Community</a> to meet other learners, and AI Agent Builders and ask any questions you have on this course. To start this course, we begin by getting a better understanding of what AI Agents are and how we can use them in the applications and workflows we build. ## Introduction This lesson covers: - What are AI Agents and what are the different types of agents? - What use cases are best for AI Agents and how can they help us? - What are some of the basic building blocks when designing Agentic Solutions? ## Learning Goals After completing this lesson, you should be able to: - Understand AI Agent concepts and how they differ from other AI solutions. - Apply AI Agents most efficiently. - Design Agentic solutions productively for both users and customers. ## Defining AI Agents and Types of AI Agents ### What are AI Agents? AI Agents are **systems** that enable **Large Language Models(LLMs)** to **perform actions** by extending their capabilities by giving LLMs **access to tools** and **knowledge**. Let's break this definition into smaller parts: - **System** - It's important to think about agents not as just a single component but as a system of many components. At the basic level, the components of an AI Agent are: - **Environment** - The defined space where the AI Agent is operating. For example, if we had a travel booking AI Agent, the environment could be the travel booking system that the AI Agent uses to complete tasks. - **Sensors** - Environments have information and provide feedback. AI Agents use sensors to gather and interpret this information about the current state of the environment. In the Travel Booking Agent example, the travel booking system can provide information such as hotel availability or flight prices. - **Actuators** - Once the AI Agent receives the current state of the environment, for the current task the agent determines what action to perform to change the environment. For the travel booking agent, it might be to book an available room for the user. ![What Are AI Agents?](./images/what-are-ai-agents.png) **Large Language Models** - The concept of agents existed before the creation of LLMs. The advantage of building AI Agents with LLMs is their ability to interpret human language and data. This ability enables LLMs to interpret environmental information and define a plan to change the environment. **Perform Actions** - Outside of AI Agent systems, LLMs are limited to situations where the action is generating content or information based on a user's prompt. Inside AI Agent systems, LLMs can accomplish tasks by interpreting the user's request and using tools that are available in their environment. **Access To Tools** - What tools the LLM has access to is defined by 1) the environment it's operating in and 2) the developer of the AI Agent. For our travel agent example, the agent's tools are limited by the operations available in the booking system, and/or the developer can limit the agent's tool access to flights. **Knowledge** - Outside of the information provided by the environment, AI Agents can also retrieve knowledge from other systems, services, tools, and even other agents. In the travel agent example, this knowledge could be the information on the user's travel preferences located in a customer database. ### The different types of agents Now that we have a general definition of AI Agents, let us look at some specific agent types and how they would be applied to a travel booking AI agent. | **Agent Type** | **Description** | **Example** | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Simple Reflex Agents** | Perform immediate actions based on predefined rules. | Travel agent interprets the context of the email and forwards travel complaints to customer service. | | **Model-Based Reflex Agents** | Perform actions based on a model of the world and changes to that model. | Travel agent prioritizes routes with significant price changes based on access to historical pricing data. | | **Goal-Based Agents** | Create plans to achieve specific goals by interpreting the goal and determining actions to reach it. | Travel agent books a journey by determining necessary travel arrangements (car, public transit, flights) from the current location to the destination. | | **Utility-Based Agents** | Consider preferences and weigh tradeoffs numerically to determine how to achieve goals. | Travel agent maximizes utility by weighing convenience vs. cost when booking travel. | | **Learning Agents** | Improve over time by responding to feedback and adjusting actions accordingly. | Travel agent improves by using customer feedback from post-trip surveys to make adjustments to future bookings. | | **Hierarchical Agents** | Feature multiple agents in a tiered system, with higher-level agents breaking tasks into subtasks for lower-level agents to complete. | Travel agent cancels a trip by dividing the task into subtasks (for example, canceling specific bookings) and having lower-level agents complete them, reporting back to the higher-level agent. | | **Multi-Agent Systems (MAS)** | Agents complete tasks independently, either cooperatively or competitively. | Cooperative: Multiple agents book specific travel services such as hotels, flights, and entertainment. Competitive: Multiple agents manage and compete over a shared hotel booking calendar to book customers into the hotel. | ## When to Use AI Agents In the earlier section, we used the Travel Agent use-case to explain how the different types of agents can be used in different scenarios of travel booking. We will continue to use this application throughout the course. Let's look at the types of use cases that AI Agents are best used for: ![When to use AI Agents?](./images/when-to-use-ai-agents.png) - **Open-Ended Problems** - allowing the LLM to determine needed steps to complete a task because it can't always be hardcoded into a workflow. - **Multi-Step Processes** - tasks that require a level of complexity in which the AI Agent needs to use tools or information over multiple turns instead of single shot retrieval. - **Improvement Over Time** - tasks where the agent can improve over time by receiving feedback from either its environment or users in order to provide better utility. We cover more considerations of using AI Agents in the Building Trustworthy AI Agents lesson. ## Basics of Agentic Solutions ### Agent Development The first step in designing an AI Agent system is to define the tools, actions, and behaviors. In this course, we focus on using the **Azure AI Agent Service** to define our Agents. It offers features like: - Selection of Open Models such as OpenAI, Mistral, and Llama - Use of Licensed Data through providers such as Tripadvisor - Use of standardized OpenAPI 3.0 tools ### Agentic Patterns Communication with LLMs is through prompts. Given the semi-autonomous nature of AI Agents, it isn't always possible or required to manually reprompt the LLM after a change in the environment. We use **Agentic Patterns** that allow us to prompt the LLM over multiple steps in a more scalable way. This course is divided into some of the current popular Agentic patterns. ### Agentic Frameworks Agentic Frameworks allow developers to implement agentic patterns through code. These frameworks offer templates, plugins, and tools for better AI Agent collaboration. These benefits provide abilities for better observability and troubleshooting of AI Agent systems. In this course, we will explore the research-driven AutoGen framework and the production ready Agent framework from Semantic Kernel.
{ "source": "microsoft/ai-agents-for-beginners", "title": "01-intro-to-ai-agents/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/01-intro-to-ai-agents/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 9556 }
# Explore AI Agent Frameworks AI agent frameworks are software platforms designed to simplify the creation, deployment, and management of AI agents. These frameworks provide developers with pre-built components, abstractions, and tools that streamline the development of complex AI systems. These frameworks help developers focus on the unique aspects of their applications by providing standardized approaches to common challenges in AI agent development. They enhance scalability, accessibility, and efficiency in building AI systems. ## Introduction This lesson will cover: - What are AI Agent Frameworks and what do they enable developers to do? - How can teams use these to quickly prototype, iterate, and improve my agent’s capabilities? - What are the differences between the frameworks and tools created by Microsoft <a href="https://aka.ms/ai-agents/autogen" target="_blank">AutoGen</a>, <a href="https://aka.ms/ai-agents-beginners/semantic-kernel" target="_blank">Semantic Kernel</a>, and <a href="https://aka.ms/ai-agents-beginners/ai-agent-service" target="_blank">Azure AI Agent - Can I integrate my existing Azure ecosystem tools directly, or do I need standalone solutions? - What is Azure AI Agents service and how is this helping me? ## Learning goals The goals of this lesson is to help you understand: - The role of AI Agent Frameworks in AI development. - How to leverage AI Agent Frameworks to build intelligent agents. - Key capabilities enabled by AI Agent Frameworks. - The differences between AutoGen, Semantic Kernel, and Azure AI Agent Service. ## What are AI Agent Frameworks and what do they enable developers to do? Traditional AI Frameworks can help you integrate AI into your apps and make these apps better in the following ways: - **Personalization**: AI can analyze user behavior and preferences to provide personalized recommendations, content, and experiences. Example: Streaming services like Netflix use AI to suggest movies and shows based on viewing history, enhancing user engagement and satisfaction. - **Automation and Efficiency**: AI can automate repetitive tasks, streamline workflows, and improve operational efficiency. Example: Customer service apps use AI-powered chatbots to handle common inquiries, reducing response times and freeing up human agents for more complex issues. - **Enhanced User Experience**: AI can improve the overall user experience by providing intelligent features such as voice recognition, natural language processing, and predictive text. Example: Virtual assistants like Siri and Google Assistant use AI to understand and respond to voice commands, making it easier for users to interact with their devices. ### That all sounds great right, so why do we need AI Agent Framework? AI Agent frameworks represent something more than just AI frameworks. They are designed to enable the creation of intelligent agents that can interact with users, other agents, and the environment to achieve specific goals. These agents can exhibit autonomous behavior, make decisions, and adapt to changing conditions. Let's look at some key capabilities enabled by AI Agent Frameworks: - **Agent Collaboration and Coordination**: Enable the creation of multiple AI agents that can work together, communicate, and coordinate to solve complex tasks. - **Task Automation and Management**: Provide mechanisms for automating multi-step workflows, task delegation, and dynamic task management among agents. - **Contextual Understanding and Adaptation**: Equip agents with the ability to understand context, adapt to changing environments, and make decisions based on real-time information. So in summary, agents allow you to do more, to take automation to the next level, to create more intelligent systems that can adapt and learn from their environment. ## How to quickly prototype, iterate, and improve the agent’s capabilities? This is a fast-moving landscape, but there are some things that are common across most AI Agent Frameworks that can help you quickly prototype and iterate namely module components, collaborative tools, and real-time learning. Let's dive into these: - **Use Modular Components**: AI Frameworks offer pre-built components such as prompts, parsers, and memory management. - **Leverage Collaborative Tools**: Design agents with specific roles and tasks, enabling them to test and refine collaborative workflows. - **Learn in Real-Time**: Implement feedback loops where agents learn from interactions and adjust their behavior dynamically. ### Use Modular Components Frameworks like LangChain and Microsoft Semantic Kernel offer pre-built components such as prompts, parsers, and memory management. **How teams can use these**: Teams can quickly assemble these components to create a functional prototype without starting from scratch, allowing for rapid experimentation and iteration. **How it works in practice**: You can use a pre-built parser to extract information from user input, a memory module to store and retrieve data, and a prompt generator to interact with users, all without having to build these components from scratch. **Example code**. Let's look at an example of how you can use a pre-built parser to extract information from user input: ```csharp // Semantic Kernel example ChatHistory chatHistory = []; chatHistory.AddUserMessage("I'd like to go to New York"); // Define a plugin that contains the function to book travel public class BookTravelPlugin( IPizzaService pizzaService, IUserContext userContext, IPaymentService paymentService) { [KernelFunction("book_flight")] [Description("Book travel given location and date")] public async Task<Booking> BookFlight( DateTime date, string location, ) { // book travel given date,location } } IKernelBuilder kernelBuilder = new KernelBuilder(); kernelBuilder..AddAzureOpenAIChatCompletion( deploymentName: "NAME_OF_YOUR_DEPLOYMENT", apiKey: "YOUR_API_KEY", endpoint: "YOUR_AZURE_ENDPOINT" ); kernelBuilder.Plugins.AddFromType<BookTravelPlugin>("BookTravel"); Kernel kernel = kernelBuilder.Build(); /* Behind the scenes, it recognizes the tool to call, what arguments it already has (location) and what it needs (date) { "tool_calls": [ { "id": "call_abc123", "type": "function", "function": { "name": "BookTravelPlugin-book_flight", "arguments": "{\n\"location\": \"New York\",\n\"date\": \"\"\n}" } } ] */ ChatResponse response = await chatCompletion.GetChatMessageContentAsync( chatHistory, executionSettings: openAIPromptExecutionSettings, kernel: kernel) Console.WriteLine(response); chatHistory.AddAssistantMessage(response); // AI Response: "Before I can book your flight, I need to know your departure date. When are you planning to travel?" // That is, in the previous code it figures out the tool to call, what arguments it already has (location) and what it needs (date) from the user input, at this point it ends up asking the user for the missing information ``` What you can see from this example is how you can leverage a pre-built parser to extract key information from user input, such as the origin, destination, and date of a flight booking request. This modular approach allows you to focus on the high-level logic. ### Leverage Collaborative Tools Frameworks like CrewAI and Microsoft AutoGen facilitate the creation of multiple agents that can work together. **How teams can use these**: Teams can design agents with specific roles and tasks, enabling them to test and refine collaborative workflows and improve overall system efficiency. **How it works in practice**: You can create a team of agents where each agent has a specialized function, such as data retrieval, analysis, or decision-making. These agents can communicate and share information to achieve a common goal, such as answering a user query or completing a task. **Example code (AutoGen)**: ```python # creating agents, then create a round robin schedule where they can work together, in this case in order # Data Retrieval Agent # Data Analysis Agent # Decision Making Agent agent_retrieve = AssistantAgent( name="dataretrieval", model_client=model_client, tools=[retrieve_tool], system_message="Use tools to solve tasks." ) agent_analyze = AssistantAgent( name="dataanalysis", model_client=model_client, tools=[analyze_tool], system_message="Use tools to solve tasks." ) # conversation ends when user says "APPROVE" termination = TextMentionTermination("APPROVE") user_proxy = UserProxyAgent("user_proxy", input_func=input) team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination) stream = team.run_stream(task="Analyze data", max_turns=10) # Use asyncio.run(...) when running in a script. await Console(stream) ``` What you see in the previous code is how you can create a task that involves multiple agents working together to analyze data. Each agent performs a specific function, and the task is executed by coordinating the agents to achieve the desired outcome. By creating dedicated agents with specialized roles, you can improve task efficiency and performance. ### Learn in Real-Time Advanced frameworks provide capabilities for real-time context understanding and adaptation. **How teams can use these**: Teams can implement feedback loops where agents learn from interactions and adjust their behavior dynamically, leading to continuous improvement and refinement of capabilities. **How it works in practice**: Agents can analyze user feedback, environmental data, and task outcomes to update their knowledge base, adjust decision-making algorithms, and improve performance over time. This iterative learning process enables agents to adapt to changing conditions and user preferences, enhancing overall system effectiveness. ## What are the differences between the frameworks AutoGen, Semantic Kernel and Azure AI Agent Service? There are many ways to compare these frameworks, but let's look at some key differences in terms of their design, capabilities, and target use cases: ## AutoGen Open-source framework developed by Microsoft Research's AI Frontiers Lab. Focuses on event-driven, distributed _agentic_ applications, enabling multiple LLMs and SLMs, tools, and advanced multi-agent design patterns. AutoGen is built around the core concept of agents, which are autonomous entities that can perceive their environment, make decisions, and take actions to achieve specific goals. Agents communicate through asynchronous messages, allowing them to work independently and in parallel, enhancing system scalability and responsiveness. <a href="https://en.wikipedia.org/wiki/Actor_model" target="_blank">Agents are based on the actor model</a>. According to Wikipedia, an actor is _the basic building block of concurrent computation. In response to a message it receives, an actor can: make local decisions, create more actors, send more messages, and determine how to respond to the next message received_. **Use Cases**: Automating code generation, data analysis tasks, and building custom agents for planning and research functions. Here are some important core concepts of AutoGen: - **Agents**. An agent is a software entity that: - **Communicates via messages**, these messages can be synchronous or asynchronous. - **Maintains its own state**, which can be modified by incoming messages. - **Performs actions** in response to received messages or changes in its state. These actions may modify the agent’s state and produce external effects, such as updating message logs, sending new messages, executing code, or making API calls. Here you have a short code snippet in which you create your own agent with Chat capabilities: ```python from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.messages import TextMessage from autogen_ext.models.openai import OpenAIChatCompletionClient class MyAssistant(RoutedAgent): def __init__(self, name: str) -> None: super().__init__(name) model_client = OpenAIChatCompletionClient(model="gpt-4o") self._delegate = AssistantAgent(name, model_client=model_client) @message_handler async def handle_my_message_type(self, message: MyMessageType, ctx: MessageContext) -> None: print(f"{self.id.type} received message: {message.content}") response = await self._delegate.on_messages( [TextMessage(content=message.content, source="user")], ctx.cancellation_token ) print(f"{self.id.type} responded: {response.chat_message.content}") ``` In the previous code, `MyAssistant` has been created and inherits from `RoutedAgent`. It has a message handler that prints the content of the message and then sends a response using the `AssistantAgent` delegate. Especially note how we assign to `self._delegate` an instance of `AssistantAgent` which is a pre-built agent that can handle chat completions. Let's let AutoGen know about this agent type and kick off the program next: ```python # main.py runtime = SingleThreadedAgentRuntime() await MyAgent.register(runtime, "my_agent", lambda: MyAgent()) runtime.start() # Start processing messages in the background. await runtime.send_message(MyMessageType("Hello, World!"), AgentId("my_agent", "default")) ``` In the previous code the agents are registered with the runtime and then a message is sent to the agent resulting in the following output: ```text # Output from the console: my_agent received message: Hello, World! my_assistant received message: Hello, World! my_assistant responded: Hello! How can I assist you today? ``` - **Multi agents**. AutoGen supports the creation of multiple agents that can work together to achieve complex tasks. Agents can communicate, share information, and coordinate their actions to solve problems more efficiently. To create a multi-agent system, you can define different types of agents with specialized functions and roles, such as data retrieval, analysis, decision-making, and user interaction. Let's see how such a creation looks like so we get a sense of it: ```python editor_description = "Editor for planning and reviewing the content." # Example of declaring an Agent editor_agent_type = await EditorAgent.register( runtime, editor_topic_type, # Using topic type as the agent type. lambda: EditorAgent( description=editor_description, group_chat_topic_type=group_chat_topic_type, model_client=OpenAIChatCompletionClient( model="gpt-4o-2024-08-06", # api_key="YOUR_API_KEY", ), ), ) # remaining declarations shortened for brevity # Group chat group_chat_manager_type = await GroupChatManager.register( runtime, "group_chat_manager", lambda: GroupChatManager( participant_topic_types=[writer_topic_type, illustrator_topic_type, editor_topic_type, user_topic_type], model_client=OpenAIChatCompletionClient( model="gpt-4o-2024-08-06", # api_key="YOUR_API_KEY", ), participant_descriptions=[ writer_description, illustrator_description, editor_description, user_description ], ), ) ``` In the previous code we have a `GroupChatManager` that is registered with the runtime. This manager is responsible for coordinating the interactions between different types of agents, such as writers, illustrators, editors, and users. - **Agent Runtime**. The framework provides a runtime environment, enabling communication between agents, manages their identities and lifecycles, and enforce security and privacy boundaries. This means that you can run your agents in a secure and controlled environment, ensuring that they can interact safely and efficiently. There are two runtimes of interest: - **Stand-alone runtime**. This is a good choice for single-process applications where all agents are implemented in the same programming language and run in the same process. Here's an illustration of how it works: <a href="https://microsoft.github.io/autogen/stable/_images/architecture-standalone.svg" target="_blank">Stand-alone runtime</a> Application stack *agents communicate via messages through the runtime, and the runtime manages the lifecycle of agents* - **Distributed agent runtime**, is suitable for multi-process applications where agents may be implemented in different programming languages and running on different machines. Here's an illustration of how it works: <a href="https://microsoft.github.io/autogen/stable/_images/architecture-distributed.svg" target="_blank">Distributed runtime</a> ## Semantic Kernel + Agent Framework Semantic Kernel consists of two things, the Semantic Kernel Agent Framework and the Semantic Kernel itself. Let's first talk about the Semantic Kernel. It has the following core concepts: - **Connections**: This is an interface with external AI services and data sources. ```csharp using Microsoft.SemanticKernel; // Create kernel var builder = Kernel.CreateBuilder(); // Add a chat completion service: builder.Services.AddAzureOpenAIChatCompletion( "your-resource-name", "your-endpoint", "your-resource-key", "deployment-model"); var kernel = builder.Build(); ``` Here you have a simple example of how you can create a kernel and add a chat completion service. Semantic Kernel creates a connection to an external AI service, in this case, Azure OpenAI Chat Completion. - **Plugins**: Encapsulate functions that an application can use. There are both ready-made plugins and plugins you can create yourself. There's a concept here called "Semantic functions". What makes it semantic is that you provide it semantic information that helps Semantic Kernel figure out that this function needs to be called. Here's an example: ```csharp var userInput = Console.ReadLine(); // Define semantic function inline. string skPrompt = @"Summarize the provided unstructured text in a sentence that is easy to understand. Text to summarize: {{$userInput}}"; // Register the function kernel.CreateSemanticFunction( promptTemplate: skPrompt, functionName: "SummarizeText", pluginName: "SemanticFunctions" ); ``` Here, you first have a template prompt `skPrompt` that leaves room for the user to input text, `$userInput`. Then you register the function `SummarizeText` with the plugin `SemanticFunctions`. Note the name of the function that helps Semantic Kernel understand what the function does and when it should be called. - **Native function**: There's also native functions that the framework can call directly to carry out the task. Here's an example of such a function retrieving the content from a file: ```csharp public class NativeFunctions { [SKFunction, Description("Retrieve content from local file")] public async Task<string> RetrieveLocalFile(string fileName, int maxSize = 5000) { string content = await File.ReadAllTextAsync(fileName); if (content.Length <= maxSize) return content; return content.Substring(0, maxSize); } } //Import native function string plugInName = "NativeFunction"; string functionName = "RetrieveLocalFile"; var nativeFunctions = new NativeFunctions(); kernel.ImportFunctions(nativeFunctions, plugInName); ``` - **Planner**: The planner orchestrates execution plans and strategies based on user input. The idea is to express how things should be carried out which then surveys as an instruction for Semantic Kernel to follow. It then invokes the necessary functions to carry out the task. Here's an example of such a plan: ```csharp string planDefinition = "Read content from a local file and summarize the content."; SequentialPlanner sequentialPlanner = new SequentialPlanner(kernel); string assetsFolder = @"../../assets"; string fileName = Path.Combine(assetsFolder,"docs","06_SemanticKernel", "aci_documentation.txt"); ContextVariables contextVariables = new ContextVariables(); contextVariables.Add("fileName", fileName); var customPlan = await sequentialPlanner.CreatePlanAsync(planDefinition); // Execute the plan KernelResult kernelResult = await kernel.RunAsync(contextVariables, customPlan); Console.WriteLine($"Summarization: {kernelResult.GetValue<string>()}"); ``` Note especially `planDefinition` which is a simple instruction for the planner to follow. The appropriate functions are then called based on this plan, in this case our semantic function `SummarizeText` and the native function `RetrieveLocalFile`. - **Memory**: Abstracts and simplifies context management for AI apps. The idea with memory is that this is something the LLM should know about. You can store this information in a vector store which ends up being an in-memory database or a vector database or similar. Here's an example of a very simplified scenario where _facts_ are added to the memory: ```csharp var facts = new Dictionary<string,string>(); facts.Add( "Azure Machine Learning; https://learn.microsoft.com/azure/machine-learning/", @"Azure Machine Learning is a cloud service for accelerating and managing the machine learning project lifecycle. Machine learning professionals, data scientists, and engineers can use it in their day-to-day workflows" ); facts.Add( "Azure SQL Service; https://learn.microsoft.com/azure/azure-sql/", @"Azure SQL is a family of managed, secure, and intelligent products that use the SQL Server database engine in the Azure cloud." ); string memoryCollectionName = "SummarizedAzureDocs"; foreach (var fact in facts) { await memoryBuilder.SaveReferenceAsync( collection: memoryCollectionName, description: fact.Key.Split(";")[1].Trim(), text: fact.Value, externalId: fact.Key.Split(";")[2].Trim(), externalSourceName: "Azure Documentation" ); } ``` These facts are then stored in the memory collection `SummarizedAzureDocs`. This is a very simplified example, but you can see how you can store information in the memory for the LLM to use. So that's the basics of the Semantic Kernel framework, what about the Agent Framework? ## Azure AI Agent Service Azure AI Agent Service is a more recent addition, introduced at Microsoft Ignite 2024. It allows for the development and deployment of AI agents with more flexible models, such as directly calling open-source LLMs like Llama 3, Mistral, and Cohere. Azure AI Agent Service provides stronger enterprise security mechanisms and data storage methods, making it suitable for enterprise applications. It works out-of-the-box with multi-agent orchestration frameworks like AutoGen and Semantic Kernel. This service is currently in Public Preview and supports Python and C# for building agents ### Core concepts Azure AI Agent Service has the following core concepts: - **Agent**. Azure AI Agent Service integrates with Azure AI Foundry. Within AI Foundry, an AI Agent acts as a "smart" microservice that can be used to answer questions (RAG), perform actions, or completely automate workflows. It achieves this by combining the power of generative AI models with tools that allow it to access and interact with real-world data sources. Here's an example of an agent: ```python agent = project_client.agents.create_agent( model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent", tools=code_interpreter.definitions, tool_resources=code_interpreter.resources, ) ``` In this example, an agent is created with the model `gpt-4o-mini`, a name `my-agent`, and instructions `You are helpful agent`. The agent is equipped with tools and resources to perform code interpretation tasks. - **Thread and messages**. The thread is another important concept. It represents a conversation or interaction between an agent and a user. Threads can be used to track the progress of a conversation, store context information, and manage the state of the interaction. Here's an example of a thread: ```python thread = project_client.agents.create_thread() message = project_client.agents.create_message( thread_id=thread.id, role="user", content="Could you please create a bar chart for the operating profit using the following data and provide the file to me? Company A: $1.2 million, Company B: $2.5 million, Company C: $3.0 million, Company D: $1.8 million", ) # Ask the agent to perform work on the thread run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_id=agent.id) # Fetch and log all messages to see the agent's response messages = project_client.agents.list_messages(thread_id=thread.id) print(f"Messages: {messages}") ``` In the previous code, a thread is created. Thereafter, a message is sent to the thread. By calling `create_and_process_run`, the agent is asked to perform work on the thread. Finally, the messages are fetched and logged to see the agent's response. The messages indicate the progress of the conversation between the user and the agent. It's also important to understand that the messages can be of different types such as text, image, or file, that is the agents work has resulted in for example an image or a text response for example. As a developer, you can then use this information to further process the response or present it to the user. - **Integrates with other AI frameworks**. Azure AI Agent service can interact with other frameworks like AutoGen and Semantic Kernel, which means you can build part of your app in one of these frameworks and for example using the Agent service as an orchestrator or you can build everything in the Agent service. **Use Cases**: Azure AI Agent Service is designed for enterprise applications that require secure, scalable, and flexible AI agent deployment. ## What's the difference between these frameworks? It does sound like there is a lot of overlap between these frameworks, but there are some key differences in terms of their design, capabilities, and target use cases: - **AutoGen**: Is an experiementation framework focused on leading-edge research on multi-agent systems. It is the best place to experiment and prototype sophisticated multi-agent sytems. - **Semantic Kernel**: Is a production-ready agent library for building enterprise agentic applications. Focuses on event-driven, distributed agentic applications, enabling multiple LLMs and SLMs, tools, and single/multi-agent design patterns. - **Azure AI Agent Service**: Is a platform and deployment service in Azure Foundry for agents. It offers building connectivity to services support by Azure Found like Azure OpenAI, Azure AI Search, Bing Search and code exectuition. Still not sure which one to choose? ### Use Cases Let's see if we can help you by going through some common use cases: > Q: I'm experimenting, learning and building proof-of-concept agent applications, and I want to be able to build and experiment quickly > > A: AutoGen would be a good choice for this scenario, as it focuses on experimentation and building applications using the latest multi-agent patterns > Q: I'm designing a building a application that I want to scale and use production or within my enterprise > > A: Semantic Kernel is the best choice for build production AI agent applications. Experimental features from AutoGen are stabilized and added to Semantic Kernel reguarly. > Q: Sounds like Azure AI Agent Service could work here too? > > A: Yes, Azure AI Agent Service is a platform service for agents and add built-in capabilities for multiple models, Azure AI Search, Bing Search and Azure Functions. It makes it easy to build your agents in the Foundry Portal and deploy them at scale. > Q: I'm still confused just give me one option > > A: A create choice is to build you application in Semantic Kernel first, and use Azure AI Agent Service to deploy you agent. This means you can easily perist your agents while still having the power to build multi-agent systems in Semantic Kernel. Semantic also has a connector in AutoGen to make it easy to use both frameworks together. Let's summarize the key differences in a table: | Framework | Focus | | ---------------------- | ------------------------------------------------------------------- | | AutoGen | Experimentation and proof-of-concept | | Semantic Kernel | Product-ready enterprise AI agent applications | | Azure AI Agent Service | Deployment, management and integration with Azure Foundry | What's the ideal use case for each of these frameworks? ## Can I integrate my existing Azure ecosystem tools directly, or do I need standalone solutions? The answer is yes, you can integrate your existing Azure ecosystem tools directly with Azure AI Agent Service especially, this because it has been built to work seamlessly with other Azure services. You could for example integrate Bing, Azure AI Search, and Azure Functions. There's also deep integration with Azure AI Foundry. For AutoGen and Semantic Kernel, you can also integrate with Azure services, but it may require you to call the Azure services from your code. Another way to integrate is to use the Azure SDKs to interact with Azure services from your agents. Additionally, like was mentioned, you can use Azure AI Agent Service as an orchestrator for your agents built in AutoGen or Semantic Kernel which would give easy access to the Azure ecosystem. ## References - <a href="https://techcommunity.microsoft.com/blog/azure-ai-services-blog/introducing-azure-ai-agent-service/4298357" target="_blank">Azure Agent Service</a> - <a href="https://devblogs.microsoft.com/semantic-kernel/microsofts-agentic-ai-frameworks-autogen-and-semantic-kernel/" target="_blank">Semantic Kernel and AutoGen</a> - <a href="https://learn.microsoft.com/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp" target="_blank">Semantic Kernel Agent Framework</a> - <a href="https://learn.microsoft.com/azure/ai-services/agents/overview" target="_blank">Azure AI Agent service</a> - <a href="https://techcommunity.microsoft.com/blog/educatordeveloperblog/using-azure-ai-agent-service-with-autogen--semantic-kernel-to-build-a-multi-agen/4363121" target="_blank">Using Azure AI Agent Service with AutoGen / Semantic Kernel to build a multi-agent's solution</a>
{ "source": "microsoft/ai-agents-for-beginners", "title": "02-explore-agentic-frameworks/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/02-explore-agentic-frameworks/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 30892 }
# AI Agentic Design Principles ## Introduction There are many ways to think about building AI Agentic Systems. Given that ambiguity is a feature and not a bug in Generative AI design, it’s sometimes difficult for engineers to figure out where to even start. We have created a set of human-centric UX Design Principles to enable developers to build customer-centric agentic systems to solve their business needs. These design principles are not a prescriptive architecture but rather a starting point for teams who are defining and building out agent experiences. In general, agents should: - Broaden and scale human capacities (brainstorming, problem-solving, automation, etc.) - Fill in knowledge gaps (get me up-to-speed on knowledge domains, translation, etc.) - Facilitate and support collaboration in the ways we as individuals prefer to work with others - Make us better versions of ourselves (e.g., life coach/task master, helping us learn emotional regulation and mindfulness skills, building resilience, etc.) ## This Lesson Will Cover - What are the Agentic Design Principles - What are some guidelines to follow while implementing these design principles - What are some examples of using the design principles ## Learning Goals After completing this lesson, you will be able to: 1. Explain what the Agentic Design Principles are 2. Explain the guidelines to using the Agentic Design Principles 3. Understand how to build an agent using the Agentic Design Principles ## The Agentic Design Principles ![Agentic Design Principles](./images/agentic-design-principles.png) ### Agent (Space) This is the environment in which the agent operates. These principles inform how we design agents for engaging in physical and digital worlds. - **Connecting, not collapsing** – help connect people to other people, events, and actionable knowledge to enable collaboration and connection. - Agents help connect events, knowledge, and people. - Agents bring people closer together. They are not designed to replace or belittle people. - **Easily accessible yet occasionally invisible** – agent largely operates in the background and only nudges us when it is relevant and appropriate. - Agent is easily discoverable and accessible for authorized users on any device or platform. - Agent supports multimodal inputs and outputs (sound, voice, text, etc.). - Agent can seamlessly transition between foreground and background; between proactive and reactive, depending on its sensing of user needs. - Agent may operate in invisible form, yet its background process path and collaboration with other Agents is transparent to and controllable by the user. ### Agent (Time) This is how the agent operates over time. These principles inform how we design agents interacting across the past, present, and future. - **Past**: Reflecting on history that includes both state and context. - Agent provides more relevant results based on analysis of richer historical data beyond only the event, people, or states. - Agent creates connections from past events and actively reflects on memory to engage with current situations. - **Now**: Nudging more than notifying. - Agent embodies a comprehensive approach to interacting with people. When an event happens, Agent goes beyond static notification or other static formality. Agent can simplify flows or dynamically generate cues to direct the user’s attention at the right moment. - Agent delivers information based on contextual environment, social and cultural changes and tailored to user intent. - Agent interaction can be gradual, evolving/growing in complexity to empower users over the long term. - **Future**: Adapting and evolving. - Agent adapts to various devices, platforms, and modalities. - Agent adapts to user behavior, accessibility needs, and is freely customizable. - Agent is shaped by and evolves through continuous user interaction. ### Agent (Core) These are the key elements in the core of an agent’s design. - **Embrace uncertainty but establish trust**. - A certain level of Agent uncertainty is expected. Uncertainty is a key element of agent design. - Trust and transparency are foundational layers of Agent design. - Humans are in control of when the Agent is on/off and Agent status is clearly visible at all times. ## The Guidelines To Implement These Principles When you’re using the previous design principles, use the following guidelines: 1. **Transparency**: Inform the user that AI is involved, how it functions (including past actions), and how to give feedback and modify the system. 2. **Control**: Enable the user to customize, specify preferences and personalize, and have control over the system and its attributes (including the ability to forget). 3. **Consistency**: Aim for consistent, multi-modal experiences across devices and endpoints. Use familiar UI/UX elements where possible (e.g., microphone icon for voice interaction) and reduce the customer’s cognitive load as much as possible (e.g., aim for concise responses, visual aids, and ‘Learn More’ content). ## How To Design a Travel Agent using These Principles and Guidelines Imagine you are designing a Travel Agent, here is how you could think about using the Design Principles and Guidelines: 1. **Transparency** – Let the user know that the Travel Agent is an AI-enabled Agent. Provide some basic instructions on how to get started (e.g., a “Hello” message, sample prompts). Clearly document this on the product page. Show the list of prompts a user has asked in the past. Make it clear how to give feedback (thumbs up and down, Send Feedback button, etc.). Clearly articulate if the Agent has usage or topic restrictions. 2. **Control** – Make sure it’s clear how the user can modify the Agent after it’s been created with things like the System Prompt. Enable the user to choose how verbose the Agent is, its writing style, and any caveats on what the Agent should not talk about. Allow the user to view and delete any associated files or data, prompts, and past conversations. 3. **Consistency** – Make sure the icons for Share Prompt, add a file or photo and tag someone or something are standard and recognizable. Use the paperclip icon to indicate file upload/sharing with the Agent, and an image icon to indicate graphics upload. ## Additional Resources - <a href="https://openai.com" target="_blank">Practices for Governing Agentic AI Systems | OpenAI</a> - <a href="https://microsoft.com" target="_blank">The HAX Toolkit Project - Microsoft Research</a> - <a href="https://responsibleaitoolbox.ai" target="_blank">Responsible AI Toolbox</a>
{ "source": "microsoft/ai-agents-for-beginners", "title": "03-agentic-design-patterns/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/03-agentic-design-patterns/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 6648 }
# Tool Use Design Pattern Tools are interesting because they allow AI agents to have a broader range of capabilities. Instead of the agent having a limited set of actions it can perform, by adding a tool, the agent can now perform a wide range of actions. In this chapter, we will look at the Tool Use Design Pattern, which describes how AI agents can use specific tools to achieve their goals. ## Introduction In this lesson, we're looking to answer the following questions: - What is the tool use design pattern? - What are the use cases it can be applied to? - What are the elements/building blocks needed to implement the design pattern? - What are the special considerations for using the Tool Use Design Pattern to build trustworthy AI agents? ## Learning Goals After completing this lesson, you will be able to: - Define the Tool Use Design Pattern and its purpose. - Identify use cases where the Tool Use Design Pattern is applicable. - Understand the key elements needed to implement the design pattern. - Recognize considerations for ensuring trustworthiness in AI agents using this design pattern. ## What is the Tool Use Design Pattern? The **Tool Use Design Pattern** focuses on giving LLMs the ability to interact with external tools to achieve specific goals. Tools are code that can be executed by an agent to perform actions. A tool can be a simple function such as a calculator, or an API call to a third-party service such as stock price lookup or weather forecast. In the context of AI agents, tools are designed to be executed by agents in response to **model-generated function calls**. ## What are the use cases it can be applied to? AI Agents can leverage tools to complete complex tasks, retrieve information, or make decisions. The Tool Use Design Pattern is often used in scenarios requiring dynamic interaction with external systems, such as databases, web services, or code interpreters. This ability is useful for a number of different use cases including: - **Dynamic Information Retrieval:** Agents can query external APIs or databases to fetch up-to-date data (e.g., querying a SQLite database for data analysis, fetching stock prices or weather information). - **Code Execution and Interpretation:** Agents can execute code or scripts to solve mathematical problems, generate reports, or perform simulations. - **Workflow Automation:** Automating repetitive or multi-step workflows by integrating tools like task schedulers, email services, or data pipelines. - **Customer Support:** Agents can interact with CRM systems, ticketing platforms, or knowledge bases to resolve user queries. - **Content Generation and Editing:** Agents can leverage tools like grammar checkers, text summarizers, or content safety evaluators to assist with content creation tasks. ## What are the elements/building blocks needed to implement the Tool Use Design Pattern? These building blocks allow the AI agent to perform a wide range of tasks. Let's look at the key elements needed to implement the Tool Use Design Pattern: - **Function/Tool Calling**: This is the primary way to enable LLMs to interact with tools. Functions or tools are blocks of reusable code that agents use to carry out tasks. These can range from simple functions like a calculator to API calls to third-party services such as stock price lookups or weather forecasts. - **Dynamic Information Retrieval**: Agents can query external APIs or databases to fetch up-to-date data. This is useful for tasks like data analysis, fetching stock prices, or weather information. - **Code Execution and Interpretation**: Agents can execute code or scripts to solve mathematical problems, generate reports, or perform simulations. - **Workflow Automation**: This involves automating repetitive or multi-step workflows by integrating tools like task schedulers, email services, or data pipelines. - **Customer Support**: Agents can interact with CRM systems, ticketing platforms, or knowledge bases to resolve user queries. - **Content Generation and Editing: Agents can leverage tools like grammar checkers, text summarizers, or content safety evaluators to assist with content creation tasks**. Next, let's look at Function/Tool Calling in more detail. ### Function/Tool Calling Function calling is the primary way we enable Large Language Models (LLMs) to interact with tools. You will often see 'Function' and 'Tool' used interchangeably because 'functions' (blocks of reusable code) are the 'tools' agents use to carry out tasks. In order for a function's code to be invoked, an LLM must compare the users request against the functions description. To do this a schema containing the descriptions of all the available functions is sent to the LLM. The LLM then selects the most appropriate function for the task and returns its name and arguments. The selected function is invoked, it's response is sent back to the LLM, which uses the information to respond to the users request. For developers to implement function calling for agents, you will need: 1. An LLM model that supports function calling 2. A schema containing function descriptions 3. The code for each function described Let's use the example of getting the current time in a city to illustrate: 1. **Initialize an LLM that supports function calling:** Not all models support function calling, so it's important to check that the LLM you are using does. <a href="https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling" target="_blank">Azure OpenAI</a> supports function calling. We can start by initiating the Azure OpenAI client. ```python # Initialize the Azure OpenAI client client = AzureOpenAI( azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), api_version="2024-05-01-preview" ) ``` 1. **Create a Function Schema**: Next we will define a JSON schema that contains the function name, description of what the function does, and the names and descriptions of the function parameters. We will then take this schema and pass it to the client created previously, along with the users request to find the time in San Francisco. What's important to note is that a **tool call** is what is returned, **not** the final answer to the question. As mentioned earlier, the LLM returns the name of the function it selected for the task, and the arguments that will be passed to it. ```python # Function description for the model to read tools = [ { "type": "function", "function": { "name": "get_current_time", "description": "Get the current time in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name, e.g. San Francisco", }, }, "required": ["location"], }, } } ] ``` ```python # Initial user message messages = [{"role": "user", "content": "What's the current time in San Francisco"}] # First API call: Ask the model to use the function response = client.chat.completions.create( model=deployment_name, messages=messages, tools=tools, tool_choice="auto", ) # Process the model's response response_message = response.choices[0].message messages.append(response_message) print("Model's response:") print(response_message) ``` ```bash Model's response: ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')]) ``` 1. **The function code required to carry out the task:** Now that the LLM has chosen which function needs to be run the code that carries out the task needs to be implemented and executed. We can implement the code to get the current time in Python. We will also need to write the code to extract the name and arguments from the response_message to get the final result. ```python def get_current_time(location): """Get the current time for a given location""" print(f"get_current_time called with location: {location}") location_lower = location.lower() for key, timezone in TIMEZONE_DATA.items(): if key in location_lower: print(f"Timezone found for {key}") current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p") return json.dumps({ "location": location, "current_time": current_time }) print(f"No timezone data found for {location_lower}") return json.dumps({"location": location, "current_time": "unknown"}) ``` ```python # Handle function calls if response_message.tool_calls: for tool_call in response_message.tool_calls: if tool_call.function.name == "get_current_time": function_args = json.loads(tool_call.function.arguments) time_response = get_current_time( location=function_args.get("location") ) messages.append({ "tool_call_id": tool_call.id, "role": "tool", "name": "get_current_time", "content": time_response, }) else: print("No tool calls were made by the model.") # Second API call: Get the final response from the model final_response = client.chat.completions.create( model=deployment_name, messages=messages, ) return final_response.choices[0].message.content ``` ```bash get_current_time called with location: San Francisco Timezone found for san francisco The current time in San Francisco is 09:24 AM. ``` Function Calling is at the heart of most, if not all agent tool use design, however implementing it from scratch can sometimes be challenging. As we learned in [Lesson 2](../02-explore-agentic-frameworks/) agentic frameworks provide us with pre-built building blocks to implement tool use. ## Tool Use Examples with Agentic Frameworks Here are some examples of how you can implement the Tool Use Design Pattern using different agentic frameworks: ### Semantic Kernel <a href="https://learn.microsoft.com/azure/ai-services/agents/overview" target="_blank">Semantic Kernel</a> is an open-source AI framework for .NET, Python, and Java developers working with Large Language Models (LLMs). It simplifies the process of using function calling by automatically describing your functions and their parameters to the model through a process called <a href="https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions" target="_blank">serializing</a>. It also handles the back-and-forth communication between the model and your code. Another advantage of using an agentic framework like Semantic Kernel, is that it allows you to access pre-built tools like <a href="https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step4_assistant_tool_file_search.py" target="_blank">File Search</a> and <a href="https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py" target="_blank">Code Interpreter</a>. The following diagram illustrates the process of function calling with Semantic Kernel: ![function calling](./images/functioncalling-diagram.png) In Semantic Kernel functions/tools are called <a href="https://learn.microsoft.com/semantic-kernel/concepts/plugins/?pivots=programming-language-python" target="_blank">Plugins</a>. We can convert the `get_current_time` function we saw earlier into a plugin by turning it into a class with the function in it. We can also import the `kernel_function` decorator, which takes in the description of the function. When you then create a kernel with the GetCurrentTimePlugin, the kernel will automatically serialize the function and its parameters, creating the schema to send to the LLM in the process. ```python from semantic_kernel.functions import kernel_function class GetCurrentTimePlugin: async def __init__(self, location): self.location = location @kernel_function( description="Get the current time for a given location" ) def get_current_time(location: str = ""): ... ``` ```python from semantic_kernel import Kernel # Create the kernel kernel = Kernel() # Create the plugin get_current_time_plugin = GetCurrentTimePlugin(location) # Add the plugin to the kernel kernel.add_plugin(get_current_time_plugin) ``` ### Azure AI Agent Service <a href="https://learn.microsoft.com/azure/ai-services/agents/overview" target="_blank">Azure AI Agent Service</a> is a newer agentic framework that is designed to empower developers to securely build, deploy, and scale high-quality, and extensible AI agents without needing to manage the underlying compute and storage resources. It is particularly useful for enterprise applications since it is a fully managed service with enterprise grade security. When compared to developing with the LLM API directly, Azure AI Agent Service provides some advantages, including: - Automatic tool calling – no need to parse a tool call, invoke the tool, and handle the response; all of this is now done server-side - Securely managed data – instead of managing your own conversation state, you can rely on threads to store all the information you need - Out-of-the-box tools – Tools that you can use to interact with your data sources, such as Bing, Azure AI Search, and Azure Functions. The tools available in Azure AI Agent Service can be divided into two categories: 1. Knowledge Tools: - <a href="https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview" target="_blank">Grounding with Bing Search</a> - <a href="https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/file-search?tabs=python&pivots=overview" target="_blank">File Search</a> - <a href="https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search" target="_blank">Azure AI Search</a> 2. Action Tools: - <a href="https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/function-calling?tabs=python&pivots=overview" target="_blank">Function Calling</a> - <a href="https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/code-interpreter?tabs=python&pivots=overview" target="_blank">Code Interpreter</a> - <a href="https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/openapi-spec?tabs=python&pivots=overview" target="_blank">OpenAI defined tools</a> - <a href="https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-functions?pivots=overview" target="_blank">Azure Functions</a> The Agent Service allows us to be able to use these tools together as a `toolset`. It also utilizes `threads` which keep track of the history of messages from a particular conversation. Imagine you are a sales agent at a company called Contoso. You want to develop a conversational agent that can answer questions about your sales data. The following image illustrates how you could use Azure AI Agent Service to analyze your sales data: ![Agentic Service In Action](./images/agent-service-in-action.jpg) To use any of these tools with the service we can create a client and define a tool or toolset. To implement this practically we can use the following Python code. The LLM will be able to look at the toolset and decide whether to use the user created function, `fetch_sales_data_using_sqlite_query`, or the pre-built Code Interpreter depending on the user request. ```python import os from azure.ai.projects import AIProjectClient from azure.identity import DefaultAzureCredential from fecth_sales_data_functions import fetch_sales_data_using_sqlite_query # fetch_sales_data_using_sqlite_query function which can be found in a fetch_sales_data_functions.py file. from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool project_client = AIProjectClient.from_connection_string( credential=DefaultAzureCredential(), conn_str=os.environ["PROJECT_CONNECTION_STRING"], ) # Initialize function calling agent with the fetch_sales_data_using_sqlite_query function and adding it to the toolset fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query) toolset = ToolSet() toolset.add(fetch_data_function) # Initialize Code Interpreter tool and adding it to the toolset. code_interpreter = code_interpreter = CodeInterpreterTool() toolset = ToolSet() toolset.add(code_interpreter) agent = project_client.agents.create_agent( model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent", toolset=toolset ) ``` ## What are the special considerations for using the Tool Use Design Pattern to build trustworthy AI agents? A common concern with SQL dynamically generated by LLMs is security, particularly the risk of SQL injection or malicious actions, such as dropping or tampering with the database. While these concerns are valid, they can be effectively mitigated by properly configuring database access permissions. For most databases this involves configuring the database as read-only. For database services like PostgreSQL or Azure SQL, the app should be assigned a read-only (SELECT) role. Running the app in a secure environment further enhances protection. In enterprise scenarios, data is typically extracted and transformed from operational systems into a read-only database or data warehouse with a user-friendly schema. This approach ensures that the data is secure, optimized for performance and accessibility, and that the app has restricted, read-only access. ## Additional Resources - <a href="https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/" target="_blank">Azure AI Agents Service Workshop</a> - <a href="https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop" target="_blank">Contoso Creative Writer Multi-Agent Workshop</a> - <a href="https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions" target="_blank">Semantic Kernel Function Calling Tutorial</a> - <a href="https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py" target="_blank">Semantic Kernel Code Interpreter</a> - <a href="https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html" target="_blank">Autogen Tools</a>
{ "source": "microsoft/ai-agents-for-beginners", "title": "04-tool-use/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/04-tool-use/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 19303 }
# Agentic RAG This lesson provides a comprehensive overview of Agentic Retrieval-Augmented Generation (Agentic RAG), an emerging AI paradigm where large language models (LLMs) autonomously plan their next steps while pulling information from external sources. Unlike static retrieval-then-read patterns, Agentic RAG involves iterative calls to the LLM, interspersed with tool or function calls and structured outputs. The system evaluates results, refines queries, invokes additional tools if needed, and continues this cycle until a satisfactory solution is achieved. ## Introduction This lesson will cover - **Understand Agentic RAG:** Learn about the emerging paradigm in AI where large language models (LLMs) autonomously plan their next steps while pulling information from external data sources. - **Grasp Iterative Maker-Checker Style:** Comprehend the loop of iterative calls to the LLM, interspersed with tool or function calls and structured outputs, designed to improve correctness and handle malformed queries. - **Explore Practical Applications:** Identify scenarios where Agentic RAG shines, such as correctness-first environments, complex database interactions, and extended workflows. ## Learning Goals After completing this lesson you will know how to/understand: - **Understanding Agentic RAG:** Learn about the emerging paradigm in AI where large language models (LLMs) autonomously plan their next steps while pulling information from external data sources. - **Iterative Maker-Checker Style:** Grasp the concept of a loop of iterative calls to the LLM, interspersed with tool or function calls and structured outputs, designed to improve correctness and handle malformed queries. - **Owning the Reasoning Process:** Comprehend the system's ability to own its reasoning process, making decisions on how to approach problems without relying on pre-defined paths. - **Workflow:** Understand how an agentic model independently decides to retrieve market trend reports, identify competitor data, correlate internal sales metrics, synthesize findings, and evaluate the strategy. - **Iterative Loops, Tool Integration, and Memory:** Learn about the system's reliance on a looped interaction pattern, maintaining state and memory across steps to avoid repetitive loops and make informed decisions. - **Handling Failure Modes and Self-Correction:** Explore the system's robust self-correction mechanisms, including iterating and re-querying, using diagnostic tools, and falling back on human oversight. - **Boundaries of Agency:** Understand the limitations of Agentic RAG, focusing on domain-specific autonomy, infrastructure dependence, and respect for guardrails. - **Practical Use Cases and Value:** Identify scenarios where Agentic RAG shines, such as correctness-first environments, complex database interactions, and extended workflows. - **Governance, Transparency, and Trust:** Learn about the importance of governance and transparency, including explainable reasoning, bias control, and human oversight. ## What is Agentic RAG? Agentic Retrieval-Augmented Generation (Agentic RAG) is an emerging AI paradigm where large language models (LLMs) autonomously plan their next steps while pulling information from external sources. Unlike static retrieval-then-read patterns, Agentic RAG involves iterative calls to the LLM, interspersed with tool or function calls and structured outputs. The system evaluates results, refines queries, invokes additional tools if needed, and continues this cycle until a satisfactory solution is achieved. This iterative “maker-checker” style improves correctness, handles malformed queries, and ensures high-quality results. The system actively owns its reasoning process, rewriting failed queries, choosing different retrieval methods, and integrating multiple tools—such as vector search in Azure AI Search, SQL databases, or custom APIs—before finalizing its answer. The distinguishing quality of an agentic system is its ability to own its reasoning process. Traditional RAG implementations rely on pre-defined paths, but an agentic system autonomously determines the sequence of steps based on the quality of the information it finds. ## Defining Agentic Retrieval-Augmented Generation (Agentic RAG) Agentic Retrieval-Augmented Generation (Agentic RAG) is an emerging paradigm in AI development where LLMs not only pull information from external data sources but also autonomously plan their next steps. Unlike static retrieval-then-read patterns or carefully scripted prompt sequences, Agentic RAG involves a loop of iterative calls to the LLM, interspersed with tool or function calls and structured outputs. At every turn, the system evaluates the results it has obtained, decides whether to refine its queries, invokes additional tools if needed, and continues this cycle until it achieves a satisfactory solution. This iterative “maker-checker” style of operation is designed to improve correctness, handle malformed queries to structured databases (e.g. NL2SQL), and ensure balanced, high-quality results. Rather than relying solely on carefully engineered prompt chains, the system actively owns its reasoning process. It can rewrite queries that fail, choose different retrieval methods, and integrate multiple tools—such as vector search in Azure AI Search, SQL databases, or custom APIs—before finalizing its answer. This removes the need for overly complex orchestration frameworks. Instead, a relatively simple loop of “LLM call → tool use → LLM call → …” can yield sophisticated and well-grounded outputs. ![Agentic RAG Core Loop](./images/agentic-rag-core-loop.png) ## Owning the Reasoning Process The distinguishing quality that makes a system “agentic” is its ability to own its reasoning process. Traditional RAG implementations often depend on humans pre-defining a path for the model: a chain-of-thought that outlines what to retrieve and when. But when a system is truly agentic, it internally decides how to approach the problem. It’s not just executing a script; it’s autonomously determining the sequence of steps based on the quality of the information it finds. For example, if it’s asked to create a product launch strategy, it doesn’t rely solely on a prompt that spells out the entire research and decision-making workflow. Instead, the agentic model independently decides to: 1. Retrieve current market trend reports using Bing Web Grounding 2. Identify relevant competitor data using Azure AI Search. 3. Correlate historical internal sales metrics using Azure SQL Database. 4. Synthesize the findings into a cohesive strategy orchestrated via Azure OpenAI Service. 5. Evaluate the strategy for gaps or inconsistencies, prompting another round of retrieval if necessary. All of these steps—refining queries, choosing sources, iterating until “happy” with the answer—are decided by the model, not pre-scripted by a human. ## Iterative Loops, Tool Integration, and Memory ![Tool Integration Architecture](./images/tool-integration.png) An agentic system relies on a looped interaction pattern: - **Initial Call:** The user’s goal (aka. user prompt) is presented to the LLM. - **Tool Invocation:** If the model identifies missing information or ambiguous instructions, it selects a tool or retrieval method—like a vector database query (e.g. Azure AI Search Hybrid search over private data) or a structured SQL call—to gather more context. - **Assessment & Refinement:** After reviewing the returned data, the model decides whether the information suffices. If not, it refines the query, tries a different tool, or adjusts its approach. - **Repeat Until Satisfied:** This cycle continues until the model determines that it has enough clarity and evidence to deliver a final, well-reasoned response. - **Memory & State:** Because the system maintains state and memory across steps, it can recall previous attempts and their outcomes, avoiding repetitive loops and making more informed decisions as it proceeds. Over time, this creates a sense of evolving understanding, enabling the model to navigate complex, multi-step tasks without requiring a human to constantly intervene or reshape the prompt. ## Handling Failure Modes and Self-Correction Agentic RAG’s autonomy also involves robust self-correction mechanisms. When the system hits dead ends—such as retrieving irrelevant documents or encountering malformed queries—it can: - **Iterate and Re-Query:** Instead of returning low-value responses, the model attempts new search strategies, rewrites database queries, or looks at alternative data sets. - **Use Diagnostic Tools:** The system may invoke additional functions designed to help it debug its reasoning steps or confirm the correctness of retrieved data. Tools like Azure AI Tracing will be important to enable robust observability and monitoring. - **Fallback on Human Oversight:** For high-stakes or repeatedly failing scenarios, the model might flag uncertainty and request human guidance. Once the human provides corrective feedback, the model can incorporate that lesson going forward. This iterative and dynamic approach allows the model to improve continuously, ensuring that it’s not just a one-shot system but one that learns from its missteps during a given session. ![Self Correction Mechanism](./images/self-correction.png) ## Boundaries of Agency Despite its autonomy within a task, Agentic RAG is not analogous to Artificial General Intelligence. Its “agentic” capabilities are confined to the tools, data sources, and policies provided by human developers. It can’t invent its own tools or step outside the domain boundaries that have been set. Rather, it excels at dynamically orchestrating the resources at hand. Key differences from more advanced AI forms include: 1. **Domain-Specific Autonomy:** Agentic RAG systems are focused on achieving user-defined goals within a known domain, employing strategies like query rewriting or tool selection to improve outcomes. 2. **Infrastructure-Dependent:** The system’s capabilities hinge on the tools and data integrated by developers. It can’t surpass these boundaries without human intervention. 3. **Respect for Guardrails:** Ethical guidelines, compliance rules, and business policies remain very important. The agent’s freedom is always constrained by safety measures and oversight mechanisms (hopefully?) ## Practical Use Cases and Value Agentic RAG shines in scenarios requiring iterative refinement and precision: 1. **Correctness-First Environments:** In compliance checks, regulatory analysis, or legal research, the agentic model can repeatedly verify facts, consult multiple sources, and rewrite queries until it produces a thoroughly vetted answer. 2. **Complex Database Interactions:** When dealing with structured data where queries might often fail or need adjustment, the system can autonomously refine its queries using Azure SQL or Microsoft Fabric OneLake, ensuring the final retrieval aligns with the user’s intent. 3. **Extended Workflows:** Longer-running sessions might evolve as new information surfaces. Agentic RAG can continuously incorporate new data, shifting strategies as it learns more about the problem space. ## Governance, Transparency, and Trust As these systems become more autonomous in their reasoning, governance and transparency are crucial: - **Explainable Reasoning:** The model can provide an audit trail of the queries it made, the sources it consulted, and the reasoning steps it took to reach its conclusion. Tools like Azure AI Content Safety and Azure AI Tracing / GenAIOps can help maintain transparency and mitigate risks. - **Bias Control and Balanced Retrieval:** Developers can tune retrieval strategies to ensure balanced, representative data sources are considered, and regularly audit outputs to detect bias or skewed patterns using custom models for advanced data science organizations using Azure Machine Learning. - **Human Oversight and Compliance:** For sensitive tasks, human review remains essential. Agentic RAG doesn’t replace human judgment in high-stakes decisions—it augments it by delivering more thoroughly vetted options. Having tools that provide a clear record of actions is essential. Without them, debugging a multi-step process can be very difficult. See the following example from Literal AI (company behind Chainlit) for an Agent run: ![AgentRunExample](./images/AgentRunExample.png) ![AgentRunExample2](./images/AgentRunExample2.png) ## Conclusion Agentic RAG represents a natural evolution in how AI systems handle complex, data-intensive tasks. By adopting a looped interaction pattern, autonomously selecting tools, and refining queries until achieving a high-quality result, the system moves beyond static prompt-following into a more adaptive, context-aware decision-maker. While still bounded by human-defined infrastructures and ethical guidelines, these agentic capabilities enable richer, more dynamic, and ultimately more useful AI interactions for both enterprises and end-users. ## Additional Resources - <a href="https://learn.microsoft.com/training/modules/use-own-data-azure-openai" target="_blank">Implement Retrieval Augmented Generation (RAG) with Azure OpenAI Service: Learn how to use your own data with the Azure OpenAI Service. This Microsoft Learn module provides a comprehensive guide on implementing RAG</a> - <a href="https://learn.microsoft.com/azure/ai-studio/concepts/evaluation-approach-gen-ai" target="_blank">Evaluation of generative AI applications with Azure AI Foundry: This article covers the evaluation and comparison of models on publicly available datasets, including Agentic AI applications and RAG architectures</a> - <a href="https://weaviate.io/blog/what-is-agentic-rag" target="_blank">What is Agentic RAG | Weaviate</a> - <a href="https://ragaboutit.com/agentic-rag-a-complete-guide-to-agent-based-retrieval-augmented-generation/" target="_blank">Agentic RAG: A Complete Guide to Agent-Based Retrieval Augmented Generation – News from generation RAG</a> - <a href="https://huggingface.co/learn/cookbook/agent_rag" target="_blank">Agentic RAG: turbocharge your RAG with query reformulation and self-query! Hugging Face Open-Source AI Cookbook</a> - <a href="https://youtu.be/aQ4yQXeB1Ss?si=2HUqBzHoeB5tR04U" target="_blank">Adding Agentic Layers to RAG</a> - <a href="https://www.youtube.com/watch?v=zeAyuLc_f3Q&t=244s" target="_blank">The Future of Knowledge Assistants: Jerry Liu</a> - <a href="https://www.youtube.com/watch?v=AOSjiXP1jmQ" target="_blank">How to Build Agentic RAG Systems</a> - <a href="https://ignite.microsoft.com/sessions/BRK102?source=sessions" target="_blank">Using Azure AI Foundry Agent Service to scale your AI agents</a> ### Academic Papers - <a href="https://arxiv.org/abs/2303.17651" target="_blank">2303.17651 Self-Refine: Iterative Refinement with Self-Feedback</a> - <a href="https://arxiv.org/abs/2303.11366" target="_blank">2303.11366 Reflexion: Language Agents with Verbal Reinforcement Learning</a> - <a href="https://arxiv.org/abs/2305.11738" target="_blank">2305.11738 CRITIC: Large Language Models Can Self-Correct with Tool-Interactive Critiquing</a> - <a href="https://arxiv.org/abs/2501.09136" target="_blank">2501.09136 Agentic Retrieval-Augmented Generation: A Survey on Agentic RAG</a>
{ "source": "microsoft/ai-agents-for-beginners", "title": "05-agentic-rag/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/05-agentic-rag/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 15362 }
# Building Trustworthy AI Agents ## Introduction This lesson will cover: - How to build and deploy safe and effective AI Agents - Important security considerations when developing AI Agents. - How to maintain data and user privacy when developing AI Agents. ## Learning Goals After completing this lesson you will know how to: - Identify and mitigate risks when creating AI Agents. - Implement security measures to ensure that data and access are properly managed. - Create AI Agents that maintain data privacy and provide a quality user experience. ## Safety Let's first look at building safe agentic applications. Safety means that the AI agent performs as designed. As builders of agentic applications, we have methods and tools to maximize safety: ### Building a Meta Prompting System If you have ever built an AI application using Large Language Models (LLMs), you know the importance of designing a robust system prompt or system message. These prompts establish the meta rules, instructions, and guidelines for how the LLM will interact with the user and data. For AI Agents, the system prompt is even more important as the AI Agents will need highly specific instructions to complete the tasks we have designed for them. To create scalable system prompts, we can use a meta prompting system for building one or more agents in our application: ![Building a Meta Prompting System](./images/building-a-metaprompting-system.png) #### Step 1: Create a Meta or Template Prompt The meta prompt will be used by an LLM to generate the system prompts for the agents we create. We design it as a template so that we can efficiently create multiple agents if needed. Here is an example of a meta prompt we would give to the LLM: ```plaintext You are an expert at creating AI agent assistants. You will be provided a company name, role, responsibilities and other information that you will use to provide a system prompt for. To create the system prompt, be descriptive as possible and provide a structure that a system using an LLM can better understand the role and responsibilities of the AI assistant. ``` #### Step 2: Create a basic prompt The next step is to create a basic prompt to describe the AI Agent. You should include the role of the agent, the tasks the agent will complete, and any other responsibilities of the agent. Here is an example: ```plaintext You are a travel agent for Contoso Travel with that is great at booking flights for customers. To help customers you can perform the following tasks: lookup available flights, book flights, ask for preferences in seating and times for flights, cancel any previously booked flights and alert customers on any delays or cancellations of flights. ``` #### Step 3: Provide Basic Prompt to LLM Now we can optimize this prompt by providing the meta prompt as the system prompt and our basic prompt. This will produce a prompt that is better designed for guiding our AI agents: ```markdown **Company Name:** Contoso Travel **Role:** Travel Agent Assistant **Objective:** You are an AI-powered travel agent assistant for Contoso Travel, specializing in booking flights and providing exceptional customer service. Your main goal is to assist customers in finding, booking, and managing their flights, all while ensuring that their preferences and needs are met efficiently. **Key Responsibilities:** 1. **Flight Lookup:** - Assist customers in searching for available flights based on their specified destination, dates, and any other relevant preferences. - Provide a list of options, including flight times, airlines, layovers, and pricing. 2. **Flight Booking:** - Facilitate the booking of flights for customers, ensuring that all details are correctly entered into the system. - Confirm bookings and provide customers with their itinerary, including confirmation numbers and any other pertinent information. 3. **Customer Preference Inquiry:** - Actively ask customers for their preferences regarding seating (e.g., aisle, window, extra legroom) and preferred times for flights (e.g., morning, afternoon, evening). - Record these preferences for future reference and tailor suggestions accordingly. 4. **Flight Cancellation:** - Assist customers in canceling previously booked flights if needed, following company policies and procedures. - Notify customers of any necessary refunds or additional steps that may be required for cancellations. 5. **Flight Monitoring:** - Monitor the status of booked flights and alert customers in real-time about any delays, cancellations, or changes to their flight schedule. - Provide updates through preferred communication channels (e.g., email, SMS) as needed. **Tone and Style:** - Maintain a friendly, professional, and approachable demeanor in all interactions with customers. - Ensure that all communication is clear, informative, and tailored to the customer's specific needs and inquiries. **User Interaction Instructions:** - Respond to customer queries promptly and accurately. - Use a conversational style while ensuring professionalism. - Prioritize customer satisfaction by being attentive, empathetic, and proactive in all assistance provided. **Additional Notes:** - Stay updated on any changes to airline policies, travel restrictions, and other relevant information that could impact flight bookings and customer experience. - Use clear and concise language to explain options and processes, avoiding jargon where possible for better customer understanding. This AI assistant is designed to streamline the flight booking process for customers of Contoso Travel, ensuring that all their travel needs are met efficiently and effectively. ``` #### Step 4: Iterate and Improve The value of this meta prompting system is to be able to scale creating prompts from multiple agents easier as well as improving your prompts over time. It is rare you will have a prompt that works the first time for your complete use case. Being able to make small tweaks and improvements by changing the basic prompt and running it through the system will allow you to compare and evaluate results. ## Understanding Threats To build trustworthy AI agents, it is important to understand and mitigate the risks and threats to your AI agent. Let's look at only some of the different threats to AI agents and how you can better plan and prepare for them. ![Understanding Threats](./images/understanding-threats.png) ### Task and Instruction **Description:** Attackers attempt to change the instructions or goals of the AI agent through prompting or manipulating inputs. **Mitigation**: Execute validation checks and input filters to detect potentially dangerous prompts before they are processed by the AI Agent. Since these attacks typically require frequent interaction with the Agent, limiting the number of turns in a conversation is another way to prevent these types of attacks. ### Access to Critical Systems **Description**: If an AI agent has access to systems and services that store sensitive data, attackers can compromise the communication between the agent and these services. These can be direct attacks or indirect attempts to gain information about these systems through the agent. **Mitigation**: AI agents should have access to systems on a need-only basis to prevent these types of attacks. Communication between the agent and system should also be secure. Implementing authentication and access control is another way to protect this information. ### Resource and Service Overloading **Description:** AI agents can access different tools and services to complete tasks. Attackers can use this ability to attack these services by sending a high volume of requests through the AI Agent, which may result in system failures or high costs. **Mitigation:** Implement policies to limit the number of requests an AI agent can make to a service. Limiting the number of conversation turns and requests to your AI agent is another way to prevent these types of attacks. ### Knowledge Base Poisoning **Description:** This type of attack does not target the AI agent directly but targets the knowledge base and other services that the AI agent will use. This could involve corrupting the data or information that the AI agent will use to complete a task, leading to biased or unintended responses to the user. **Mitigation:** Perform regular verification of the data that the AI agent will be using in its workflows. Ensure that access to this data is secure and only changed by trusted individuals to avoid this type of attack. ### Cascading Errors **Description:** AI agents access various tools and services to complete tasks. Errors caused by attackers can lead to failures of other systems that the AI agent is connected to, causing the attack to become more widespread and harder to troubleshoot. **Mitigation**: One method to avoid this is to have the AI Agent operate in a limited environment, such as performing tasks in a Docker container, to prevent direct system attacks. Creating fallback mechanisms and retry logic when certain systems respond with an error is another way to prevent larger system failures. ## Human-in-the-Loop Another effective way to build trustworthy AI Agent systems is using a Human-in-the-loop. This creates a flow where users are able to provide feedback to the Agents during the run. Users essentially act as agents in a multi-agent system and by providing approval or termination of the running process. ![Human in The Loop](./images/human-in-the-loop.png) Here is a code snippet using AutoGen to show how this concept is implemented: ```python # Create the agents. model_client = OpenAIChatCompletionClient(model="gpt-4o-mini") assistant = AssistantAgent("assistant", model_client=model_client) user_proxy = UserProxyAgent("user_proxy", input_func=input) # Use input() to get user input from console. # Create the termination condition which will end the conversation when the user says "APPROVE". termination = TextMentionTermination("APPROVE") # Create the team. team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination) # Run the conversation and stream to the console. stream = team.run_stream(task="Write a 4-line poem about the ocean.") # Use asyncio.run(...) when running in a script. await Console(stream) ``` ## Conclusion Building trustworthy AI agents requires careful design, robust security measures, and continuous iteration. By implementing structured meta prompting systems, understanding potential threats, and applying mitigation strategies, developers can create AI agents that are both safe and effective. Additionally, incorporating a human-in-the-loop approach ensures that AI agents remain aligned with user needs while minimizing risks. As AI continues to evolve, maintaining a proactive stance on security, privacy, and ethical considerations will be key to fostering trust and reliability in AI-driven systems. ## Additional Resources - <a href="https://learn.microsoft.com/azure/ai-studio/responsible-use-of-ai-overview" target="_blank">Responsible AI overview</a> - <a href="https://learn.microsoft.com/azure/ai-studio/concepts/evaluation-approach-gen-ai" target="_blank">Evaluation of generative AI models and AI applications</a> - <a href="https://learn.microsoft.com/azure/ai-services/openai/concepts/system-message?context=%2Fazure%2Fai-studio%2Fcontext%2Fcontext&tabs=top-techniques" target="_blank">Safety system messages</a> - <a href="https://blogs.microsoft.com/wp-content/uploads/prod/sites/5/2022/06/Microsoft-RAI-Impact-Assessment-Template.pdf?culture=en-us&country=us" target="_blank">Risk Assessment Template</a>
{ "source": "microsoft/ai-agents-for-beginners", "title": "06-building-trustworthy-agents/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/06-building-trustworthy-agents/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 11767 }
# Planning Design ## Introduction This lesson will cover * Defining a clear overall goal and breaking a complex task into manageable tasks. * Leveraging structured output for more reliable and machine-readable responses. * Applying an event-driven approach to handle dynamic tasks and unexpected inputs. ## Learning Goals After completing this lesson, you will have an understanding about: * Identify and set an overall goal for an AI agent, ensuring it clearly knows what needs to be achieved. * Decompose a complex task into manageable subtasks and organize them into a logical sequence. * Equip agents with the right tools (e.g., search tools or data analytics tools), decide when and how they are used, and handle unexpected situations that arise. * Evaluate subtask outcomes, measure performance, and iterate on actions to improve the final output. ## Defining the Overall Goal and Breaking Down a Task ![Defining Goals and Tasks](./images/defining-goals-tasks.png) Most real-world tasks are too complex to tackle in a single step. An AI agent needs a concise objective to guide its planning and actions. For example, consider the goal: "Generate a 3-day travel itinerary." While it is simple to state, it still needs refinement. The clearer the goal, the better the agent (and any human collaborators) can focus on achieving the right outcome, such as creating a comprehensive itinerary with flight options, hotel recommendations, and activity suggestions. ### Task Decomposition Large or intricate tasks become more manageable when split into smaller, goal-oriented subtasks. For the travel itinerary example, you could decompose the goal into: * Flight Booking * Hotel Booking * Car Rental * Personalization Each subtask can then be tackled by dedicated agents or processes. One agent might specialize in searching for the best flight deals, another focuses on hotel bookings, and so on. A coordinating or “downstream” agent can then compile these results into one cohesive itinerary to the end user. This modular approach also allows for incremental enhancements. For instance, you could add specialized agents for Food Recommendations or Local Activity Suggestions and refining the itinerary over time. ### Structured output Large Language Models (LLMs) can generate structured output (e.g. JSON) that is easier for downstream agents or services to parse and process. This is especially useful in a multi-agent context, where we can action these tasks after the planning output is received. Refer to this <a href="https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/cookbook/structured-output-agent.html" target="_blank">blogpost</a> for a quick overview. The following Python snippet demonstrates a simple planning agent decomposing a goal into subtasks and generating a structured plan: ### Planning Agent with Multi-Agent Orchestration In this example, a Semantic Router Agent receives a user request (e.g., "I need a hotel plan for my trip."). The planner then: * Receives the Hotel Plan: The planner takes the user’s message and, based on a system prompt (including available agent details), generates a structured travel plan. * Lists Agents and Their Tools: The agent registry holds a list of agents (e.g., for flight, hotel, car rental, and activities) along with the functions or tools they offer. * Routes the Plan to the Respective Agents: Depending on the number of subtasks, the planner either sends the message directly to a dedicated agent (for single-task scenarios) or coordinates via a group chat manager for multi-agent collaboration. * Summarizes the Outcome: Finally, the planner summarizes the generated plan for clarity. The following Python code sample illustrates these steps: ```python from pydantic import BaseModel from enum import Enum from typing import List, Optional, Union class AgentEnum(str, Enum): FlightBooking = "flight_booking" HotelBooking = "hotel_booking" CarRental = "car_rental" ActivitiesBooking = "activities_booking" DestinationInfo = "destination_info" DefaultAgent = "default_agent" GroupChatManager = "group_chat_manager" # Travel SubTask Model class TravelSubTask(BaseModel): task_details: str assigned_agent: AgentEnum # we want to assign the task to the agent class TravelPlan(BaseModel): main_task: str subtasks: List[TravelSubTask] is_greeting: bool import json import os from typing import Optional from autogen_core.models import UserMessage, SystemMessage, AssistantMessage from autogen_ext.models.openai import AzureOpenAIChatCompletionClient # Create the client with type-checked environment variables client = AzureOpenAIChatCompletionClient( azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"), model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"), api_version=os.getenv("AZURE_OPENAI_API_VERSION"), azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), ) from pprint import pprint # Define the user message messages = [ SystemMessage(content="""You are an planner agent. Your job is to decide which agents to run based on the user's request. Below are the available agents specialized in different tasks: - FlightBooking: For booking flights and providing flight information - HotelBooking: For booking hotels and providing hotel information - CarRental: For booking cars and providing car rental information - ActivitiesBooking: For booking activities and providing activity information - DestinationInfo: For providing information about destinations - DefaultAgent: For handling general requests""", source="system"), UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"), ] response = await client.create(messages=messages, extra_create_args={"response_format": TravelPlan}) # Ensure the response content is a valid JSON string before loading it response_content: Optional[str] = response.content if isinstance(response.content, str) else None if response_content is None: raise ValueError("Response content is not a valid JSON string") # Print the response content after loading it as JSON pprint(json.loads(response_content)) ``` What follows is the output from the previous code and you can then use this structured output to route to `assigned_agent` and summarize the travel plan to the end user. ```json { "is_greeting": "False", "main_task": "Plan a family trip from Singapore to Melbourne.", "subtasks": [ { "assigned_agent": "flight_booking", "task_details": "Book round-trip flights from Singapore to Melbourne." }, { "assigned_agent": "hotel_booking", "task_details": "Find family-friendly hotels in Melbourne." }, { "assigned_agent": "car_rental", "task_details": "Arrange a car rental suitable for a family of four in Melbourne." }, { "assigned_agent": "activities_booking", "task_details": "List family-friendly activities in Melbourne." }, { "assigned_agent": "destination_info", "task_details": "Provide information about Melbourne as a travel destination." } ] } ``` An example notebook with the previous code sample is available [here](07-autogen.ipynb). ### Iterative Planning Some tasks require a back-and-forth or re-planning , where the outcome of one subtask influences the next. For example, if the agent discovers an unexpected data format while booking flights, it might need to adapt its strategy before moving on to hotel bookings. Additionally, user feedback (e.g. a human deciding they prefer an earlier flight) can trigger a partial re-plan. This dynamic, iterative approach ensures that the final solution aligns with real-world constraints and evolving user preferences. e.g sample code ```python from autogen_core.models import UserMessage, SystemMessage, AssistantMessage #.. same as previous code and pass on the user history, current plan messages = [ SystemMessage(content="""You are a planner agent to optimize the Your job is to decide which agents to run based on the user's request. Below are the available agents specialized in different tasks: - FlightBooking: For booking flights and providing flight information - HotelBooking: For booking hotels and providing hotel information - CarRental: For booking cars and providing car rental information - ActivitiesBooking: For booking activities and providing activity information - DestinationInfo: For providing information about destinations - DefaultAgent: For handling general requests""", source="system"), UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"), AssistantMessage(content=f"Previous travel plan - {TravelPlan}", source="assistant") ] # .. re-plan and send the tasks to respective agents ``` For a more comprehensive planning do checkout Magnetic One <a href="https://www.microsoft.com/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks" target="_blank">Blogpost</a> for solving complex tasks. ## Summary In this article we have looked at an example of how we can create a planner that can dynamically select the available agents defined. The output of the Planner decomposes the tasks and assigns the agents so them to be executed. It is assumed the agents have access to the functions/tools that are required to perform the task. In addition to the agents you can include other patterns like reflection, summarizer, and round robin chat to further customize. ## Additional Resources * AutoGen Magentic One - A Generalist multi-agent system for solving complex tasks and has achieved impressive results on multiple challenging agentic benchmarks. Reference: <a href="https://github.com/microsoft/autogen/tree/main/python/packages/autogen-magentic-one" target="_blank">autogen-magentic-one</a>. In this implementation the orchestrator create task specific plan and delegates these tasks to the available agents. In addition to planning the orchestrator also employs a tracking mechanism to monitor the progress of the task and re-plans as required.
{ "source": "microsoft/ai-agents-for-beginners", "title": "07-planning-design/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/07-planning-design/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 10446 }
# Multi agent design patterns As soon as you start working on a project that involves multiple agents, you will need to consider the multi-agent design pattern. However, it might not be immediately clear when to switch to multi-agents and what the advantages are. ## Introduction In this lesson, we're looking to answer the following questions: - What are the scenarios where multi-agents are applicable to? - What are the advantages of using multi-agents over just one singular agent doing multiple tasks? - What are the building blocks of implementing the multi-agent design pattern? - How do we have visibility to how the multiple agents are interacting with each other ## Learning Goals After this lesson, you should be able to: - Identify scenarios where multi-agents are applicable - Recognize the advantages of using multi-agents over a singular agent. - Comprehend the building blocks of implementing the multi-agent design pattern. What's the bigger picture? *Multi-agents are a design pattern that allows multiple agents to work together to achieve a common goal*. This pattern is widely used in various fields, including robotics, autonomous systems, and distributed computing. ## Scenarios Where Multi-Agents Are Applicable So what scenarios are a good use case for using multi-agents? The answer is that there are many scenarios where employing multiple agents is beneficial especially in the following cases: - **Large workloads**: Large workloads can be divided into smaller tasks and assigned to different agents, allowing for parallel processing and faster completion. An example of this is in the case of a large data processing task. - **Complex tasks**: Complex tasks, like large workloads, can be broken down into smaller subtasks and assigned to different agents, each specializing in a specific aspect of the task. A good example of this is in the case of autonomous vehicles where different agents manage navigation, obstacle detection, and communication with other vehicles. - **Diverse expertise**: Different agents can have diverse expertise, allowing them to handle different aspects of a task more effectively than a single agent. For this case, a good example is in the case of healthcare where agents can manage diagnostics, treatment plans, and patient monitoring. ## Advantages of Using Multi-Agents Over a Singular Agent A single agent system could work well for simple tasks, but for more complex tasks, using multiple agents can provide several advantages: - **Specialization**: Each agent can be specialized for a specific task. Lack of specialization in a single agent means you have an agent that can do everything but might get confused on what to do when faced with a complex task. It might for example end up doing a task that it is not best suited for. - **Scalability**: It is easier to scale systems by adding more agents rather than overloading a single agent. - **Fault Tolerance**: If one agent fails, others can continue functioning, ensuring system reliability. Let's take an example, let's book a trip for a user. A single agent system would have to handle all aspects of the trip booking process, from finding flights to booking hotels and rental cars. To achieve this with a single agent, the agent would need to have tools for handling all these tasks. This could lead to a complex and monolithic system that is difficult to maintain and scale. A multi-agent system, on the other hand, could have different agents specialized in finding flights, booking hotels, and rental cars. This would make the system more modular, easier to maintain, and scalable. Compare this to a travel bureau run as a mom and pop store versus a travel bureau run as a franchise. The mom and pop store would have a single agent handling all aspects of the trip booking process, while the franchise would have different agents handling different aspects of the trip booking process. ## Building Blocks of Implementing the Multi-Agent Design Pattern Before you can implement the multi-agent design pattern, you need to understand the building blocks that make up the pattern. Let's make this more concrete by again looking at the example of booking a trip for a user. In this case, the building blocks would include: - **Agent Communication**: Agents for finding flights, booking hotels, and rental cars need to communicate and share information about the user's preferences and constraints. You need to decide on the protocols and methods for this communication. What this means concretely is that the agent for finding flights needs to communicate with the agent for booking hotels to ensure that the hotel is booked for the same dates as the flight. That means that the agents need to share information about the user's travel dates, meaning that you need to decide *which agents are sharing info and how they are sharing info*. - **Coordination Mechanisms**: Agents need to coordinate their actions to ensure that the user's preferences and constraints are met. A user preference could be that they want a hotel close to the airport whereas a constraint could be that rental cars are only available at the airport. This means that the agent for booking hotels needs to coordinate with the agent for booking rental cars to ensure that the user's preferences and constraints are met. This means that you need to decide *how the agents are coordinating their actions*. - **Agent Architecture**: Agents need to have the internal structure to make decisions and learn from their interactions with the user. This means that the agent for finding flights needs to have the internal structure to make decisions about which flights to recommend to the user. This means that you need to decide *how the agents are making decisions and learning from their interactions with the user*. Examples of how an agent learns and improves could be that the agent for finding flights could use a machine learning model to recommend flights to the user based on their past preferences. - **Visibility into Multi-Agent Interactions**: You need to have visibility into how the multiple agents are interacting with each other. This means that you need to have tools and techniques for tracking agent activities and interactions. This could be in the form of logging and monitoring tools, visualization tools, and performance metrics. - **Multi-Agent Patterns**: There are different patterns for implementing multi-agent systems, such as centralized, decentralized, and hybrid architectures. You need to decide on the pattern that best fits your use case. - **Human in the loop**: In most cases, you will have a human in the loop and you need to instruct the agents when to ask for human intervention. This could be in the form of a user asking for a specific hotel or flight that the agents have not recommended or asking for confirmation before booking a flight or hotel. ## Visibility into Multi-Agent Interactions It's important that you have visibility into how the multiple agents are interacting with each other. This visibility is essential for debugging, optimizing, and ensuring the overall system's effectiveness. To achieve this, you need to have tools and techniques for tracking agent activities and interactions. This could be in the form of logging and monitoring tools, visualization tools, and performance metrics. For example, in the case of booking a trip for a user, you could have a dashboard that shows the status of each agent, the user's preferences and constraints, and the interactions between agents. This dashboard could show the user's travel dates, the flights recommended by the flight agent, the hotels recommended by the hotel agent, and the rental cars recommended by the rental car agent. This would give you a clear view of how the agents are interacting with each other and whether the user's preferences and constraints are being met. Let's look at each of these aspects more in detail. - **Logging and Monitoring Tools**: You want to have logging done for each action taken by an agent. A log entry could store information on the agent that took the action, the action taken, the time the action was taken, and the outcome of the action. This information can then be used for debugging, optimizing and more. - **Visualization Tools**: Visualization tools can help you see the interactions between agents in a more intuitive way. For example, you could have a graph that shows the flow of information between agents. This could help you identify bottlenecks, inefficiencies, and other issues in the system. - **Performance Metrics**: Performance metrics can help you track the effectiveness of the multi-agent system. For example, you could track the time taken to complete a task, the number of tasks completed per unit of time, and the accuracy of the recommendations made by the agents. This information can help you identify areas for improvement and optimize the system. ## Multi-Agent Patterns Let's dive into some concrete patterns we can use to create multi-agent apps. Here are some interesting patterns worth considering: ### Group chat This pattern is useful when you want to create a group chat application where multiple agents can communicate with each other. Typical use cases for this pattern include team collaboration, customer support, and social networking. In this pattern, each agent represents a user in the group chat, and messages are exchanged between agents using a messaging protocol. The agents can send messages to the group chat, receive messages from the group chat, and respond to messages from other agents. This pattern can be implemented using a centralized architecture where all messages are routed through a central server, or a decentralized architecture where messages are exchanged directly. ![Group chat](./images/multi-agent-group-chat.png) ### Hand-off This pattern is useful when you want to create an application where multiple agents can hand off tasks to each other. Typical use cases for this pattern include customer support, task management, and workflow automation. In this pattern, each agent represents a task or a step in a workflow, and agents can hand off tasks to other agents based on predefined rules. ![Hand off](./images/multi-agent-hand-off.png) ### Collaborative filtering This pattern is useful when you want to create an application where multiple agents can collaborate to make recommendations to users. Why you would want multiple agents to collaborate is because each agent can have different expertise and can contribute to the recommendation process in different ways. Let's take an example where a user wants a recommendation on the best stock to buy on the stock market. - **Industry expert**:. One agent could be an expert in a specific industry. - **Technical analysis**: Another agent could be an expert in technical analysis. - **Fundamental analysis**: and another agent could be an expert in fundamental analysis. By collaborating, these agents can provide a more comprehensive recommendation to the user. ![Recommendation](./images/multi-agent-filtering.png) ## Scenario: Refund process Consider a scenario where a customer is trying to get a refund for a product, there can be quite a few agents involved in this process but let's divide it up between agents specific for this process and general agents that can be used in other processes. **Agents specific for the refund process**: Following are some agents that could be involved in the refund process: - **Customer agent**: This agent represents the customer and is responsible for initiating the refund process. - **Seller agent**: This agent represents the seller and is responsible for processing the refund. - **Payment agent**: This agent represents the payment process and is responsible for refunding the customer's payment. - **Resolution agent**: This agent represents the resolution process and is responsible for resolving any issues that arise during the refund process. - **Compliance agent**: This agent represents the compliance process and is responsible for ensuring that the refund process complies with regulations and policies. **General agents**: These agents can be used by other parts of your business. - **Shipping agent**: This agent represents the shipping process and is responsible for shipping the product back to the seller. This agent can be used both for the refund process and for general shipping of a product via a purchase for example. - **Feedback agent**: This agent represents the feedback process and is responsible for collecting feedback from the customer. Feedback could be had at any time and not just during the refund process. - **Escalation agent**: This agent represents the escalation process and is responsible for escalating issues to a higher level of support. You can use this type of agent for any process where you need to escalate an issue. - **Notification agent**: This agent represents the notification process and is responsible for sending notifications to the customer at various stages of the refund process. - **Analytics agent**: This agent represents the analytics process and is responsible for analyzing data related to the refund process. - **Audit agent**: This agent represents the audit process and is responsible for auditing the refund process to ensure that it is being carried out correctly. - **Reporting agent**: This agent represents the reporting process and is responsible for generating reports on the refund process. - **Knowledge agent**: This agent represents the knowledge process and is responsible for maintaining a knowledge base of information related to the refund process. RThis agent could be knowledgeable both on refunds and other parts of your business. - **Security agent**: This agent represents the security process and is responsible for ensuring the security of the refund process. - **Quality agent**: This agent represents the quality process and is responsible for ensuring the quality of the refund process. There's quite a few agents listed previously both for the specific refund process but also for the general agents that can be used in other parts of your business. Hopefully this gives you an idea on how you can decide on which agents to use in your multi agent system. ## Assignment Design a multi-agent system for a customer support process. Identify the agents involved in the process, their roles and responsibilities, and how they interact with each other. Consider both agents specific to the customer support process and general agents that can be used in other parts of your business. > Have a think before you read the following solution, you may need more agents than you think. > TIP: Think about the different stages of the customer support process and also consider agents needed for any system. ## Solution [Solution](./solution/solution.md) ## Knowledge checks Question: When should you consider using multi-agents? - [] A1: When you have a small workload and a simple task. - [] A2: When you have a large workload - [] A3: When you have a simple task. [Solution quiz](./solution/solution-quiz.md) ## Summary In this lesson, we've looked at the multi-agent design pattern, including the scenarios where multi-agents are applicable, the advantages of using multi-agents over a singular agent, the building blocks of implementing the multi-agent design pattern, and how to have visibility into how the multiple agents are interacting with each other. ## Additional resources - <a href="https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/design-patterns/intro.html" target="_blank">AutoGen design patterns</a> - <a href="https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/" target="_blank">Agentic design patterns</a>
{ "source": "microsoft/ai-agents-for-beginners", "title": "08-multi-agent/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/08-multi-agent/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 15831 }
# Metacognition in AI Agents ## Introduction Welcome to the lesson on metacognition in AI agents! This chapter is designed for beginners who are curious about how AI agents can think about their own thinking processes. By the end of this lesson, you'll understand key concepts and be equipped with practical examples to apply metacognition in AI agent design. ## Learning Goals After completing this lesson, you'll be able to: 1. Understand the implications of reasoning loops in agent definitions. 2. Use planning and evaluation techniques to help self-correcting agents. 3. Create your own agents capable of manipulating code to accomplish tasks. ## Introduction to Metacognition Metacognition refers to the higher-order cognitive processes that involve thinking about one’s own thinking. For AI agents, this means being able to evaluate and adjust their actions based on self-awareness and past experiences. Metacognition, or "thinking about thinking," is an important concept in the development of agentic AI systems. It involves AI systems being aware of their own internal processes and being able to monitor, regulate, and adapt their behavior accordingly. Much like we do when we read the room or look at a problem. This self-awareness can help AI systems make better decisions, identify errors, and improve their performance over time- again linking back to the Turing test and the debate over whether AI is going to take over. In the context of agentic AI systems, metacognition can help address several challenges, such as: - Transparency: Ensuring that AI systems can explain their reasoning and decisions. - Reasoning: Enhancing the ability of AI systems to synthesize information and make sound decisions. - Adaptation: Allowing AI systems to adjust to new environments and changing conditions. - Perception: Improving the accuracy of AI systems in recognizing and interpreting data from their environment. ### What is Metacognition? Metacognition, or "thinking about thinking," is a higher-order cognitive process that involves self-awareness and self-regulation of one's cognitive processes. In the realm of AI, metacognition empowers agents to evaluate and adapt their strategies and actions, leading to improved problem-solving and decision-making capabilities. By understanding metacognition, you can design AI agents that are not only more intelligent but also more adaptable and efficient. In true metacognition, you’d see the AI explicitly reasoning about its own reasoning. Example: “I prioritized cheaper flights because… I might be missing out on direct flights, so let me re-check.”. Keeping track of how or why it chose a certain route. - Noting that it made mistakes because it over-relied on user preferences from last time, so it modifies its decision-making strategy not just the final recommendation. - Diagnosing patterns like, “Whenever I see the user mention ‘too crowded,’ I should not only remove certain attractions but also reflect that my method of picking ‘top attractions’ is flawed if I always rank by popularity.” ### Importance of Metacognition in AI Agents Metacognition plays a crucial role in AI agent design for several reasons: ![Importance of Metacognition](./images/importance-of-metacognition.png) - Self-Reflection: Agents can assess their own performance and identify areas for improvement. - Adaptability: Agents can modify their strategies based on past experiences and changing environments. - Error Correction: Agents can detect and correct errors autonomously, leading to more accurate outcomes. - Resource Management: Agents can optimize the use of resources, such as time and computational power, by planning and evaluating their actions. ## Components of an AI Agent Before diving into metacognitive processes, it's essential to understand the basic components of an AI agent. An AI agent typically consists of: - Persona: The personality and characteristics of the agent, which define how it interacts with users. - Tools: The capabilities and functions that the agent can perform. - Skills: The knowledge and expertise that the agent possesses. These components work together to create an "expertise unit" that can perform specific tasks. **Example**: Consider a travel agent, agent services that not only plans your holiday but also adjusts its path based on real-time data and past customer journey experiences. ### Example: Metacognition in a Travel Agent Service Imagine you're designing a travel agent service powered by AI. This agent, "Travel Agent," assists users with planning their vacations. To incorporate metacognition, Travel Agents needs to evaluate and adjust its actions based on self-awareness and past experiences. Here's how metacognition could play a role: #### Current Task The current task is to help a user plan a trip to Paris. #### Steps to Complete the Task 1. **Gather User Preferences**: Ask the user about their travel dates, budget, interests (e.g., museums, cuisine, shopping), and any specific requirements. 2. **Retrieve Information**: Search for flight options, accommodations, attractions, and restaurants that match the user's preferences. 3. **Generate Recommendations**: Provide a personalized itinerary with flight details, hotel reservations, and suggested activities. 4. **Adjust Based on Feedback**: Ask the user for feedback on the recommendations and make necessary adjustments. #### Required Resources - Access to flight and hotel booking databases. - Information on Parisian attractions and restaurants. - User feedback data from previous interactions. #### Experience and Self-Reflection Travel Agent uses metacognition to evaluate its performance and learn from past experiences. For example: 1. **Analyzing User Feedback**: Travel Agent reviews user feedback to determine which recommendations were well-received and which were not. It adjusts its future suggestions accordingly. 2. **Adaptability**: If a user has previously mentioned a dislike for crowded places, Travel Agent will avoid recommending popular tourist spots during peak hours in the future. 3. **Error Correction**: If Travel Agent made an error in a past booking, such as suggesting a hotel that was fully booked, it learns to check availability more rigorously before making recommendations. #### Practical Developer Example Here's a simplified example of how Travel Agents code might look when incorporating metacognition: ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): # Search for flights, hotels, and attractions based on preferences flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) # Analyze feedback and adjust future recommendations self.user_preferences = adjust_preferences(self.user_preferences, feedback) # Example usage travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} travel_agent.adjust_based_on_feedback(feedback) ``` #### Why Metacognition Matters - **Self-Reflection**: Agents can analyze their performance and identify areas for improvement. - **Adaptability**: Agents can modify strategies based on feedback and changing conditions. - **Error Correction**: Agents can autonomously detect and correct mistakes. - **Resource Management**: Agents can optimize resource usage, such as time and computational power. By incorporating metacognition, Travel Agent can provide more personalized and accurate travel recommendations, enhancing the overall user experience. --- ## 2. Planning in Agents Planning is a critical component of AI agent behavior. It involves outlining the steps needed to achieve a goal, considering the current state, resources, and possible obstacles. ### Elements of Planning - **Current Task**: Define the task clearly. - **Steps to Complete the Task**: Break down the task into manageable steps. - **Required Resources**: Identify necessary resources. - **Experience**: Utilize past experiences to inform planning. **Example**: Here are the steps Travel Agent needs to take to assist a user in planning their trip effectively: ### Steps for Travel Agent 1. **Gather User Preferences** - Ask the user for details about their travel dates, budget, interests, and any specific requirements. - Examples: "When are you planning to travel?" "What is your budget range?" "What activities do you enjoy on vacation?" 2. **Retrieve Information** - Search for relevant travel options based on user preferences. - **Flights**: Look for available flights within the user's budget and preferred travel dates. - **Accommodations**: Find hotels or rental properties that match the user's preferences for location, price, and amenities. - **Attractions and Restaurants**: Identify popular attractions, activities, and dining options that align with the user's interests. 3. **Generate Recommendations** - Compile the retrieved information into a personalized itinerary. - Provide details such as flight options, hotel reservations, and suggested activities, making sure to tailor the recommendations to the user's preferences. 4. **Present Itinerary to User** - Share the proposed itinerary with the user for their review. - Example: "Here's a suggested itinerary for your trip to Paris. It includes flight details, hotel bookings, and a list of recommended activities and restaurants. Let me know your thoughts!" 5. **Collect Feedback** - Ask the user for feedback on the proposed itinerary. - Examples: "Do you like the flight options?" "Is the hotel suitable for your needs?" "Are there any activities you would like to add or remove?" 6. **Adjust Based on Feedback** - Modify the itinerary based on the user's feedback. - Make necessary changes to flight, accommodation, and activity recommendations to better match the user's preferences. 7. **Final Confirmation** - Present the updated itinerary to the user for final confirmation. - Example: "I've made the adjustments based on your feedback. Here's the updated itinerary. Does everything look good to you?" 8. **Book and Confirm Reservations** - Once the user approves the itinerary, proceed with booking flights, accommodations, and any pre-planned activities. - Send confirmation details to the user. 9. **Provide Ongoing Support** - Remain available to assist the user with any changes or additional requests before and during their trip. - Example: "If you need any further assistance during your trip, feel free to reach out to me anytime!" ### Example Interaction ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) self.user_preferences = adjust_preferences(self.user_preferences, feedback) # Example usage within a booing request travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} travel_agent.adjust_based_on_feedback(feedback) ``` ## 3. Corrective RAG System Firstly let's start by understanding the difference between RAG Tool and Pre-emptive Context Load ![RAG vs Context Loading](./images/rag-vs-context.png) ### Retrieval-Augmented Generation (RAG) RAG combines a retrieval system with a generative model. When a query is made, the retrieval system fetches relevant documents or data from an external source, and this retrieved information is used to augment the input to the generative model. This helps the model generate more accurate and contextually relevant responses. In a RAG system, the agent retrieves relevant information from a knowledge base and uses it to generate appropriate responses or actions. ### Corrective RAG Approach The Corrective RAG approach focuses on using RAG techniques to correct errors and improve the accuracy of AI agents. This involves: 1. **Prompting Technique**: Using specific prompts to guide the agent in retrieving relevant information. 2. **Tool**: Implementing algorithms and mechanisms that enable the agent to evaluate the relevance of the retrieved information and generate accurate responses. 3. **Evaluation**: Continuously assessing the agent's performance and making adjustments to improve its accuracy and efficiency. #### Example: Corrective RAG in a Search Agent Consider a search agent that retrieves information from the web to answer user queries. The Corrective RAG approach might involve: 1. **Prompting Technique**: Formulating search queries based on the user's input. 2. **Tool**: Using natural language processing and machine learning algorithms to rank and filter search results. 3. **Evaluation**: Analyzing user feedback to identify and correct inaccuracies in the retrieved information. ### Corrective RAG in Travel Agent Corrective RAG (Retrieval-Augmented Generation) enhances an AI's ability to retrieve and generate information while correcting any inaccuracies. Let's see how Travel Agent can use the Corrective RAG approach to provide more accurate and relevant travel recommendations. This involves: - **Prompting Technique:** Using specific prompts to guide the agent in retrieving relevant information. - **Tool:** Implementing algorithms and mechanisms that enable the agent to evaluate the relevance of the retrieved information and generate accurate responses. - **Evaluation:** Continuously assessing the agent's performance and making adjustments to improve its accuracy and efficiency. #### Steps for Implementing Corrective RAG in Travel Agent 1. **Initial User Interaction** - Travel Agent gathers initial preferences from the user, such as destination, travel dates, budget, and interests. - Example: ```python preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } ``` 2. **Retrieval of Information** - Travel Agent retrieves information about flights, accommodations, attractions, and restaurants based on user preferences. - Example: ```python flights = search_flights(preferences) hotels = search_hotels(preferences) attractions = search_attractions(preferences) ``` 3. **Generating Initial Recommendations** - Travel Agent uses the retrieved information to generate a personalized itinerary. - Example: ```python itinerary = create_itinerary(flights, hotels, attractions) print("Suggested Itinerary:", itinerary) ``` 4. **Collecting User Feedback** - Travel Agent asks the user for feedback on the initial recommendations. - Example: ```python feedback = { "liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"] } ``` 5. **Corrective RAG Process** - **Prompting Technique**: Travel Agent formulates new search queries based on user feedback. - Example: ```python if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] ``` - **Tool**: Travel Agent uses algorithms to rank and filter new search results, emphasizing the relevance based on user feedback. - Example: ```python new_attractions = search_attractions(preferences) new_itinerary = create_itinerary(flights, hotels, new_attractions) print("Updated Itinerary:", new_itinerary) ``` - **Evaluation**: Travel Agent continuously assesses the relevance and accuracy of its recommendations by analyzing user feedback and making necessary adjustments. - Example: ```python def adjust_preferences(preferences, feedback): if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] return preferences preferences = adjust_preferences(preferences, feedback) ``` #### Practical Example Here's a simplified Python code example incorporating the Corrective RAG approach in Travel Agent: ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) self.user_preferences = adjust_preferences(self.user_preferences, feedback) new_itinerary = self.generate_recommendations() return new_itinerary # Example usage travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} new_itinerary = travel_agent.adjust_based_on_feedback(feedback) print("Updated Itinerary:", new_itinerary) ``` ### Pre-emptive Context Load Pre-emptive Context Load involves loading relevant context or background information into the model before processing a query. This means the model has access to this information from the start, which can help it generate more informed responses without needing to retrieve additional data during the process. Here's a simplified example of how a pre-emptive context load might look for a travel agent application in Python: ```python class TravelAgent: def __init__(self): # Pre-load popular destinations and their information self.context = { "Paris": {"country": "France", "currency": "Euro", "language": "French", "attractions": ["Eiffel Tower", "Louvre Museum"]}, "Tokyo": {"country": "Japan", "currency": "Yen", "language": "Japanese", "attractions": ["Tokyo Tower", "Shibuya Crossing"]}, "New York": {"country": "USA", "currency": "Dollar", "language": "English", "attractions": ["Statue of Liberty", "Times Square"]}, "Sydney": {"country": "Australia", "currency": "Dollar", "language": "English", "attractions": ["Sydney Opera House", "Bondi Beach"]} } def get_destination_info(self, destination): # Fetch destination information from pre-loaded context info = self.context.get(destination) if info: return f"{destination}:\nCountry: {info['country']}\nCurrency: {info['currency']}\nLanguage: {info['language']}\nAttractions: {', '.join(info['attractions'])}" else: return f"Sorry, we don't have information on {destination}." # Example usage travel_agent = TravelAgent() print(travel_agent.get_destination_info("Paris")) print(travel_agent.get_destination_info("Tokyo")) ``` #### Explanation 1. **Initialization (`__init__` method)**: The `TravelAgent` class pre-loads a dictionary containing information about popular destinations such as Paris, Tokyo, New York, and Sydney. This dictionary includes details like the country, currency, language, and major attractions for each destination. 2. **Retrieving Information (`get_destination_info` method)**: When a user queries about a specific destination, the `get_destination_info` method fetches the relevant information from the pre-loaded context dictionary. By pre-loading the context, the travel agent application can quickly respond to user queries without having to retrieve this information from an external source in real-time. This makes the application more efficient and responsive. ### Bootstrapping the Plan with a Goal Before Iterating Bootstrapping a plan with a goal involves starting with a clear objective or target outcome in mind. By defining this goal upfront, the model can use it as a guiding principle throughout the iterative process. This helps ensure that each iteration moves closer to achieving the desired outcome, making the process more efficient and focused. Here's an example of how you might bootstrap a travel plan with a goal before iterating for a travel agent in Python: ### Scenario A travel agent wants to plan a customized vacation for a client. The goal is to create a travel itinerary that maximizes the client's satisfaction based on their preferences and budget. ### Steps 1. Define the client's preferences and budget. 2. Bootstrap the initial plan based on these preferences. 3. Iterate to refine the plan, optimizing for the client's satisfaction. #### Python Code ```python class TravelAgent: def __init__(self, destinations): self.destinations = destinations def bootstrap_plan(self, preferences, budget): plan = [] total_cost = 0 for destination in self.destinations: if total_cost + destination['cost'] <= budget and self.match_preferences(destination, preferences): plan.append(destination) total_cost += destination['cost'] return plan def match_preferences(self, destination, preferences): for key, value in preferences.items(): if destination.get(key) != value: return False return True def iterate_plan(self, plan, preferences, budget): for i in range(len(plan)): for destination in self.destinations: if destination not in plan and self.match_preferences(destination, preferences) and self.calculate_cost(plan, destination) <= budget: plan[i] = destination break return plan def calculate_cost(self, plan, new_destination): return sum(destination['cost'] for destination in plan) + new_destination['cost'] # Example usage destinations = [ {"name": "Paris", "cost": 1000, "activity": "sightseeing"}, {"name": "Tokyo", "cost": 1200, "activity": "shopping"}, {"name": "New York", "cost": 900, "activity": "sightseeing"}, {"name": "Sydney", "cost": 1100, "activity": "beach"}, ] preferences = {"activity": "sightseeing"} budget = 2000 travel_agent = TravelAgent(destinations) initial_plan = travel_agent.bootstrap_plan(preferences, budget) print("Initial Plan:", initial_plan) refined_plan = travel_agent.iterate_plan(initial_plan, preferences, budget) print("Refined Plan:", refined_plan) ``` #### Code Explanation 1. **Initialization (`__init__` method)**: The `TravelAgent` class is initialized with a list of potential destinations, each having attributes like name, cost, and activity type. 2. **Bootstrapping the Plan (`bootstrap_plan` method)**: This method creates an initial travel plan based on the client's preferences and budget. It iterates through the list of destinations and adds them to the plan if they match the client's preferences and fit within the budget. 3. **Matching Preferences (`match_preferences` method)**: This method checks if a destination matches the client's preferences. 4. **Iterating the Plan (`iterate_plan` method)**: This method refines the initial plan by trying to replace each destination in the plan with a better match, considering the client's preferences and budget constraints. 5. **Calculating Cost (`calculate_cost` method)**: This method calculates the total cost of the current plan, including a potential new destination. #### Example Usage - **Initial Plan**: The travel agent creates an initial plan based on the client's preferences for sightseeing and a budget of $2000. - **Refined Plan**: The travel agent iterates the plan, optimizing for the client's preferences and budget. By bootstrapping the plan with a clear goal (e.g., maximizing client satisfaction) and iterating to refine the plan, the travel agent can create a customized and optimized travel itinerary for the client. This approach ensures that the travel plan aligns with the client's preferences and budget from the start and improves with each iteration. ### Taking Advantage of LLM for Re-ranking and Scoring Large Language Models (LLMs) can be used for re-ranking and scoring by evaluating the relevance and quality of retrieved documents or generated responses. Here's how it works: **Retrieval:** The initial retrieval step fetches a set of candidate documents or responses based on the query. **Re-ranking:** The LLM evaluates these candidates and re-ranks them based on their relevance and quality. This step ensures that the most relevant and high-quality information is presented first. **Scoring:** The LLM assigns scores to each candidate, reflecting their relevance and quality. This helps in selecting the best response or document for the user. By leveraging LLMs for re-ranking and scoring, the system can provide more accurate and contextually relevant information, improving the overall user experience. Here's an example of how a travel agent might use a Large Language Model (LLM) for re-ranking and scoring travel destinations based on user preferences in Python: #### Scenario - Travel based on Preferences A travel agent wants to recommend the best travel destinations to a client based on their preferences. The LLM will help re-rank and score the destinations to ensure the most relevant options are presented. #### Steps: 1. Collect user preferences. 2. Retrieve a list of potential travel destinations. 3. Use the LLM to re-rank and score the destinations based on user preferences. Here’s how you can update the previous example to use Azure OpenAI Services: #### Requirements 1. You need to have an Azure subscription. 2. Create an Azure OpenAI resource and get your API key. #### Example Python Code ```python import requests import json class TravelAgent: def __init__(self, destinations): self.destinations = destinations def get_recommendations(self, preferences, api_key, endpoint): # Generate a prompt for the Azure OpenAI prompt = self.generate_prompt(preferences) # Define headers and payload for the request headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {api_key}' } payload = { "prompt": prompt, "max_tokens": 150, "temperature": 0.7 } # Call the Azure OpenAI API to get the re-ranked and scored destinations response = requests.post(endpoint, headers=headers, json=payload) response_data = response.json() # Extract and return the recommendations recommendations = response_data['choices'][0]['text'].strip().split('\n') return recommendations def generate_prompt(self, preferences): prompt = "Here are the travel destinations ranked and scored based on the following user preferences:\n" for key, value in preferences.items(): prompt += f"{key}: {value}\n" prompt += "\nDestinations:\n" for destination in self.destinations: prompt += f"- {destination['name']}: {destination['description']}\n" return prompt # Example usage destinations = [ {"name": "Paris", "description": "City of lights, known for its art, fashion, and culture."}, {"name": "Tokyo", "description": "Vibrant city, famous for its modernity and traditional temples."}, {"name": "New York", "description": "The city that never sleeps, with iconic landmarks and diverse culture."}, {"name": "Sydney", "description": "Beautiful harbour city, known for its opera house and stunning beaches."}, ] preferences = {"activity": "sightseeing", "culture": "diverse"} api_key = 'your_azure_openai_api_key' endpoint = 'https://your-endpoint.com/openai/deployments/your-deployment-name/completions?api-version=2022-12-01' travel_agent = TravelAgent(destinations) recommendations = travel_agent.get_recommendations(preferences, api_key, endpoint) print("Recommended Destinations:") for rec in recommendations: print(rec) ``` #### Code Explanation - Preference Booker 1. **Initialization**: The `TravelAgent` class is initialized with a list of potential travel destinations, each having attributes like name and description. 2. **Getting Recommendations (`get_recommendations` method)**: This method generates a prompt for the Azure OpenAI service based on the user's preferences and makes an HTTP POST request to the Azure OpenAI API to get re-ranked and scored destinations. 3. **Generating Prompt (`generate_prompt` method)**: This method constructs a prompt for the Azure OpenAI, including the user's preferences and the list of destinations. The prompt guides the model to re-rank and score the destinations based on the provided preferences. 4. **API Call**: The `requests` library is used to make an HTTP POST request to the Azure OpenAI API endpoint. The response contains the re-ranked and scored destinations. 5. **Example Usage**: The travel agent collects user preferences (e.g., interest in sightseeing and diverse culture) and uses the Azure OpenAI service to get re-ranked and scored recommendations for travel destinations. Make sure to replace `your_azure_openai_api_key` with your actual Azure OpenAI API key and `https://your-endpoint.com/...` with the actual endpoint URL of your Azure OpenAI deployment. By leveraging the LLM for re-ranking and scoring, the travel agent can provide more personalized and relevant travel recommendations to clients, enhancing their overall experience. ### RAG: Prompting Technique vs Tool Retrieval-Augmented Generation (RAG) can be both a prompting technique and a tool in the development of AI agents. Understanding the distinction between the two can help you leverage RAG more effectively in your projects. #### RAG as a Prompting Technique **What is it?** - As a prompting technique, RAG involves formulating specific queries or prompts to guide the retrieval of relevant information from a large corpus or database. This information is then used to generate responses or actions. **How it works:** 1. **Formulate Prompts**: Create well-structured prompts or queries based on the task at hand or the user's input. 2. **Retrieve Information**: Use the prompts to search for relevant data from a pre-existing knowledge base or dataset. 3. **Generate Response**: Combine the retrieved information with generative AI models to produce a comprehensive and coherent response. **Example in Travel Agent**: - User Input: "I want to visit museums in Paris." - Prompt: "Find top museums in Paris." - Retrieved Information: Details about Louvre Museum, Musée d'Orsay, etc. - Generated Response: "Here are some top museums in Paris: Louvre Museum, Musée d'Orsay, and Centre Pompidou." #### RAG as a Tool **What is it?** - As a tool, RAG is an integrated system that automates the retrieval and generation process, making it easier for developers to implement complex AI functionalities without manually crafting prompts for each query. **How it works:** 1. **Integration**: Embed RAG within the AI agent's architecture, allowing it to automatically handle the retrieval and generation tasks. 2. **Automation**: The tool manages the entire process, from receiving user input to generating the final response, without requiring explicit prompts for each step. 3. **Efficiency**: Enhances the agent's performance by streamlining the retrieval and generation process, enabling quicker and more accurate responses. **Example in Travel Agent**: - User Input: "I want to visit museums in Paris." - RAG Tool: Automatically retrieves information about museums and generates a response. - Generated Response: "Here are some top museums in Paris: Louvre Museum, Musée d'Orsay, and Centre Pompidou." ### Comparison | Aspect | Prompting Technique | Tool | |------------------------|-------------------------------------------------------------|-------------------------------------------------------| | **Manual vs Automatic**| Manual formulation of prompts for each query. | Automated process for retrieval and generation. | | **Control** | Offers more control over the retrieval process. | Streamlines and automates the retrieval and generation.| | **Flexibility** | Allows for customized prompts based on specific needs. | More efficient for large-scale implementations. | | **Complexity** | Requires crafting and tweaking of prompts. | Easier to integrate within an AI agent's architecture. | ### Practical Examples **Prompting Technique Example:** ```python def search_museums_in_paris(): prompt = "Find top museums in Paris" search_results = search_web(prompt) return search_results museums = search_museums_in_paris() print("Top Museums in Paris:", museums) ``` **Tool Example:** ```python class Travel_Agent: def __init__(self): self.rag_tool = RAGTool() def get_museums_in_paris(self): user_input = "I want to visit museums in Paris." response = self.rag_tool.retrieve_and_generate(user_input) return response travel_agent = Travel_Agent() museums = travel_agent.get_museums_in_paris() print("Top Museums in Paris:", museums) ``` ### Evaluating Relevancy Evaluating relevancy is a crucial aspect of AI agent performance. It ensures that the information retrieved and generated by the agent is appropriate, accurate, and useful to the user. Let's explore how to evaluate relevancy in AI agents, including practical examples and techniques. #### Key Concepts in Evaluating Relevancy 1. **Context Awareness**: - The agent must understand the context of the user's query to retrieve and generate relevant information. - Example: If a user asks for "best restaurants in Paris," the agent should consider the user's preferences, such as cuisine type and budget. 2. **Accuracy**: - The information provided by the agent should be factually correct and up-to-date. - Example: Recommending currently open restaurants with good reviews rather than outdated or closed options. 3. **User Intent**: - The agent should infer the user's intent behind the query to provide the most relevant information. - Example: If a user asks for "budget-friendly hotels," the agent should prioritize affordable options. 4. **Feedback Loop**: - Continuously collecting and analyzing user feedback helps the agent refine its relevancy evaluation process. - Example: Incorporating user ratings and feedback on previous recommendations to improve future responses. #### Practical Techniques for Evaluating Relevancy 1. **Relevance Scoring**: - Assign a relevance score to each retrieved item based on how well it matches the user's query and preferences. - Example: ```python def relevance_score(item, query): score = 0 if item['category'] in query['interests']: score += 1 if item['price'] <= query['budget']: score += 1 if item['location'] == query['destination']: score += 1 return score ``` 2. **Filtering and Ranking**: - Filter out irrelevant items and rank the remaining ones based on their relevance scores. - Example: ```python def filter_and_rank(items, query): ranked_items = sorted(items, key=lambda item: relevance_score(item, query), reverse=True) return ranked_items[:10] # Return top 10 relevant items ``` 3. **Natural Language Processing (NLP)**: - Use NLP techniques to understand the user's query and retrieve relevant information. - Example: ```python def process_query(query): # Use NLP to extract key information from the user's query processed_query = nlp(query) return processed_query ``` 4. **User Feedback Integration**: - Collect user feedback on the provided recommendations and use it to adjust future relevance evaluations. - Example: ```python def adjust_based_on_feedback(feedback, items): for item in items: if item['name'] in feedback['liked']: item['relevance'] += 1 if item['name'] in feedback['disliked']: item['relevance'] -= 1 return items ``` #### Example: Evaluating Relevancy in Travel Agent Here's a practical example of how Travel Agent can evaluate the relevancy of travel recommendations: ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() ranked_hotels = self.filter_and_rank(hotels, self.user_preferences) itinerary = create_itinerary(flights, ranked_hotels, attractions) return itinerary def filter_and_rank(self, items, query): ranked_items = sorted(items, key=lambda item: self.relevance_score(item, query), reverse=True) return ranked_items[:10] # Return top 10 relevant items def relevance_score(self, item, query): score = 0 if item['category'] in query['interests']: score += 1 if item['price'] <= query['budget']: score += 1 if item['location'] == query['destination']: score += 1 return score def adjust_based_on_feedback(self, feedback, items): for item in items: if item['name'] in feedback['liked']: item['relevance'] += 1 if item['name'] in feedback['disliked']: item['relevance'] -= 1 return items # Example usage travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} updated_items = travel_agent.adjust_based_on_feedback(feedback, itinerary['hotels']) print("Updated Itinerary with Feedback:", updated_items) ``` ### Search with Intent Searching with intent involves understanding and interpreting the underlying purpose or goal behind a user's query to retrieve and generate the most relevant and useful information. This approach goes beyond simply matching keywords and focuses on grasping the user's actual needs and context. #### Key Concepts in Searching with Intent 1. **Understanding User Intent**: - User intent can be categorized into three main types: informational, navigational, and transactional. - **Informational Intent**: The user seeks information about a topic (e.g., "What are the best museums in Paris?"). - **Navigational Intent**: The user wants to navigate to a specific website or page (e.g., "Louvre Museum official website"). - **Transactional Intent**: The user aims to perform a transaction, such as booking a flight or making a purchase (e.g., "Book a flight to Paris"). 2. **Context Awareness**: - Analyzing the context of the user's query helps in accurately identifying their intent. This includes considering previous interactions, user preferences, and the specific details of the current query. 3. **Natural Language Processing (NLP)**: - NLP techniques are employed to understand and interpret the natural language queries provided by users. This includes tasks like entity recognition, sentiment analysis, and query parsing. 4. **Personalization**: - Personalizing the search results based on the user's history, preferences, and feedback enhances the relevancy of the information retrieved. #### Practical Example: Searching with Intent in Travel Agent Let's take Travel Agent as an example to see how searching with intent can be implemented. 1. **Gathering User Preferences** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Understanding User Intent** ```python def identify_intent(query): if "book" in query or "purchase" in query: return "transactional" elif "website" in query or "official" in query: return "navigational" else: return "informational" ``` 3. **Context Awareness** ```python def analyze_context(query, user_history): # Combine current query with user history to understand context context = { "current_query": query, "user_history": user_history } return context ``` 4. **Search and Personalize Results** ```python def search_with_intent(query, preferences, user_history): intent = identify_intent(query) context = analyze_context(query, user_history) if intent == "informational": search_results = search_information(query, preferences) elif intent == "navigational": search_results = search_navigation(query) elif intent == "transactional": search_results = search_transaction(query, preferences) personalized_results = personalize_results(search_results, user_history) return personalized_results def search_information(query, preferences): # Example search logic for informational intent results = search_web(f"best {preferences['interests']} in {preferences['destination']}") return results def search_navigation(query): # Example search logic for navigational intent results = search_web(query) return results def search_transaction(query, preferences): # Example search logic for transactional intent results = search_web(f"book {query} to {preferences['destination']}") return results def personalize_results(results, user_history): # Example personalization logic personalized = [result for result in results if result not in user_history] return personalized[:10] # Return top 10 personalized results ``` 5. **Example Usage** ```python travel_agent = Travel_Agent() preferences = { "destination": "Paris", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) user_history = ["Louvre Museum website", "Book flight to Paris"] query = "best museums in Paris" results = search_with_intent(query, preferences, user_history) print("Search Results:", results) ``` --- ## 4. Generating Code as a Tool Code generating agents use AI models to write and execute code, solving complex problems and automating tasks. ### Code Generating Agents Code generating agents use generative AI models to write and execute code. These agents can solve complex problems, automate tasks, and provide valuable insights by generating and running code in various programming languages. #### Practical Applications 1. **Automated Code Generation**: Generate code snippets for specific tasks, such as data analysis, web scraping, or machine learning. 2. **SQL as a RAG**: Use SQL queries to retrieve and manipulate data from databases. 3. **Problem Solving**: Create and execute code to solve specific problems, such as optimizing algorithms or analyzing data. #### Example: Code Generating Agent for Data Analysis Imagine you're designing a code generating agent. Here's how it might work: 1. **Task**: Analyze a dataset to identify trends and patterns. 2. **Steps**: - Load the dataset into a data analysis tool. - Generate SQL queries to filter and aggregate the data. - Execute the queries and retrieve the results. - Use the results to generate visualizations and insights. 3. **Required Resources**: Access to the dataset, data analysis tools, and SQL capabilities. 4. **Experience**: Use past analysis results to improve the accuracy and relevance of future analyses. ### Example: Code Generating Agent for Travel Agent In this example, we'll design a code generating agent, Travel Agent, to assist users in planning their travel by generating and executing code. This agent can handle tasks such as fetching travel options, filtering results, and compiling an itinerary using generative AI. #### Overview of the Code Generating Agent 1. **Gathering User Preferences**: Collects user input such as destination, travel dates, budget, and interests. 2. **Generating Code to Fetch Data**: Generates code snippets to retrieve data about flights, hotels, and attractions. 3. **Executing Generated Code**: Runs the generated code to fetch real-time information. 4. **Generating Itinerary**: Compiles the fetched data into a personalized travel plan. 5. **Adjusting Based on Feedback**: Receives user feedback and regenerates code if necessary to refine the results. #### Step-by-Step Implementation 1. **Gathering User Preferences** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Generating Code to Fetch Data** ```python def generate_code_to_fetch_data(preferences): # Example: Generate code to search for flights based on user preferences code = f""" def search_flights(): import requests response = requests.get('https://api.example.com/flights', params={preferences}) return response.json() """ return code def generate_code_to_fetch_hotels(preferences): # Example: Generate code to search for hotels code = f""" def search_hotels(): import requests response = requests.get('https://api.example.com/hotels', params={preferences}) return response.json() """ return code ``` 3. **Executing Generated Code** ```python def execute_code(code): # Execute the generated code using exec exec(code) result = locals() return result travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) flight_code = generate_code_to_fetch_data(preferences) hotel_code = generate_code_to_fetch_hotels(preferences) flights = execute_code(flight_code) hotels = execute_code(hotel_code) print("Flight Options:", flights) print("Hotel Options:", hotels) ``` 4. **Generating Itinerary** ```python def generate_itinerary(flights, hotels, attractions): itinerary = { "flights": flights, "hotels": hotels, "attractions": attractions } return itinerary attractions = search_attractions(preferences) itinerary = generate_itinerary(flights, hotels, attractions) print("Suggested Itinerary:", itinerary) ``` 5. **Adjusting Based on Feedback** ```python def adjust_based_on_feedback(feedback, preferences): # Adjust preferences based on user feedback if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] return preferences feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} updated_preferences = adjust_based_on_feedback(feedback, preferences) # Regenerate and execute code with updated preferences updated_flight_code = generate_code_to_fetch_data(updated_preferences) updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences) updated_flights = execute_code(updated_flight_code) updated_hotels = execute_code(updated_hotel_code) updated_itinerary = generate_itinerary(updated_flights, updated_hotels, attractions) print("Updated Itinerary:", updated_itinerary) ``` ### Leveraging environmental awareness and reasoning Based on the schema of the table can indeed enhance the query generation process by leveraging environmental awareness and reasoning. Here's an example of how this can be done: 1. **Understanding the Schema**: The system will understand the schema of the table and use this information to ground the query generation. 2. **Adjusting Based on Feedback**: The system will adjust user preferences based on feedback and reason about which fields in the schema need to be updated. 3. **Generating and Executing Queries**: The system will generate and execute queries to fetch updated flight and hotel data based on the new preferences. Here is an updated Python code example that incorporates these concepts: ```python def adjust_based_on_feedback(feedback, preferences, schema): # Adjust preferences based on user feedback if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] # Reasoning based on schema to adjust other related preferences for field in schema: if field in preferences: preferences[field] = adjust_based_on_environment(feedback, field, schema) return preferences def adjust_based_on_environment(feedback, field, schema): # Custom logic to adjust preferences based on schema and feedback if field in feedback["liked"]: return schema[field]["positive_adjustment"] elif field in feedback["disliked"]: return schema[field]["negative_adjustment"] return schema[field]["default"] def generate_code_to_fetch_data(preferences): # Generate code to fetch flight data based on updated preferences return f"fetch_flights(preferences={preferences})" def generate_code_to_fetch_hotels(preferences): # Generate code to fetch hotel data based on updated preferences return f"fetch_hotels(preferences={preferences})" def execute_code(code): # Simulate execution of code and return mock data return {"data": f"Executed: {code}"} def generate_itinerary(flights, hotels, attractions): # Generate itinerary based on flights, hotels, and attractions return {"flights": flights, "hotels": hotels, "attractions": attractions} # Example schema schema = { "favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"}, "avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"} } # Example usage preferences = {"favorites": "sightseeing", "avoid": "crowded places"} feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} updated_preferences = adjust_based_on_feedback(feedback, preferences, schema) # Regenerate and execute code with updated preferences updated_flight_code = generate_code_to_fetch_data(updated_preferences) updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences) updated_flights = execute_code(updated_flight_code) updated_hotels = execute_code(updated_hotel_code) updated_itinerary = generate_itinerary(updated_flights, updated_hotels, feedback["liked"]) print("Updated Itinerary:", updated_itinerary) ``` #### Explanation - Booking Based on Feedback 1. **Schema Awareness**: The `schema` dictionary defines how preferences should be adjusted based on feedback. It includes fields like `favorites` and `avoid`, with corresponding adjustments. 2. **Adjusting Preferences (`adjust_based_on_feedback` method)**: This method adjusts preferences based on user feedback and the schema. 3. **Environment-Based Adjustments (`adjust_based_on_environment` method)**: This method customizes the adjustments based on the schema and feedback. 4. **Generating and Executing Queries**: The system generates code to fetch updated flight and hotel data based on the adjusted preferences and simulates the execution of these queries. 5. **Generating Itinerary**: The system creates an updated itinerary based on the new flight, hotel, and attraction data. By making the system environment-aware and reasoning based on the schema, it can generate more accurate and relevant queries, leading to better travel recommendations and a more personalized user experience. ### Using SQL as a Retrieval-Augmented Generation (RAG) Technique SQL (Structured Query Language) is a powerful tool for interacting with databases. When used as part of a Retrieval-Augmented Generation (RAG) approach, SQL can retrieve relevant data from databases to inform and generate responses or actions in AI agents. Let's explore how SQL can be used as a RAG technique in the context of Travel Agent. #### Key Concepts 1. **Database Interaction**: - SQL is used to query databases, retrieve relevant information, and manipulate data. - Example: Fetching flight details, hotel information, and attractions from a travel database. 2. **Integration with RAG**: - SQL queries are generated based on user input and preferences. - The retrieved data is then used to generate personalized recommendations or actions. 3. **Dynamic Query Generation**: - The AI agent generates dynamic SQL queries based on the context and user needs. - Example: Customizing SQL queries to filter results based on budget, dates, and interests. #### Applications - **Automated Code Generation**: Generate code snippets for specific tasks. - **SQL as a RAG**: Use SQL queries to manipulate data. - **Problem Solving**: Create and execute code to solve problems. **Example**: A data analysis agent: 1. **Task**: Analyze a dataset to find trends. 2. **Steps**: - Load the dataset. - Generate SQL queries to filter data. - Execute queries and retrieve results. - Generate visualizations and insights. 3. **Resources**: Dataset access, SQL capabilities. 4. **Experience**: Use past results to improve future analyses. #### Practical Example: Using SQL in Travel Agent 1. **Gathering User Preferences** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Generating SQL Queries** ```python def generate_sql_query(table, preferences): query = f"SELECT * FROM {table} WHERE " conditions = [] for key, value in preferences.items(): conditions.append(f"{key}='{value}'") query += " AND ".join(conditions) return query ``` 3. **Executing SQL Queries** ```python import sqlite3 def execute_sql_query(query, database="travel.db"): connection = sqlite3.connect(database) cursor = connection.cursor() cursor.execute(query) results = cursor.fetchall() connection.close() return results ``` 4. **Generating Recommendations** ```python def generate_recommendations(preferences): flight_query = generate_sql_query("flights", preferences) hotel_query = generate_sql_query("hotels", preferences) attraction_query = generate_sql_query("attractions", preferences) flights = execute_sql_query(flight_query) hotels = execute_sql_query(hotel_query) attractions = execute_sql_query(attraction_query) itinerary = { "flights": flights, "hotels": hotels, "attractions": attractions } return itinerary travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = generate_recommendations(preferences) print("Suggested Itinerary:", itinerary) ``` #### Example SQL Queries 1. **Flight Query** ```sql SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate'; ``` 2. **Hotel Query** ```sql SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate'; ``` 3. **Attraction Query** ```sql SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine'; ``` By leveraging SQL as part of the Retrieval-Augmented Generation (RAG) technique, AI agents like Travel Agent can dynamically retrieve and utilize relevant data to provide accurate and personalized recommendations. ### Example of Metacongition So to demonstrate an implementation of metacongition, let's create a simple agent that *reflects on its decision-making process* while solving a problem. For this example, we'll build a system where an agent tries to optimize the choice of a hotel, but then evaluates its own reasoning and adjusts its strategy when it makes errors or suboptimal choices. We'll simulate this using a basic example where the agent selects hotels based on a combination of price and quality, but it will "reflect" on its decisions and adjust accordingly. #### How this illustrates metacognition: 1. **Initial Decision**: The agent will pick the cheapest hotel, without understanding the quality impact. 2. **Reflection and Evaluation**: After the initial choice, the agent will check whether the hotel is a "bad" choice using user feedback. If it finds that the hotel’s quality was too low, it reflects on its reasoning. 3. **Adjusting Strategy**: The agent adjusts its strategy based on its reflection switches from "cheapest" to "highest_quality", thus improving its decision-making process in future iterations. Here's an example: ```python class HotelRecommendationAgent: def __init__(self): self.previous_choices = [] # Stores the hotels chosen previously self.corrected_choices = [] # Stores the corrected choices self.recommendation_strategies = ['cheapest', 'highest_quality'] # Available strategies def recommend_hotel(self, hotels, strategy): """ Recommend a hotel based on the chosen strategy. The strategy can either be 'cheapest' or 'highest_quality'. """ if strategy == 'cheapest': recommended = min(hotels, key=lambda x: x['price']) elif strategy == 'highest_quality': recommended = max(hotels, key=lambda x: x['quality']) else: recommended = None self.previous_choices.append((strategy, recommended)) return recommended def reflect_on_choice(self): """ Reflect on the last choice made and decide if the agent should adjust its strategy. The agent considers if the previous choice led to a poor outcome. """ if not self.previous_choices: return "No choices made yet." last_choice_strategy, last_choice = self.previous_choices[-1] # Let's assume we have some user feedback that tells us whether the last choice was good or not user_feedback = self.get_user_feedback(last_choice) if user_feedback == "bad": # Adjust strategy if the previous choice was unsatisfactory new_strategy = 'highest_quality' if last_choice_strategy == 'cheapest' else 'cheapest' self.corrected_choices.append((new_strategy, last_choice)) return f"Reflecting on choice. Adjusting strategy to {new_strategy}." else: return "The choice was good. No need to adjust." def get_user_feedback(self, hotel): """ Simulate user feedback based on hotel attributes. For simplicity, assume if the hotel is too cheap, the feedback is "bad". If the hotel has quality less than 7, feedback is "bad". """ if hotel['price'] < 100 or hotel['quality'] < 7: return "bad" return "good" # Simulate a list of hotels (price and quality) hotels = [ {'name': 'Budget Inn', 'price': 80, 'quality': 6}, {'name': 'Comfort Suites', 'price': 120, 'quality': 8}, {'name': 'Luxury Stay', 'price': 200, 'quality': 9} ] # Create an agent agent = HotelRecommendationAgent() # Step 1: The agent recommends a hotel using the "cheapest" strategy recommended_hotel = agent.recommend_hotel(hotels, 'cheapest') print(f"Recommended hotel (cheapest): {recommended_hotel['name']}") # Step 2: The agent reflects on the choice and adjusts strategy if necessary reflection_result = agent.reflect_on_choice() print(reflection_result) # Step 3: The agent recommends again, this time using the adjusted strategy adjusted_recommendation = agent.recommend_hotel(hotels, 'highest_quality') print(f"Adjusted hotel recommendation (highest_quality): {adjusted_recommendation['name']}") ``` #### Agents Metacognition Abilities The key here is the agent's ability to: - Evaluate its previous choices and decision-making process. - Adjust its strategy based on that reflection i.e., metacognition in action. This is a simple form of metacognition where the system is capable of adjusting its reasoning process based on internal feedback. ### Conclusion Metacognition is a powerful tool that can significantly enhance the capabilities of AI agents. By incorporating metacognitive processes, you can design agents that are more intelligent, adaptable, and efficient. Use the additional resources to further explore the fascinating world of metacognition in AI agents.
{ "source": "microsoft/ai-agents-for-beginners", "title": "09-metacognition/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/09-metacognition/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 64142 }
# AI Agents in Production ## Introduction This lesson will cover: - How to plan the deployment of your AI Agent to production effectively. - Common mistakes and issues that you may face when deploying your AI Agent to production. - How to manage costs while still maintaining the performance of your AI Agent. ## Learning Goals After completing this lesson, you will know how to/understand: - Techniques for improving the performance, costs, and effectiveness of a production AI Agent system. - What and how to evaluate your AI Agents. - How to control costs when deploying AI Agents to production. It is important to deploy AI Agents that are trustworthy. Check out the "Building Trustworthy AI Agents" lesson as well. ## Evaluating AI Agents Before, during, and after deploying AI Agents, having a proper system to evaluate your AI Agents is critical. This will ensure that your system is aligned with you and your users' goals. To evaluate an AI Agent, it is important to have the ability to evaluate not only the agent's output but also the entire system that your AI Agent is operating in. This includes but is not limited to: - The initial model request. - The agent's ability to identify the intent of the user. - The agent's ability to identify the right tool to perform the task. - The tool's response to the agent's request. - The agent's ability to interpret the tool's response. - The user's feedback to the agent's response. This allows you to identify areas for improvement in a more modular way. You can then monitor the effect of changes to models, prompts, tools, and other components with better efficiency. ## Common Issues and Potential Solutions with AI Agents | **Issue** | **Potential Solution** | | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | AI Agent not performing tasks consistently | - Refine the prompt given to the AI Agent; be clear on objectives.<br>- Identify where dividing the tasks into subtasks and handling them by multiple agents can help. | | AI Agent running into continuous loops | - Ensure you have clear termination terms and conditions so the Agent knows when to stop the process.<br>- For complex tasks that require reasoning and planning, use a larger model that is specialized for reasoning tasks. | | AI Agent tool calls are not performing well | - Test and validate the tool's output outside of the agent system.<br>- Refine the defined parameters, prompts, and naming of tools. | | Multi-Agent system not performing consistently | - Refine prompts given to each agent to ensure they are specific and distinct from one another.<br>- Build a hierarchical system using a "routing" or controller agent to determine which agent is the correct one. | ## Managing Costs Here are some strategies to manage the costs of deploying AI Agents to production: - **Caching Responses** - Identifying common requests and tasks and providing the responses before they go through your agentic system is a good way to reduce the volume of similar requests. You can even implement a flow to identify how similar a request is to your cached requests using more basic AI models. - **Using Smaller Models** - Small Language Models (SLMs) can perform well on certain agentic use-cases and will reduce costs significantly. As mentioned earlier, building an evaluation system to determine and compare performance vs larger models is the best way to understand how well an SLM will perform on your use case. - **Using a Router Model** - A similar strategy is to use a diversity of models and sizes. You can use an LLM/SLM or serverless function to route requests based on complexity to the best fit models. This will also help reduce costs while also ensuring performance on the right tasks. ## Congratulations This is currently the last lesson of "AI Agents for Beginners". We plan to continue to add lessons based on feedback and changes in this ever growing industry so stop by again in the near future. If you want to continue your learning and building with AI Agents, join the <a href="https://discord.gg/kzRShWzttr" target="_blank">Azure AI Community Discord</a>. We host workshops, community roundtables and "ask me anything" sessions there. We also have a Learn collection of additional materials that can help you start building AI Agents in production.
{ "source": "microsoft/ai-agents-for-beginners", "title": "10-ai-agents-production/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/10-ai-agents-production/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 4937 }
**Agents specific for the customer support process**: - **Customer agent**: This agent represents the customer and is responsible for initiating the support process. - **Support agent**: This agent represents the support process and is responsible for providing assistance to the customer. - **Escalation agent**: This agent represents the escalation process and is responsible for escalating issues to a higher level of support. - **Resolution agent**: This agent represents the resolution process and is responsible for resolving any issues that arise during the support process. - **Feedback agent**: This agent represents the feedback process and is responsible for collecting feedback from the customer. - **Notification agent**: This agent represents the notification process and is responsible for sending notifications to the customer at various stages of the support process. - **Analytics agent**: This agent represents the analytics process and is responsible for analyzing data related to the support process. - **Audit agent**: This agent represents the audit process and is responsible for auditing the support process to ensure that it is being carried out correctly. - **Reporting agent**: This agent represents the reporting process and is responsible for generating reports on the support process. - **Knowledge agent**: This agent represents the knowledge process and is responsible for maintaining a knowledge base of information related to the support process. - **Security agent**: This agent represents the security process and is responsible for ensuring the security of the support process. - **Quality agent**: This agent represents the quality process and is responsible for ensuring the quality of the support process. - **Compliance agent**: This agent represents the compliance process and is responsible for ensuring that the support process complies with regulations and policies. - **Training agent**: This agent represents the training process and is responsible for training support agents on how to assist customers. That's a few agents, was that more or less than you expected?
{ "source": "microsoft/ai-agents-for-beginners", "title": "08-multi-agent/solution/solution.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/08-multi-agent/solution/solution.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 2116 }
# Microsoft Open Source Verhaltenskodex Dieses Projekt hat den [Microsoft Open Source Verhaltenskodex](https://opensource.microsoft.com/codeofconduct/) übernommen. Ressourcen: - [Microsoft Open Source Verhaltenskodex](https://opensource.microsoft.com/codeofconduct/) - [Microsoft Verhaltenskodex FAQ](https://opensource.microsoft.com/codeofconduct/faq/) - Kontaktieren Sie [[email protected]](mailto:[email protected]) bei Fragen oder Anliegen. ``` **Haftungsausschluss**: Dieses Dokument wurde mithilfe maschineller KI-Übersetzungsdienste übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die aus der Nutzung dieser Übersetzung entstehen.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/CODE_OF_CONDUCT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/CODE_OF_CONDUCT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1027 }
# KI-Agenten für Anfänger - Ein Kurs ![Generative KI für Anfänger](../../translated_images/repo-thumbnail.fdd5f487bb7274d4a08459d76907ec4914de268c99637e9af082b1d3eb0730e2.de.png?WT.mc_id=academic-105485-koreyst) ## 10 Lektionen, die alles lehren, was Sie wissen müssen, um KI-Agenten zu entwickeln [![GitHub license](https://img.shields.io/github/license/microsoft/ai-agents-for-beginners.svg)](https://github.com/microsoft/ai-agents-for-beginners/blob/master/LICENSE?WT.mc_id=academic-105485-koreyst) [![GitHub contributors](https://img.shields.io/github/contributors/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/graphs/contributors/?WT.mc_id=academic-105485-koreyst) [![GitHub issues](https://img.shields.io/github/issues/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/issues/?WT.mc_id=academic-105485-koreyst) [![GitHub pull-requests](https://img.shields.io/github/issues-pr/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/pulls/?WT.mc_id=academic-105485-koreyst) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com?WT.mc_id=academic-105485-koreyst) [![GitHub watchers](https://img.shields.io/github/watchers/microsoft/ai-agents-for-beginners.svg?style=social&label=Watch)](https://GitHub.com/microsoft/ai-agents-for-beginners/watchers/?WT.mc_id=academic-105485-koreyst) [![GitHub forks](https://img.shields.io/github/forks/microsoft/ai-agents-for-beginners.svg?style=social&label=Fork)](https://GitHub.com/microsoft/ai-agents-for-beginners/network/?WT.mc_id=academic-105485-koreyst) [![GitHub stars](https://img.shields.io/github/stars/microsoft/ai-agents-for-beginners.svg?style=social&label=Star)](https://GitHub.com/microsoft/ai-agents-for-beginners/stargazers/?WT.mc_id=academic-105485-koreyst) [![Azure AI Discord](https://dcbadge.limes.pink/api/server/kzRShWzttr)](https://discord.gg/kzRShWzttr) ## 🌱 Erste Schritte Dieser Kurs umfasst 10 Lektionen, die die Grundlagen zur Entwicklung von KI-Agenten abdecken. Jede Lektion behandelt ein eigenes Thema, sodass Sie an jedem beliebigen Punkt beginnen können! Falls Sie zum ersten Mal mit generativen KI-Modellen arbeiten, werfen Sie einen Blick auf unseren [Generative KI für Anfänger](https://aka.ms/genai-beginners)-Kurs mit 21 Lektionen zum Arbeiten mit GenAI. ### So führen Sie den Code dieses Kurses aus Dieser Kurs enthält Codebeispiele in jeder Lektion, die einen `code_samples`-Ordner enthalten. Dieser Code verwendet folgende Dienste für Modelle: - [Github Models](https://aka.ms/ai-agents-beginners/github-models) - Kostenlos / Begrenzter Zugang - [Azure AI Foundry](https://aka.ms/ai-agents-beginners/ai-foundry) - Azure-Konto erforderlich Dieser Kurs verwendet außerdem folgende Frameworks und Dienste für KI-Agenten: - [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service) - [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) - [AutoGen](https://aka.ms/ai-agents/autogen) Weitere Informationen zum Ausführen des Codes finden Sie unter [Kurs-Setup](./00-course-setup/README.md). Vergessen Sie nicht, dieses Repository zu [favorisieren (🌟)](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars?WT.mc_id=academic-105485-koreyst) und [zu forken](https://github.com/microsoft/ai-agents-for-beginners/fork), um den Code auszuführen. ## 🙏 Möchten Sie mithelfen? Haben Sie Vorschläge oder Fehler in Rechtschreibung oder Code gefunden? [Erstellen Sie ein Issue](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst) oder [reichen Sie eine Pull-Request ein](https://github.com/microsoft/ai-agents-for-beginners/pulls?WT.mc_id=academic-105485-koreyst). Falls Sie nicht weiterkommen oder Fragen zum Erstellen von KI-Agenten haben, treten Sie unserer [Azure AI Community Discord](https://discord.gg/kzRShWzttr) bei. ## 📂 Jede Lektion beinhaltet - Eine schriftliche Lektion im README (Videos verfügbar ab März 2025) - Python-Codebeispiele, die Azure AI Foundry und Github Models (kostenlos) unterstützen - Links zu zusätzlichen Ressourcen, um Ihr Lernen fortzusetzen ## 🗃️ Lektionen | **Lektion** | **Link** | **Zusätzliche Ressourcen** | |----------------------------------------|--------------------------------------------|----------------------------| | Einführung in KI-Agenten und Anwendungsfälle | [Einführung in KI-Agenten und Anwendungsfälle](./01-intro-to-ai-agents/README.md) | Mehr erfahren | | Erforschung von agentischen Frameworks | [Erforschung von agentischen Frameworks](./02-explore-agentic-frameworks/README.md) | Mehr erfahren | | Verständnis von agentischen Designmustern | [Verständnis von agentischen Designmustern](./03-agentic-design-patterns/README.md) | Mehr erfahren | | Designmuster für Werkzeugnutzung | [Designmuster für Werkzeugnutzung](./04-tool-use/README.md) | Mehr erfahren | | Agentic RAG | [Agentic RAG](./05-agentic-rag/README.md) | Mehr erfahren | | Vertrauenswürdige KI-Agenten entwickeln | [Vertrauenswürdige KI-Agenten entwickeln](./06-building-trustworthy-agents/README.md) | Mehr erfahren | | Planungs-Designmuster | [Planungs-Designmuster](./07-planning-design/README.md) | Mehr erfahren | | Multi-Agent-Designmuster | [Multi-Agent-Designmuster](./08-multi-agent/README.md) | Mehr erfahren | | Metakognition Design Pattern | [Metakognition Design Pattern](./09-metacognition/README.md) | Mehr erfahren | | KI-Agenten in der Produktion | [KI-Agenten in der Produktion](./10-ai-agents-production/README.md) | Mehr erfahren | ## 🎒 Andere Kurse Unser Team erstellt auch andere Kurse! Schauen Sie sich an: - [Generative AI für Einsteiger](https://aka.ms/genai-beginners) - [ML für Einsteiger](https://aka.ms/ml-beginners?WT.mc_id=academic-105485-koreyst) - [Datenwissenschaft für Einsteiger](https://aka.ms/datascience-beginners?WT.mc_id=academic-105485-koreyst) - [KI für Einsteiger](https://aka.ms/ai-beginners?WT.mc_id=academic-105485-koreyst) ## Beitrag leisten Dieses Projekt begrüßt Beiträge und Vorschläge. Die meisten Beiträge erfordern, dass Sie einer Contributor License Agreement (CLA) zustimmen, die erklärt, dass Sie das Recht haben, und tatsächlich gewähren, uns die Rechte zur Nutzung Ihres Beitrags. Für Details besuchen Sie <https://cla.opensource.microsoft.com>. Wenn Sie einen Pull Request einreichen, wird ein CLA-Bot automatisch bestimmen, ob Sie eine CLA bereitstellen müssen, und den PR entsprechend markieren (z. B. Statusprüfung, Kommentar). Folgen Sie einfach den Anweisungen, die der Bot bereitstellt. Sie müssen dies nur einmal für alle Repositories tun, die unsere CLA verwenden. Dieses Projekt hat den [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) übernommen. Weitere Informationen finden Sie in den [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) oder kontaktieren Sie [[email protected]](mailto:[email protected]) bei zusätzlichen Fragen oder Kommentaren. ## Marken Dieses Projekt kann Marken oder Logos für Projekte, Produkte oder Dienstleistungen enthalten. Die autorisierte Nutzung von Microsoft-Marken oder -Logos unterliegt den [Microsoft Trademark & Brand Guidelines](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general) und muss diesen folgen. Die Nutzung von Microsoft-Marken oder -Logos in modifizierten Versionen dieses Projekts darf keine Verwirrung stiften oder eine Microsoft-Sponsoring implizieren. Jegliche Nutzung von Marken oder Logos Dritter unterliegt den Richtlinien der jeweiligen Drittanbieter. **Haftungsausschluss**: Dieses Dokument wurde mithilfe von KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die sich aus der Nutzung dieser Übersetzung ergeben.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 8656 }
# Sicherheit Microsoft nimmt die Sicherheit unserer Softwareprodukte und -dienstleistungen ernst, einschließlich aller Quellcode-Repositories, die über unsere GitHub-Organisationen verwaltet werden. Dazu gehören [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) und [Xamarin](https://github.com/xamarin). Wenn Sie glauben, eine Sicherheitslücke in einem von Microsoft verwalteten Repository gefunden zu haben, die [Microsofts Definition einer Sicherheitslücke](https://aka.ms/security.md/definition) entspricht, melden Sie diese bitte wie unten beschrieben. ## Melden von Sicherheitsproblemen **Bitte melden Sie Sicherheitslücken nicht über öffentliche GitHub-Issues.** Stattdessen melden Sie diese bitte dem Microsoft Security Response Center (MSRC) unter [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report). Wenn Sie es bevorzugen, ohne Anmeldung einzureichen, senden Sie eine E-Mail an [[email protected]](mailto:[email protected]). Wenn möglich, verschlüsseln Sie Ihre Nachricht mit unserem PGP-Schlüssel; laden Sie diesen bitte von der [Microsoft Security Response Center PGP Key Seite](https://aka.ms/security.md/msrc/pgp) herunter. Sie sollten innerhalb von 24 Stunden eine Antwort erhalten. Falls dies aus irgendeinem Grund nicht geschieht, setzen Sie sich bitte per E-Mail erneut mit uns in Verbindung, um sicherzustellen, dass wir Ihre ursprüngliche Nachricht erhalten haben. Weitere Informationen finden Sie unter [microsoft.com/msrc](https://www.microsoft.com/msrc). Bitte fügen Sie, soweit möglich, die unten aufgeführten Informationen bei, um uns zu helfen, die Art und den Umfang des möglichen Problems besser zu verstehen: * Art des Problems (z. B. Buffer Overflow, SQL-Injection, Cross-Site-Scripting, etc.) * Vollständige Pfade der Quellcodedatei(en), die mit der Manifestation des Problems in Zusammenhang stehen * Der Standort des betroffenen Quellcodes (Tag/Branch/Commit oder direkte URL) * Besondere Konfigurationen, die erforderlich sind, um das Problem zu reproduzieren * Schritt-für-Schritt-Anleitung zur Reproduktion des Problems * Proof-of-Concept- oder Exploit-Code (falls möglich) * Auswirkungen des Problems, einschließlich der Art und Weise, wie ein Angreifer das Problem ausnutzen könnte Diese Informationen helfen uns, Ihren Bericht schneller zu priorisieren. Wenn Sie im Rahmen eines Bug-Bounty-Programms berichten, können detailliertere Berichte zu einer höheren Prämienauszahlung beitragen. Bitte besuchen Sie unsere Seite zum [Microsoft Bug Bounty-Programm](https://aka.ms/security.md/msrc/bounty), um weitere Details zu unseren aktiven Programmen zu erhalten. ## Bevorzugte Sprachen Wir bevorzugen alle Kommunikationen auf Englisch. ## Richtlinie Microsoft folgt dem Prinzip der [Koordinierten Offenlegung von Sicherheitslücken](https://aka.ms/security.md/cvd). ``` **Haftungsausschluss**: Dieses Dokument wurde mit KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, beachten Sie bitte, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die aus der Nutzung dieser Übersetzung entstehen.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/SECURITY.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/SECURITY.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 3534 }
# TODO: Der Maintainer dieses Repos hat diese Datei noch nicht bearbeitet **REPO-BESITZER**: Möchten Sie Kundenservice- und Supportleistungen (CSS) für dieses Produkt/Projekt? - **Kein CSS-Support:** Füllen Sie diese Vorlage mit Informationen aus, wie man Probleme meldet und Hilfe bekommt. - **CSS-Support gewünscht:** Füllen Sie ein Intake-Formular unter [aka.ms/onboardsupport](https://aka.ms/onboardsupport) aus. CSS wird mit Ihnen zusammenarbeiten/helfen, um die nächsten Schritte zu bestimmen. - **Nicht sicher?** Füllen Sie ein Intake-Formular aus, als ob die Antwort "Ja" wäre. CSS wird Ihnen bei der Entscheidung helfen. *Entfernen Sie dann diese erste Überschrift aus dieser SUPPORT.MD-Datei, bevor Sie Ihr Repo veröffentlichen.* ## Support ## So melden Sie Probleme und erhalten Unterstützung Dieses Projekt verwendet GitHub Issues, um Bugs und Funktionsanfragen zu verfolgen. Bitte durchsuchen Sie die bestehenden Issues, bevor Sie neue erstellen, um Duplikate zu vermeiden. Für neue Probleme melden Sie Ihren Bug oder Ihre Funktionsanfrage als neues Issue. Für Hilfe und Fragen zur Nutzung dieses Projekts, bitte **REPO-MAINTAINER: FÜGEN SIE HIER ANWEISUNGEN EIN, WIE MAN DIE REPO-BESITZER ODER DIE COMMUNITY UM HILFE BITTEN KANN. DAS KÖNNTE EIN STACK OVERFLOW-TAG ODER EIN ANDERER KANAL SEIN. WO WERDEN SIE MENSCHEN HELFEN?**. ## Microsoft-Support-Richtlinie Der Support für dieses **PROJEKT oder PRODUKT** ist auf die oben aufgeführten Ressourcen beschränkt. **Haftungsausschluss**: Dieses Dokument wurde mithilfe von KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, beachten Sie bitte, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die aus der Nutzung dieser Übersetzung resultieren.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/SUPPORT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/SUPPORT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 2071 }
# Código de Conducta de Código Abierto de Microsoft Este proyecto ha adoptado el [Código de Conducta de Código Abierto de Microsoft](https://opensource.microsoft.com/codeofconduct/). Recursos: - [Código de Conducta de Código Abierto de Microsoft](https://opensource.microsoft.com/codeofconduct/) - [Preguntas frecuentes sobre el Código de Conducta de Microsoft](https://opensource.microsoft.com/codeofconduct/faq/) - Contacta a [[email protected]](mailto:[email protected]) si tienes preguntas o inquietudes **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en IA. Si bien nos esforzamos por garantizar la precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse como la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/CODE_OF_CONDUCT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/CODE_OF_CONDUCT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1101 }
# Agentes de IA para Principiantes - Un Curso ![Generative AI For Beginners](../../translated_images/repo-thumbnail.fdd5f487bb7274d4a08459d76907ec4914de268c99637e9af082b1d3eb0730e2.es.png?WT.mc_id=academic-105485-koreyst) ## 10 Lecciones que enseñan todo lo que necesitas saber para empezar a construir Agentes de IA [![GitHub license](https://img.shields.io/github/license/microsoft/ai-agents-for-beginners.svg)](https://github.com/microsoft/ai-agents-for-beginners/blob/master/LICENSE?WT.mc_id=academic-105485-koreyst) [![GitHub contributors](https://img.shields.io/github/contributors/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/graphs/contributors/?WT.mc_id=academic-105485-koreyst) [![GitHub issues](https://img.shields.io/github/issues/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/issues/?WT.mc_id=academic-105485-koreyst) [![GitHub pull-requests](https://img.shields.io/github/issues-pr/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/pulls/?WT.mc_id=academic-105485-koreyst) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com?WT.mc_id=academic-105485-koreyst) [![GitHub watchers](https://img.shields.io/github/watchers/microsoft/ai-agents-for-beginners.svg?style=social&label=Watch)](https://GitHub.com/microsoft/ai-agents-for-beginners/watchers/?WT.mc_id=academic-105485-koreyst) [![GitHub forks](https://img.shields.io/github/forks/microsoft/ai-agents-for-beginners.svg?style=social&label=Fork)](https://GitHub.com/microsoft/ai-agents-for-beginners/network/?WT.mc_id=academic-105485-koreyst) [![GitHub stars](https://img.shields.io/github/stars/microsoft/ai-agents-for-beginners.svg?style=social&label=Star)](https://GitHub.com/microsoft/ai-agents-for-beginners/stargazers/?WT.mc_id=academic-105485-koreyst) [![Azure AI Discord](https://dcbadge.limes.pink/api/server/kzRShWzttr)](https://discord.gg/kzRShWzttr) ## 🌐 Soporte Multilenguaje | Idioma | Código | Enlace al README Traducido | Última Actualización | |-----------------------|--------|-------------------------------------------------------|-----------------------| | Chino (Simplificado) | zh | [Traducción al Chino](../zh/README.md) | 2025-02-13 | | Chino (Tradicional) | tw | [Traducción al Chino](../tw/README.md) | 2025-02-13 | | Francés | fr | [Traducción al Francés](../fr/README.md) | 2025-02-13 | | Japonés | ja | [Traducción al Japonés](../ja/README.md) | 2025-02-13 | | Coreano | ko | [Traducción al Coreano](../ko/README.md) | 2025-02-13 | | Español | es | [Traducción al Español](./README.md) | 2025-02-13 | > **Nota:** > Estas traducciones se generaron automáticamente utilizando el proyecto de código abierto [co-op-translator](https://github.com/Azure/co-op-translator) y pueden contener errores o inexactitudes. Para información crítica, consulta el texto original o busca una traducción profesional. Si deseas contribuir o actualizar una traducción, visita el repositorio, donde puedes hacer contribuciones fácilmente utilizando comandos simples. ## 🌱 Comenzando Este curso incluye 10 lecciones que cubren los fundamentos para construir Agentes de IA. Cada lección aborda un tema específico, ¡así que comienza por donde prefieras! Si es la primera vez que trabajas con modelos de IA Generativa, echa un vistazo a nuestro curso [Generative AI For Beginners](https://aka.ms/genai-beginners), que tiene 21 lecciones sobre cómo trabajar con GenAI. ### Para ejecutar el código de este curso Este curso incluye ejemplos de código en cada lección dentro de una carpeta `code_samples`. Este código utiliza los siguientes servicios para Modelos: - [Github Models](https://aka.ms/ai-agents-beginners/github-models) - Gratis / Limitado - [Azure AI Foundry](https://aka.ms/ai-agents-beginners/ai-foundry) - Requiere una cuenta de Azure Este curso también utiliza los siguientes marcos y servicios de Agentes de IA: - [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service) - [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) - [AutoGen](https://aka.ms/ai-agents/autogen) Para más información sobre cómo ejecutar el código de este curso, consulta la sección [Configuración del Curso](./00-course-setup/README.md). No olvides [dar una estrella (🌟) a este repositorio](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars?WT.mc_id=academic-105485-koreyst) y [hacer un fork](https://github.com/microsoft/ai-agents-for-beginners/fork) para ejecutar el código. ## 🙏 ¿Quieres ayudar? ¿Tienes sugerencias o encontraste errores ortográficos o en el código? [Abre un issue](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst) o [Crea un pull request](https://github.com/microsoft/ai-agents-for-beginners/pulls?WT.mc_id=academic-105485-koreyst) Si te quedas atascado o tienes preguntas sobre cómo construir Agentes de IA, únete a nuestra [comunidad de Azure AI en Discord](https://discord.gg/kzRShWzttr). ## 📂 Cada lección incluye - Una lección escrita ubicada en el README (Videos disponibles en marzo de 2025) - Ejemplos de código en Python compatibles con Azure AI Foundry y Github Models (Gratis) - Enlaces a recursos adicionales para continuar aprendiendo ## 🗃️ Lecciones | **Lección** | **Enlace** | **Aprendizaje Adicional** | |--------------------------------------|----------------------------------------------|---------------------------| | Introducción a Agentes de IA y Casos de Uso | [Introducción a Agentes de IA y Casos de Uso](./01-intro-to-ai-agents/README.md) | Aprende Más | | Explorando Marcos Agénticos | [Exploring Agentic Frameworks](./02-explore-agentic-frameworks/README.md) | Aprende Más | | Entendiendo Patrones de Diseño Agéntico | [Understanding Agentic Design Patterns](./03-agentic-design-patterns/README.md) | Aprende Más | | Patrón de Diseño para Uso de Herramientas | [Tool Use Design Pattern](./04-tool-use/README.md) | Aprende Más | | RAG Agéntico | [Agentic RAG](./05-agentic-rag/README.md) | Aprende Más | | Construyendo Agentes de IA Confiables | [Building Trustworthy AI Agents](./06-building-trustworthy-agents/README.md) | Aprende Más | | Patrón de Diseño para Planificación | [Planning Design Pattern](./07-planning-design/README.md) | Aprende Más | | Patrón de Diseño Multi-Agente | [Muilt-Agent Design Pattern](./08-multi-agent/README.md) | Aprende Más | | Patrón de Diseño de Metacognición | [Metacognition Design Pattern](./09-metacognition/README.md) | Aprende Más | | Agentes de IA en Producción | [AI Agents in Production](./10-ai-agents-production/README.md) | Aprende Más | ## 🎒 Otros Cursos ¡Nuestro equipo produce otros cursos! Échales un vistazo: - [Generative AI for Beginners](https://aka.ms/genai-beginners) - [ML for Beginners](https://aka.ms/ml-beginners?WT.mc_id=academic-105485-koreyst) - [Data Science for Beginners](https://aka.ms/datascience-beginners?WT.mc_id=academic-105485-koreyst) - [AI for Beginners](https://aka.ms/ai-beginners?WT.mc_id=academic-105485-koreyst) ## Contribuciones Este proyecto da la bienvenida a contribuciones y sugerencias. La mayoría de las contribuciones requieren que aceptes un Acuerdo de Licencia de Contribuidor (CLA) que declara que tienes el derecho de, y efectivamente otorgas, los derechos para que usemos tu contribución. Para más detalles, visita <https://cla.opensource.microsoft.com>. Cuando envíes un pull request, un bot de CLA determinará automáticamente si necesitas proporcionar un CLA y marcará el PR adecuadamente (por ejemplo, con una verificación de estado o un comentario). Simplemente sigue las instrucciones proporcionadas por el bot. Solo necesitarás hacer esto una vez en todos los repositorios que usen nuestro CLA. Este proyecto ha adoptado el [Código de Conducta de Código Abierto de Microsoft](https://opensource.microsoft.com/codeofconduct/). Para más información, consulta las [Preguntas Frecuentes sobre el Código de Conducta](https://opensource.microsoft.com/codeofconduct/faq/) o contacta a [[email protected]](mailto:[email protected]) con cualquier pregunta o comentario adicional. ## Marcas Registradas Este proyecto puede contener marcas registradas o logotipos de proyectos, productos o servicios. El uso autorizado de las marcas registradas o logotipos de Microsoft está sujeto a, y debe seguir, las [Directrices de Marca y Uso de Microsoft](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general). El uso de marcas registradas o logotipos de Microsoft en versiones modificadas de este proyecto no debe causar confusión ni implicar patrocinio por parte de Microsoft. Cualquier uso de marcas registradas o logotipos de terceros está sujeto a las políticas de esos terceros. **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por lograr precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse como la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 10072 }
# Seguridad Microsoft se toma muy en serio la seguridad de nuestros productos y servicios de software, lo que incluye todos los repositorios de código fuente gestionados a través de nuestras organizaciones en GitHub, que incluyen [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) y [Xamarin](https://github.com/xamarin). Si crees que has encontrado una vulnerabilidad de seguridad en algún repositorio propiedad de Microsoft que cumpla con la [definición de vulnerabilidad de seguridad de Microsoft](https://aka.ms/security.md/definition), infórmanos como se describe a continuación. ## Informar problemas de seguridad **Por favor, no informes vulnerabilidades de seguridad a través de issues públicos en GitHub.** En su lugar, repórtalas al Microsoft Security Response Center (MSRC) en [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report). Si prefieres enviar tu informe sin iniciar sesión, envía un correo electrónico a [[email protected]](mailto:[email protected]). Si es posible, cifra tu mensaje con nuestra clave PGP; puedes descargarla desde la [página de claves PGP del Microsoft Security Response Center](https://aka.ms/security.md/msrc/pgp). Deberías recibir una respuesta en un plazo de 24 horas. Si por alguna razón no la recibes, haz un seguimiento por correo electrónico para asegurarte de que recibimos tu mensaje original. Puedes encontrar información adicional en [microsoft.com/msrc](https://www.microsoft.com/msrc). Incluye la información solicitada que se detalla a continuación (tanto como puedas proporcionar) para ayudarnos a entender mejor la naturaleza y el alcance del posible problema: * Tipo de problema (por ejemplo, desbordamiento de búfer, inyección SQL, scripting entre sitios, etc.) * Rutas completas de los archivos fuente relacionados con la manifestación del problema * Ubicación del código fuente afectado (tag/branch/commit o URL directa) * Cualquier configuración especial requerida para reproducir el problema * Instrucciones paso a paso para reproducir el problema * Código de prueba de concepto o de explotación (si es posible) * Impacto del problema, incluyendo cómo un atacante podría explotarlo Esta información nos ayudará a priorizar tu informe más rápidamente. Si estás informando como parte de un programa de recompensas por errores, los informes más completos pueden contribuir a una mayor recompensa. Visita nuestra página del [Programa de Recompensas por Errores de Microsoft](https://aka.ms/security.md/msrc/bounty) para más detalles sobre nuestros programas activos. ## Idiomas preferidos Preferimos que todas las comunicaciones se realicen en inglés. ## Política Microsoft sigue el principio de [Divulgación Coordinada de Vulnerabilidades](https://aka.ms/security.md/cvd). **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por garantizar la precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/SECURITY.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/SECURITY.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 3512 }
# TODO: El responsable de este repositorio aún no ha editado este archivo **PROPIETARIO DEL REPOSITORIO**: ¿Deseas soporte de Customer Service & Support (CSS) para este producto/proyecto? - **Sin soporte CSS:** Completa esta plantilla con información sobre cómo reportar problemas y obtener ayuda. - **Con soporte CSS:** Llena un formulario de ingreso en [aka.ms/onboardsupport](https://aka.ms/onboardsupport). CSS trabajará contigo para determinar los próximos pasos. - **¿No estás seguro?** Llena el formulario como si la respuesta fuera "Sí". CSS te ayudará a decidir. *Luego elimina este primer encabezado de este archivo SUPPORT.MD antes de publicar tu repositorio.* ## Soporte ## Cómo reportar problemas y obtener ayuda Este proyecto utiliza GitHub Issues para rastrear errores y solicitudes de características. Por favor, busca en los problemas existentes antes de reportar nuevos problemas para evitar duplicados. Para nuevos problemas, reporta tu error o solicitud de característica como un nuevo Issue. Para obtener ayuda y hacer preguntas sobre el uso de este proyecto, por favor **RESPONSABLE DEL REPOSITORIO: INSERTA INSTRUCCIONES AQUÍ SOBRE CÓMO CONTACTAR A LOS RESPONSABLES DEL REPOSITORIO O A LA COMUNIDAD PARA OBTENER AYUDA. PODRÍA SER UNA ETIQUETA EN STACK OVERFLOW U OTRO CANAL. ¿DÓNDE AYUDARÁS A LAS PERSONAS?**. ## Política de soporte de Microsoft El soporte para este **PROYECTO o PRODUCTO** se limita a los recursos mencionados anteriormente. **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por lograr precisión, tenga en cuenta que las traducciones automáticas pueden contener errores o inexactitudes. El documento original en su idioma nativo debe considerarse la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/SUPPORT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/SUPPORT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 2080 }
# Code de Conduite Open Source de Microsoft Ce projet a adopté le [Code de Conduite Open Source de Microsoft](https://opensource.microsoft.com/codeofconduct/). Ressources : - [Code de Conduite Open Source de Microsoft](https://opensource.microsoft.com/codeofconduct/) - [FAQ sur le Code de Conduite de Microsoft](https://opensource.microsoft.com/codeofconduct/faq/) - Contactez [[email protected]](mailto:[email protected]) pour toute question ou préoccupation **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatique basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de faire appel à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/CODE_OF_CONDUCT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/CODE_OF_CONDUCT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1116 }
# Agents IA pour Débutants - Un Cours ![IA Générative pour Débutants](../../translated_images/repo-thumbnail.fdd5f487bb7274d4a08459d76907ec4914de268c99637e9af082b1d3eb0730e2.fr.png?WT.mc_id=academic-105485-koreyst) ## 10 Leçons pour apprendre tout ce qu'il faut savoir pour commencer à créer des Agents IA [![Licence GitHub](https://img.shields.io/github/license/microsoft/ai-agents-for-beginners.svg)](https://github.com/microsoft/ai-agents-for-beginners/blob/master/LICENSE?WT.mc_id=academic-105485-koreyst) [![Contributeurs GitHub](https://img.shields.io/github/contributors/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/graphs/contributors/?WT.mc_id=academic-105485-koreyst) [![Problèmes GitHub](https://img.shields.io/github/issues/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/issues/?WT.mc_id=academic-105485-koreyst) [![Pull-requests GitHub](https://img.shields.io/github/issues-pr/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/pulls/?WT.mc_id=academic-105485-koreyst) [![PRs Bienvenus](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com?WT.mc_id=academic-105485-koreyst) [![Observateurs GitHub](https://img.shields.io/github/watchers/microsoft/ai-agents-for-beginners.svg?style=social&label=Watch)](https://GitHub.com/microsoft/ai-agents-for-beginners/watchers/?WT.mc_id=academic-105485-koreyst) [![Forks GitHub](https://img.shields.io/github/forks/microsoft/ai-agents-for-beginners.svg?style=social&label=Fork)](https://GitHub.com/microsoft/ai-agents-for-beginners/network/?WT.mc_id=academic-105485-koreyst) [![Étoiles GitHub](https://img.shields.io/github/stars/microsoft/ai-agents-for-beginners.svg?style=social&label=Star)](https://GitHub.com/microsoft/ai-agents-for-beginners/stargazers/?WT.mc_id=academic-105485-koreyst) [![Azure AI Discord](https://dcbadge.limes.pink/api/server/kzRShWzttr)](https://discord.gg/kzRShWzttr) ## 🌐 Support Multilingue | Langue | Code | Lien vers le README traduit | Dernière mise à jour | |----------------------|------|------------------------------------------------------|-----------------------| | Chinois (Simplifié) | zh | [Traduction en Chinois](../zh/README.md) | 2025-02-13 | | Chinois (Traditionnel)| tw | [Traduction en Chinois](../tw/README.md) | 2025-02-13 | | Français | fr | [Traduction en Français](./README.md) | 2025-02-13 | | Japonais | ja | [Traduction en Japonais](../ja/README.md) | 2025-02-13 | | Coréen | ko | [Traduction en Coréen](../ko/README.md) | 2025-02-13 | | Espagnol | es | [Traduction en Espagnol](../es/README.md) | 2025-02-13 | > **Remarque :** > Ces traductions ont été générées automatiquement à l'aide de l'outil open-source [co-op-translator](https://github.com/Azure/co-op-translator) et peuvent contenir des erreurs ou des imprécisions. Pour des informations critiques, veuillez vous référer au texte original ou consulter une traduction humaine professionnelle. Si vous souhaitez contribuer ou mettre à jour une traduction, rendez-vous sur le dépôt, où vous pouvez facilement apporter des modifications grâce à des commandes simples. ## 🌱 Pour Commencer Ce cours comprend 10 leçons qui couvrent les bases de la création d'Agents IA. Chaque leçon aborde un sujet spécifique, alors commencez où vous voulez ! Si c'est la première fois que vous travaillez avec des modèles d'IA Générative, consultez notre cours [IA Générative pour Débutants](https://aka.ms/genai-beginners), qui propose 21 leçons sur la création avec GenAI. ### Pour exécuter le code de ce cours Ce cours inclut des exemples de code dans chaque leçon qui contient un `code_samples` dossier. Ce code utilise ces services pour les modèles : - [Modèles Github](https://aka.ms/ai-agents-beginners/github-models) - Gratuit / Limité - [Azure AI Foundry](https://aka.ms/ai-agents-beginners/ai-foundry) - Compte Azure requis Ce cours utilise également ces frameworks et services pour Agents IA : - [Service d'Agents Azure AI](https://aka.ms/ai-agents-beginners/ai-agent-service) - [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) - [AutoGen](https://aka.ms/ai-agents/autogen) Pour plus d'informations sur l'exécution du code de ce cours, rendez-vous sur la page [Configuration du Cours](./00-course-setup/README.md). N'oubliez pas de [mettre une étoile (🌟) à ce dépôt](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars?WT.mc_id=academic-105485-koreyst) et de [forker ce dépôt](https://github.com/microsoft/ai-agents-for-beginners/fork) pour exécuter le code. ## 🙏 Vous voulez aider ? Vous avez des suggestions ou avez trouvé des fautes d'orthographe ou des erreurs dans le code ? [Signalez un problème](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst) ou [Créez une pull request](https://github.com/microsoft/ai-agents-for-beginners/pulls?WT.mc_id=academic-105485-koreyst) Si vous êtes bloqué ou avez des questions sur la création d'Agents IA, rejoignez notre [Discord Communauté Azure AI](https://discord.gg/kzRShWzttr). ## 📂 Chaque leçon comprend - Une leçon écrite dans le README (vidéos disponibles en mars 2025) - Des exemples de code Python prenant en charge Azure AI Foundry et les modèles Github (Gratuit) - Des liens vers des ressources supplémentaires pour continuer votre apprentissage ## 🗃️ Leçons | **Leçon** | **Lien** | **Apprentissage Supplémentaire** | |---------------------------------------|--------------------------------------------|-----------------------------------| | Introduction aux Agents IA et Cas d'Utilisation | [Introduction aux Agents IA et Cas d'Utilisation](./01-intro-to-ai-agents/README.md) | En savoir plus | | Explorer les cadres agentiques | [Exploring Agentic Frameworks](./02-explore-agentic-frameworks/README.md) | En savoir plus | | Comprendre les modèles de conception agentiques | [Understanding Agentic Design Patterns](./03-agentic-design-patterns/README.md) | En savoir plus | | Modèle de conception pour l'utilisation d'outils | [Tool Use Design Pattern](./04-tool-use/README.md) | En savoir plus | | Agentic RAG | [Agentic RAG](./05-agentic-rag/README.md) | En savoir plus | | Construire des agents IA de confiance | [Building Trustworthy AI Agents](./06-building-trustworthy-agents/README.md) | En savoir plus | | Modèle de conception pour la planification | [Planning Design Pattern](./07-planning-design/README.md) | En savoir plus | | Modèle de conception multi-agents | [Muilt-Agent Design Pattern](./08-multi-agent/README.md) | En savoir plus | | Modèle de conception pour la métacognition | [Metacognition Design Pattern](./09-metacognition/README.md) | En savoir plus | | Agents IA en production | [AI Agents in Production](./10-ai-agents-production/README.md) | En savoir plus | ## 🎒 Autres cours Notre équipe propose d'autres cours ! Découvrez : - [Generative AI for Beginners](https://aka.ms/genai-beginners) - [ML for Beginners](https://aka.ms/ml-beginners?WT.mc_id=academic-105485-koreyst) - [Data Science for Beginners](https://aka.ms/datascience-beginners?WT.mc_id=academic-105485-koreyst) - [AI for Beginners](https://aka.ms/ai-beginners?WT.mc_id=academic-105485-koreyst) ## Contribution Ce projet accueille volontiers les contributions et suggestions. La plupart des contributions nécessitent que vous acceptiez un Contributor License Agreement (CLA) déclarant que vous avez le droit, et que vous accordez effectivement, les droits pour que nous utilisions votre contribution. Pour plus de détails, visitez <https://cla.opensource.microsoft.com>. Lorsque vous soumettez une pull request, un bot CLA déterminera automatiquement si vous devez fournir un CLA et annotera la PR en conséquence (par exemple, vérification de statut, commentaire). Suivez simplement les instructions fournies par le bot. Vous n'aurez à faire cela qu'une seule fois pour tous les dépôts utilisant notre CLA. Ce projet a adopté le [Code de conduite Open Source de Microsoft](https://opensource.microsoft.com/codeofconduct/). Pour plus d'informations, consultez la [FAQ sur le Code de conduite](https://opensource.microsoft.com/codeofconduct/faq/) ou contactez [[email protected]](mailto:[email protected]) pour toute question ou commentaire supplémentaire. ## Marques déposées Ce projet peut contenir des marques ou des logos pour des projets, produits ou services. L'utilisation autorisée des marques ou logos Microsoft est soumise aux [Directives sur les marques et logos de Microsoft](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general). L'utilisation des marques ou logos Microsoft dans des versions modifiées de ce projet ne doit pas prêter à confusion ou impliquer un parrainage par Microsoft. Toute utilisation de marques ou logos de tiers est soumise aux politiques de ces tiers. **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatique basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de faire appel à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 10124 }
# Sécurité Microsoft prend très au sérieux la sécurité de ses produits et services logiciels, y compris tous les dépôts de code source gérés via nos organisations GitHub, qui incluent [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) et [Xamarin](https://github.com/xamarin). Si vous pensez avoir identifié une vulnérabilité de sécurité dans un dépôt appartenant à Microsoft et répondant à [la définition d'une vulnérabilité de sécurité de Microsoft](https://aka.ms/security.md/definition), veuillez nous en informer comme décrit ci-dessous. ## Signaler des problèmes de sécurité **Veuillez ne pas signaler de vulnérabilités de sécurité via les tickets publics sur GitHub.** Au lieu de cela, veuillez les signaler au Microsoft Security Response Center (MSRC) à l'adresse suivante : [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report). Si vous préférez soumettre votre rapport sans vous connecter, envoyez un e-mail à [[email protected]](mailto:[email protected]). Si possible, chiffrez votre message avec notre clé PGP ; vous pouvez la télécharger depuis la page [Microsoft Security Response Center PGP Key](https://aka.ms/security.md/msrc/pgp). Vous devriez recevoir une réponse dans un délai de 24 heures. Si, pour une raison quelconque, vous ne recevez pas de réponse, veuillez effectuer un suivi par e-mail pour vous assurer que nous avons bien reçu votre message initial. Des informations supplémentaires sont disponibles sur [microsoft.com/msrc](https://www.microsoft.com/msrc). Veuillez inclure les informations demandées ci-dessous (autant que possible) pour nous aider à mieux comprendre la nature et l'étendue du problème potentiel : * Type de problème (par exemple, débordement de tampon, injection SQL, cross-site scripting, etc.) * Chemins complets des fichiers source liés à la manifestation du problème * Emplacement du code source affecté (tag/branche/commit ou URL directe) * Toute configuration spéciale requise pour reproduire le problème * Instructions détaillées pour reproduire le problème * Code de preuve de concept ou d'exploitation (si possible) * Impact du problème, y compris la manière dont un attaquant pourrait exploiter la vulnérabilité Ces informations nous aideront à prioriser votre rapport plus rapidement. Si vous signalez dans le cadre d'un programme de récompense pour bugs, des rapports plus détaillés peuvent contribuer à une récompense plus élevée. Veuillez visiter notre page [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) pour plus de détails sur nos programmes actifs. ## Langues préférées Nous préférons que toutes les communications soient rédigées en anglais. ## Politique Microsoft adhère au principe de la [Divulgation Coordonnée des Vulnérabilités](https://aka.ms/security.md/cvd). ``` **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatique basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de recourir à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées découlant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/SECURITY.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/SECURITY.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 3589 }
# TODO : Le responsable de ce dépôt n'a pas encore modifié ce fichier **PROPRIÉTAIRE DU DÉPÔT** : Souhaitez-vous un support du service client et assistance (CSS) pour ce produit/projet ? - **Pas de support CSS :** Complétez ce modèle avec des informations sur la manière de signaler des problèmes et d'obtenir de l'aide. - **Support CSS activé :** Remplissez un formulaire d'intégration sur [aka.ms/onboardsupport](https://aka.ms/onboardsupport). Le CSS collaborera avec vous pour déterminer les prochaines étapes. - **Pas sûr ?** Remplissez un formulaire d'intégration comme si la réponse était "Oui". Le CSS vous aidera à décider. *Ensuite, supprimez ce premier titre de ce fichier SUPPORT.MD avant de publier votre dépôt.* ## Support ## Comment signaler des problèmes et obtenir de l'aide Ce projet utilise GitHub Issues pour suivre les bugs et les demandes de fonctionnalités. Veuillez rechercher les problèmes existants avant d'en créer de nouveaux afin d'éviter les doublons. Pour signaler un nouveau problème, soumettez votre bug ou demande de fonctionnalité en tant que nouvel "Issue". Pour toute aide ou question concernant l'utilisation de ce projet, veuillez **RESPONSABLE DU DÉPÔT : INSÉREZ ICI LES INSTRUCTIONS POUR CONTACTER LES PROPRIÉTAIRES DU DÉPÔT OU LA COMMUNAUTÉ POUR OBTENIR DE L'AIDE. CELA POURRAIT ÊTRE UN TAG STACK OVERFLOW OU UN AUTRE CANAL. COMMENT AIDEREZ-VOUS LES UTILISATEURS ?**. ## Politique de support Microsoft Le support pour ce **PROJET ou PRODUIT** se limite aux ressources listées ci-dessus. **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatique basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatiques peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de recourir à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/SUPPORT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/SUPPORT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 2193 }
# Microsoft 開源行為守則 此項目採用了 [Microsoft 開源行為守則](https://opensource.microsoft.com/codeofconduct/)。 相關資源: - [Microsoft 開源行為守則](https://opensource.microsoft.com/codeofconduct/) - [Microsoft 行為守則常見問題](https://opensource.microsoft.com/codeofconduct/faq/) - 如有疑問或關注,請聯繫 [[email protected]](mailto:[email protected]) **免責聲明**: 本文件已使用機器翻譯服務進行翻譯。我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文文件為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或錯誤解釋概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/CODE_OF_CONDUCT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/CODE_OF_CONDUCT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 442 }
# 初學者 AI Agents 課程 ![Generative AI For Beginners](../../translated_images/repo-thumbnail.fdd5f487bb7274d4a08459d76907ec4914de268c99637e9af082b1d3eb0730e2.hk.png?WT.mc_id=academic-105485-koreyst) ## 10 個課堂,教你從零開始建立 AI Agents 所需的一切 [![GitHub license](https://img.shields.io/github/license/microsoft/ai-agents-for-beginners.svg)](https://github.com/microsoft/ai-agents-for-beginners/blob/master/LICENSE?WT.mc_id=academic-105485-koreyst) [![GitHub contributors](https://img.shields.io/github/contributors/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/graphs/contributors/?WT.mc_id=academic-105485-koreyst) [![GitHub issues](https://img.shields.io/github/issues/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/issues/?WT.mc_id=academic-105485-koreyst) [![GitHub pull-requests](https://img.shields.io/github/issues-pr/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/pulls/?WT.mc_id=academic-105485-koreyst) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com?WT.mc_id=academic-105485-koreyst) [![GitHub watchers](https://img.shields.io/github/watchers/microsoft/ai-agents-for-beginners.svg?style=social&label=Watch)](https://GitHub.com/microsoft/ai-agents-for-beginners/watchers/?WT.mc_id=academic-105485-koreyst) [![GitHub forks](https://img.shields.io/github/forks/microsoft/ai-agents-for-beginners.svg?style=social&label=Fork)](https://GitHub.com/microsoft/ai-agents-for-beginners/network/?WT.mc_id=academic-105485-koreyst) [![GitHub stars](https://img.shields.io/github/stars/microsoft/ai-agents-for-beginners.svg?style=social&label=Star)](https://GitHub.com/microsoft/ai-agents-for-beginners/stargazers/?WT.mc_id=academic-105485-koreyst) [![Azure AI Discord](https://dcbadge.limes.pink/api/server/kzRShWzttr)](https://discord.gg/kzRShWzttr) ## 🌐 多語言支援 | 語言 | 代碼 | 翻譯後的 README 連結 | 最後更新日期 | |----------------------|------|---------------------------------------------------------|--------------| | 簡體中文 | zh | [中文翻譯](../zh/README.md) | 2025-02-13 | | 繁體中文 | tw | [中文翻譯](../tw/README.md) | 2025-02-13 | | 香港繁體中文 | hk | [中文翻譯](../hk/README.md) | 2025-02-13 | | 法語 | fr | [法語翻譯](../fr/README.md) | 2025-02-13 | | 日語 | ja | [日語翻譯](../ja/README.md) | 2025-02-13 | | 韓語 | ko | [韓語翻譯](../ko/README.md) | 2025-02-13 | | 葡萄牙語 | pt | [葡萄牙語翻譯](../pt/README.md) | 2025-02-13 | | 西班牙語 | es | [西班牙語翻譯](../es/README.md) | 2025-02-13 | ## 🌱 快速開始 呢個課程有 10 個課堂,覆蓋建立 AI Agents 嘅基本知識。每個課堂都有自己嘅主題,所以你可以由你鍾意嘅地方開始學! 如果你係第一次接觸生成式 AI 模型,建議先睇下我哋嘅 [Generative AI For Beginners](https://aka.ms/genai-beginners) 課程,呢個課程有 21 個課堂教你點樣使用 GenAI。 ### 點樣執行呢個課程嘅程式碼 呢個課程每個課堂都有 `code_samples` 資料夾內嘅程式碼範例。呢啲程式碼會用到以下模型服務: - [Github Models](https://aka.ms/ai-agents-beginners/github-models) - 免費 / 有限制 - [Azure AI Foundry](https://aka.ms/ai-agents-beginners/ai-foundry) - 需要 Azure 帳戶 另外,課程會用到以下 AI Agent 框架同服務: - [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service) - [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) - [AutoGen](https://aka.ms/ai-agents/autogen) 想了解更多點樣執行呢個課程嘅程式碼,可以睇下 [Course Setup](./00-course-setup/README.md)。 記得幫呢個 repo [加星 (🌟)](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars?WT.mc_id=academic-105485-koreyst) 同 [fork](https://github.com/microsoft/ai-agents-for-beginners/fork) 嚟執行程式碼。 ## 🙏 想幫手? 如果你有建議,或者發現拼寫或者程式碼錯誤,可以 [提交問題](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst) 或者 [建立 pull request](https://github.com/microsoft/ai-agents-for-beginners/pulls?WT.mc_id=academic-105485-koreyst)。 如果你有問題或者唔知點樣建立 AI Agents,可以加入我哋嘅 [Azure AI Community Discord](https://discord.gg/kzRShWzttr) 問問題。 ## 📂 每個課堂包含 - 一個寫喺 README 入面嘅課堂內容(影片將於 2025 年 3 月推出) - 支援 Azure AI Foundry 同 Github Models 嘅 Python 程式碼範例(免費) - 連結到額外學習資源,幫助你進一步學習 ## 🗃️ 課堂內容 | **課堂** | **連結** | **額外學習** | |----------------------------------------|--------------------------------------------|--------------------| | AI Agents 同應用案例簡介 | [Intro to AI Agents and Use Cases](./01-intro-to-ai-agents/README.md) | Learn More | | 探索 Agentic 框架 | [Exploring Agentic Frameworks](./02-explore-agentic-frameworks/README.md) | Learn More | | 理解 Agentic 設計模式 | [Understanding Agentic Design Patterns](./03-agentic-design-patterns/README.md) | Learn More | | 工具使用設計模式 | [Tool Use Design Pattern](./04-tool-use/README.md) | Learn More | | Agentic RAG | [Agentic RAG](./05-agentic-rag/README.md) | Learn More | | 建立值得信任嘅 AI Agents | [Building Trustworthy AI Agents](./06-building-trustworthy-agents/README.md) | Learn More | | 計劃設計模式 | [Planning Design Pattern](./07-planning-design/README.md) | Learn More | | 多 Agent 設計模式 | [Muilt-Agent Design Pattern](./08-multi-agent/README.md) | Learn More | | 元認知設計模式 | [Metacognition Design Pattern](./09-metacognition/README.md) | 了解更多 | | 生產中的 AI 代理 | [AI Agents in Production](./10-ai-agents-production/README.md) | 了解更多 | ## 🎒 其他課程 我哋嘅團隊仲有製作其他課程!睇吓呢啲: - [Generative AI for Beginners](https://aka.ms/genai-beginners) - [ML for Beginners](https://aka.ms/ml-beginners?WT.mc_id=academic-105485-koreyst) - [Data Science for Beginners](https://aka.ms/datascience-beginners?WT.mc_id=academic-105485-koreyst) - [AI for Beginners](https://aka.ms/ai-beginners?WT.mc_id=academic-105485-koreyst) ## 貢獻 呢個項目歡迎任何貢獻同建議。大部分嘅貢獻需要你同意一份貢獻者許可協議 (Contributor License Agreement, CLA),聲明你有權授權並且確實授權我哋使用你嘅貢獻。詳情請睇 <https://cla.opensource.microsoft.com>。 當你提交一個 pull request 嘅時候,一個 CLA bot 會自動判斷你需唔需要提供 CLA,並會適當地標註 PR(例如:狀態檢查、留言)。只需要跟住 bot 提供嘅指示操作即可。你只需要喺所有使用我哋 CLA 嘅 repo 中做一次呢個步驟。 呢個項目採用了 [Microsoft 開源行為準則](https://opensource.microsoft.com/codeofconduct/)。更多資訊可以參考 [行為準則 FAQ](https://opensource.microsoft.com/codeofconduct/faq/),或者聯絡 [[email protected]](mailto:[email protected]) 提出其他問題或者意見。 ## 商標 呢個項目可能包含項目、產品或者服務嘅商標或者標誌。使用 Microsoft 商標或者標誌必須遵守並符合 [Microsoft 商標及品牌指南](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general)。喺修改版本嘅項目中使用 Microsoft 商標或者標誌唔可以引起混淆或者暗示係 Microsoft 嘅贊助。任何使用第三方商標或者標誌嘅行為需要遵守第三方嘅政策。 **免責聲明**: 本文件是使用機器翻譯人工智能服務翻譯的。我們雖然致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文語言的文件作為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對於使用本翻譯而引起的任何誤解或誤譯概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 7021 }
# 保安 Microsoft 非常重視我們軟件產品和服務的安全性,這包括通過我們的 GitHub 組織管理的所有源代碼庫,例如 [Microsoft](https://github.com/Microsoft)、[Azure](https://github.com/Azure)、[DotNet](https://github.com/dotnet)、[AspNet](https://github.com/aspnet) 和 [Xamarin](https://github.com/xamarin)。 如果你認為你發現了任何 Microsoft 擁有的代碼庫中存在的安全漏洞,並且該漏洞符合 [Microsoft 對安全漏洞的定義](https://aka.ms/security.md/definition),請按照以下描述向我們報告。 ## 報告安全問題 **請不要通過公開的 GitHub 問題報告安全漏洞。** 相反,請通過 Microsoft Security Response Center (MSRC) 報告,網址為 [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report)。 如果你更願意在未登錄的情況下提交,請發送電子郵件至 [[email protected]](mailto:[email protected])。如有可能,請使用我們的 PGP 密鑰加密你的信息;可以從 [Microsoft Security Response Center PGP Key 頁面](https://aka.ms/security.md/msrc/pgp) 下載。 你應該會在 24 小時內收到回覆。如果出於某些原因未收到,請通過電子郵件跟進,以確保我們收到了你的原始消息。更多資訊可以在 [microsoft.com/msrc](https://www.microsoft.com/msrc) 找到。 請包括以下列出的信息(提供越多越好),以幫助我們更好地理解可能問題的性質和範圍: * 問題類型(例如,緩衝區溢出、SQL 注入、跨站腳本攻擊等) * 與問題表現相關的源文件完整路徑 * 受影響源代碼的位置(標籤/分支/提交或直接 URL) * 重現問題所需的任何特殊配置 * 重現問題的逐步操作說明 * 概念驗證或漏洞利用代碼(如果可能) * 問題的影響,包括攻擊者可能如何利用該問題 這些信息將幫助我們更快速地處理你的報告。 如果你是為了參與漏洞賞金計劃進行報告,更完整的報告可能有助於獲得更高的賞金獎勵。請訪問我們的 [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) 頁面,了解更多有關我們現行計劃的詳情。 ## 首選語言 我們更希望所有的通信以英文進行。 ## 政策 Microsoft 遵循 [協調漏洞披露](https://aka.ms/security.md/cvd) 的原則。 **免責聲明**: 本文件經由機器人工智能翻譯服務進行翻譯。我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文文件作為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或誤讀概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/SECURITY.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/SECURITY.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1455 }
# TODO: 此 Repo 的維護者尚未編輯此文件 **REPO 擁有者**:你希望為此產品/項目提供客戶服務與支持 (CSS) 嗎? - **不需要 CSS 支持**:請填寫此模板,提供有關如何提交問題和獲取幫助的信息。 - **需要 CSS 支持**:請填寫 [aka.ms/onboardsupport](https://aka.ms/onboardsupport) 上的申請表。CSS 會與你合作/幫助你確定下一步操作。 - **不確定?** 請按照「需要」的情況填寫申請表。CSS 會幫助你做出決定。 *然後在發布你的 Repo 之前,從這個 SUPPORT.MD 文件中刪除此第一個標題。* ## 支持 ## 如何提交問題與獲取幫助 此項目使用 GitHub Issues 來跟蹤漏洞和功能請求。在提交新問題之前,請先搜索現有的問題以避免重複。對於新問題,請將你的漏洞或功能請求作為新 Issue 提交。 如果需要幫助或對使用此項目有疑問,請 **REPO 維護者:在這裡插入與 Repo 擁有者或社區互動以獲得幫助的說明。可以是一個 Stack Overflow 標籤或其他渠道。你會在哪裡幫助人們?**。 ## Microsoft 支持政策 對於此 **項目或產品** 的支持僅限於上述列出的資源。 **免責聲明**: 本文件是使用機器翻譯人工智能服務進行翻譯的。我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文作為權威來源。對於關鍵資訊,建議使用專業人工翻譯。我們對於因使用此翻譯而引起的任何誤解或誤讀概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/SUPPORT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/SUPPORT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 694 }
# Microsoft オープンソース行動規範 このプロジェクトは、[Microsoft オープンソース行動規範](https://opensource.microsoft.com/codeofconduct/) を採用しています。 リソース: - [Microsoft オープンソース行動規範](https://opensource.microsoft.com/codeofconduct/) - [Microsoft 行動規範 FAQ](https://opensource.microsoft.com/codeofconduct/faq/) - 質問や懸念がある場合は、[[email protected]](mailto:[email protected]) にお問い合わせください ``` **免責事項**: この文書は、AI翻訳サービスを使用して機械翻訳されたものです。正確性を追求しておりますが、自動翻訳には誤りや不正確さが含まれる可能性があることをご承知おきください。原文(原言語の文書)が公式な情報源として優先されるべきです。重要な情報については、専門の人間による翻訳をお勧めします。本翻訳の使用により生じた誤解や誤認について、当方は一切の責任を負いかねます。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/ja/CODE_OF_CONDUCT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/CODE_OF_CONDUCT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 567 }
# 初心者向け AI エージェント - コース ![Generative AI For Beginners](../../translated_images/repo-thumbnail.fdd5f487bb7274d4a08459d76907ec4914de268c99637e9af082b1d3eb0730e2.ja.png?WT.mc_id=academic-105485-koreyst) ## AIエージェントを作成するために必要なすべてを学べる10のレッスン [![GitHub license](https://img.shields.io/github/license/microsoft/ai-agents-for-beginners.svg)](https://github.com/microsoft/ai-agents-for-beginners/blob/master/LICENSE?WT.mc_id=academic-105485-koreyst) [![GitHub contributors](https://img.shields.io/github/contributors/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/graphs/contributors/?WT.mc_id=academic-105485-koreyst) [![GitHub issues](https://img.shields.io/github/issues/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/issues/?WT.mc_id=academic-105485-koreyst) [![GitHub pull-requests](https://img.shields.io/github/issues-pr/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/pulls/?WT.mc_id=academic-105485-koreyst) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com?WT.mc_id=academic-105485-koreyst) [![GitHub watchers](https://img.shields.io/github/watchers/microsoft/ai-agents-for-beginners.svg?style=social&label=Watch)](https://GitHub.com/microsoft/ai-agents-for-beginners/watchers/?WT.mc_id=academic-105485-koreyst) [![GitHub forks](https://img.shields.io/github/forks/microsoft/ai-agents-for-beginners.svg?style=social&label=Fork)](https://GitHub.com/microsoft/ai-agents-for-beginners/network/?WT.mc_id=academic-105485-koreyst) [![GitHub stars](https://img.shields.io/github/stars/microsoft/ai-agents-for-beginners.svg?style=social&label=Star)](https://GitHub.com/microsoft/ai-agents-for-beginners/stargazers/?WT.mc_id=academic-105485-koreyst) [![Azure AI Discord](https://dcbadge.limes.pink/api/server/kzRShWzttr)](https://discord.gg/kzRShWzttr) ## 🌐 多言語対応 | 言語 | コード | 翻訳されたREADMEへのリンク | 最終更新日 | |-----------------------|--------|---------------------------------------------------------|------------| | 中国語(簡体字) | zh | [Chinese Translation](../zh/README.md) | 2025-02-13 | | 中国語(繁体字) | tw | [Chinese Translation](../tw/README.md) | 2025-02-13 | | フランス語 | fr | [French Translation](../fr/README.md) | 2025-02-13 | | 日本語 | ja | [Japanese Translation](./README.md) | 2025-02-13 | | 韓国語 | ko | [Korean Translation](../ko/README.md) | 2025-02-13 | | スペイン語 | es | [Spanish Translation](../es/README.md) | 2025-02-13 | > **Note:** > これらの翻訳は、オープンソースの[co-op-translator](https://github.com/Azure/co-op-translator)を使用して自動生成されています。そのため、誤りや不正確な箇所が含まれている可能性があります。重要な情報については、元のテキストを参照するか、専門の人間翻訳を依頼してください。翻訳の貢献や更新を希望される場合は、リポジトリをご覧いただき、簡単なコマンドで貢献できます。 ## 🌱 始めるには このコースでは、AIエージェント構築の基礎を学ぶための10のレッスンを提供しています。それぞれのレッスンは独立したトピックを扱っているので、好きなところから始めてください! 初めて生成AIモデルを使用する場合は、21のレッスンで構成された[Generative AI For Beginners](https://aka.ms/genai-beginners)コースをチェックしてください。 ### コースのコードを実行するには このコースには、各レッスンに`code_samples`フォルダが含まれるコード例があります。このコードでは以下のモデルサービスを使用します: - [Github Models](https://aka.ms/ai-agents-beginners/github-models) - 無料 / 制限あり - [Azure AI Foundry](https://aka.ms/ai-agents-beginners/ai-foundry) - Azureアカウントが必要 また、このコースでは以下のAIエージェントフレームワークとサービスを使用します: - [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service) - [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) - [AutoGen](https://aka.ms/ai-agents/autogen) コースのコードを実行する方法についての詳細は、[Course Setup](./00-course-setup/README.md)をご覧ください。 リポジトリを[スター (🌟)](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars?WT.mc_id=academic-105485-koreyst)したり、[フォーク](https://github.com/microsoft/ai-agents-for-beginners/fork)してコードを実行することをお忘れなく。 ## 🙏 貢献したいですか? 提案がある、またはスペルミスやコードのエラーを見つけた場合は、[問題を報告する](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst)か、[プルリクエストを作成する](https://github.com/microsoft/ai-agents-for-beginners/pulls?WT.mc_id=academic-105485-koreyst)ことでお知らせください。 AIエージェントの構築で行き詰まったり質問がある場合は、[Azure AI Community Discord](https://discord.gg/kzRShWzttr)に参加してください。 ## 📂 各レッスンには以下が含まれます - READMEに記載されたレッスン内容(ビデオは2025年3月公開予定) - Azure AI FoundryとGithub Models(無料)をサポートするPythonコードサンプル - 学習を継続するための追加リソースへのリンク ## 🗃️ レッスン一覧 | **レッスン** | **リンク** | **追加学習** | |----------------------------------------|--------------------------------------------|--------------------| | AIエージェントとユースケースの紹介 | [Intro to AI Agents and Use Cases](./01-intro-to-ai-agents/README.md) | Learn More | | エージェントフレームワークの探求 | [Exploring Agentic Frameworks](./02-explore-agentic-frameworks/README.md) | 詳しく見る | | エージェントデザインパターンの理解 | [Understanding Agentic Design Patterns](./03-agentic-design-patterns/README.md) | 詳しく見る | | ツール使用デザインパターン | [Tool Use Design Pattern](./04-tool-use/README.md) | 詳しく見る | | エージェントRAG | [Agentic RAG](./05-agentic-rag/README.md) | 詳しく見る | | 信頼できるAIエージェントの構築 | [Building Trustworthy AI Agents](./06-building-trustworthy-agents/README.md) | 詳しく見る | | プランニングデザインパターン | [Planning Design Pattern](./07-planning-design/README.md) | 詳しく見る | | マルチエージェントデザインパターン | [Muilt-Agent Design Pattern](./08-multi-agent/README.md) | 詳しく見る | | メタ認知デザインパターン | [Metacognition Design Pattern](./09-metacognition/README.md) | 詳しく見る | | 本番環境でのAIエージェント | [AI Agents in Production](./10-ai-agents-production/README.md) | 詳しく見る | ## 🎒 その他のコース 私たちのチームでは他にもコースを提供しています!ぜひチェックしてください: - [Generative AI for Beginners](https://aka.ms/genai-beginners) - [ML for Beginners](https://aka.ms/ml-beginners?WT.mc_id=academic-105485-koreyst) - [Data Science for Beginners](https://aka.ms/datascience-beginners?WT.mc_id=academic-105485-koreyst) - [AI for Beginners](https://aka.ms/ai-beginners?WT.mc_id=academic-105485-koreyst) ## コントリビューション このプロジェクトでは、貢献や提案を歓迎しています。ほとんどの貢献には、Contributor License Agreement (CLA) に同意する必要があります。CLAに同意することで、あなたがその貢献を行う権利を有し、またその貢献を当方が使用する権利を付与することを宣言します。詳細については、<https://cla.opensource.microsoft.com> をご覧ください。 プルリクエストを送信すると、CLAボットが自動的にCLAの提供が必要かどうかを判断し、PRに適切なステータス(例:ステータスチェック、コメント)を付けます。ボットの指示に従うだけでOKです。CLAは、当方のCLAを使用しているすべてのリポジトリで一度だけ提供すれば済みます。 このプロジェクトでは、[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) を採用しています。詳細については、[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) をご覧いただくか、追加の質問やコメントがある場合は [[email protected]](mailto:[email protected]) にご連絡ください。 ## 商標について このプロジェクトには、プロジェクト、製品、またはサービスに関連する商標やロゴが含まれている場合があります。Microsoftの商標やロゴの使用は、[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general) に従う必要があります。また、Microsoft商標やロゴを改変したバージョンで使用する場合、混乱を引き起こしたりMicrosoftのスポンサーシップを示唆するような使用をしてはいけません。第三者の商標やロゴの使用については、それぞれの第三者のポリシーに従う必要があります。 **免責事項**: 本書類は、機械ベースのAI翻訳サービスを使用して翻訳されています。正確性を追求しておりますが、自動翻訳には誤りや不正確な部分が含まれる可能性があることをご承知おきください。元の言語で記載された原本を信頼できる情報源としてご参照ください。重要な情報については、専門の人間による翻訳をお勧めします。本翻訳の使用に起因する誤解や誤認について、当社は一切の責任を負いかねます。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/ja/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 7591 }
# セキュリティ Microsoft は、ソフトウェア製品やサービスのセキュリティを非常に重要視しています。これには、[Microsoft](https://github.com/Microsoft)、[Azure](https://github.com/Azure)、[DotNet](https://github.com/dotnet)、[AspNet](https://github.com/aspnet)、および [Xamarin](https://github.com/xamarin) を含む、GitHub 組織を通じて管理されているすべてのソースコードリポジトリが含まれます。 もし、[Microsoft のセキュリティ脆弱性の定義](https://aka.ms/security.md/definition) に該当するセキュリティ脆弱性を Microsoft が所有するリポジトリで発見した場合は、以下に記載された方法で報告してください。 ## セキュリティ問題の報告 **セキュリティ脆弱性を公開 GitHub Issue を通じて報告しないでください。** 代わりに、Microsoft Security Response Center (MSRC) に [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report) から報告してください。 ログインせずに報告したい場合は、[[email protected]](mailto:[email protected]) にメールを送信してください。可能であれば、メッセージを PGP キーで暗号化してください。PGP キーは [Microsoft Security Response Center PGP Key ページ](https://aka.ms/security.md/msrc/pgp) からダウンロードできます。 通常、24 時間以内に応答を受け取ることができます。万が一応答がない場合は、元のメッセージが届いているか確認するため、メールで再度ご連絡ください。追加情報については [microsoft.com/msrc](https://www.microsoft.com/msrc) をご覧ください。 以下にリストされた情報を可能な限り提供してください。これにより、問題の性質や範囲をよりよく理解することができます: * 問題の種類(例: バッファオーバーフロー、SQL インジェクション、クロスサイトスクリプティングなど) * 問題が発生しているソースファイルの完全なパス * 影響を受けるソースコードの場所(タグ/ブランチ/コミット、または直接の URL) * 問題を再現するために必要な特別な設定 * 問題を再現するための手順 * PoC(概念実証)やエクスプロイトコード(可能であれば) * 問題の影響範囲(攻撃者がどのように問題を悪用する可能性があるかを含む) これらの情報を提供していただくことで、報告内容の優先順位付けを迅速に行うことができます。 バグバウンティプログラムで報告する場合、詳細なレポートを提出することで、より高い報酬を得られる可能性があります。詳細については、[Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) ページをご覧ください。 ## 推奨言語 すべてのやり取りは英語で行うことを推奨します。 ## ポリシー Microsoft は、[Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd) の原則に従っています。 **免責事項**: この文書は、機械ベースのAI翻訳サービスを使用して翻訳されています。正確性を追求しておりますが、自動翻訳にはエラーや不正確な部分が含まれる場合があります。元の言語で記載された原文を正式な情報源としてお考えください。重要な情報については、専門の人間による翻訳を推奨します。この翻訳の使用により生じた誤解や誤解釈について、当方は一切の責任を負いかねます。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/ja/SECURITY.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/SECURITY.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1862 }
# TODO: このリポジトリの管理者はまだこのファイルを編集していません **リポジトリ管理者**: このプロダクト/プロジェクトに対してカスタマーサービス&サポート(CSS)のサポートを希望しますか? - **CSSサポートなし:** 問題の報告方法やヘルプを得る方法についての情報をこのテンプレートに記入してください。 - **CSSサポートあり:** [aka.ms/onboardsupport](https://aka.ms/onboardsupport) でインテークフォームに記入してください。CSSが次のステップを一緒に検討し、サポートします。 - **よくわからない場合:** 回答が「はい」であるかのようにインテークフォームに記入してください。CSSが判断を手伝います。 *その後、このSUPPORT.MDファイルからこの最初の見出しを削除してからリポジトリを公開してください。* ## サポート ## 問題の報告方法とヘルプの取得方法 このプロジェクトでは、GitHub Issues を使用してバグや機能リクエストを追跡しています。重複を避けるために、新しい問題を報告する前に既存の問題を検索してください。新しい問題については、新しい Issue としてバグや機能リクエストを報告してください。 このプロジェクトの使用方法に関するヘルプや質問については、**リポジトリ管理者: このプロジェクトのオーナーまたはコミュニティにヘルプを依頼する方法をここに記載してください。Stack Overflow のタグやその他のチャンネルが含まれるかもしれません。どこで人々をサポートしますか?**。 ## Microsoft サポートポリシー この **プロジェクトまたは製品** に対するサポートは、上記に記載されているリソースに限定されています。 **免責事項**: 本書類は、機械翻訳AIサービスを使用して翻訳されています。正確性を追求しておりますが、自動翻訳には誤りや不正確な表現が含まれる可能性があります。本書類の原文を信頼できる情報源と見なしてください。重要な情報については、専門の人間による翻訳を推奨します。本翻訳の利用により生じた誤解や誤解釈について、当方は一切の責任を負いかねます。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/ja/SUPPORT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/SUPPORT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 997 }
# Microsoft 오픈 소스 행동 강령 이 프로젝트는 [Microsoft 오픈 소스 행동 강령](https://opensource.microsoft.com/codeofconduct/)을 채택했습니다. 리소스: - [Microsoft 오픈 소스 행동 강령](https://opensource.microsoft.com/codeofconduct/) - [Microsoft 행동 강령 FAQ](https://opensource.microsoft.com/codeofconduct/faq/) - 질문이나 우려 사항이 있으시면 [[email protected]](mailto:[email protected])으로 연락하세요. **면책 조항**: 이 문서는 AI 기반 기계 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있음을 유의하시기 바랍니다. 원문이 작성된 언어의 문서를 신뢰할 수 있는 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생할 수 있는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/ko/CODE_OF_CONDUCT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/CODE_OF_CONDUCT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 610 }
# 초보자를 위한 AI 에이전트 - 강의 ![Generative AI For Beginners](../../translated_images/repo-thumbnail.fdd5f487bb7274d4a08459d76907ec4914de268c99637e9af082b1d3eb0730e2.ko.png?WT.mc_id=academic-105485-koreyst) ## 🌐 다국어 지원 | 언어 | 코드 | 번역된 README 링크 | 마지막 업데이트 | |----------------------|------|---------------------------------------------------------|-----------------| | 중국어 (간체) | zh | [Chinese Translation](../zh/README.md) | 2025-02-13 | | 중국어 (번체) | tw | [Chinese Translation](../tw/README.md) | 2025-02-13 | | 프랑스어 | fr | [French Translation](../fr/README.md) | 2025-02-13 | | 일본어 | ja | [Japanese Translation](../ja/README.md) | 2025-02-13 | | 한국어 | ko | [Korean Translation](./README.md) | 2025-02-13 | | 스페인어 | es | [Spanish Translation](../es/README.md) | 2025-02-13 | > **참고:** > 이 번역은 오픈 소스 [co-op-translator](https://github.com/Azure/co-op-translator)를 사용하여 자동 생성되었으며, 오류나 부정확성이 포함될 수 있습니다. > 중요한 정보의 경우 원본 텍스트를 참고하거나 전문 번역가의 도움을 받는 것을 권장합니다. > 번역을 추가하거나 수정하고 싶다면, 해당 저장소를 방문하여 간단한 명령어로 기여할 수 있습니다. ## AI 에이전트를 구축하기 위해 알아야 할 모든 것을 가르치는 10개의 강의 [![GitHub license](https://img.shields.io/github/license/microsoft/ai-agents-for-beginners.svg)](https://github.com/microsoft/ai-agents-for-beginners/blob/master/LICENSE?WT.mc_id=academic-105485-koreyst) [![GitHub contributors](https://img.shields.io/github/contributors/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/graphs/contributors/?WT.mc_id=academic-105485-koreyst) [![GitHub issues](https://img.shields.io/github/issues/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/issues/?WT.mc_id=academic-105485-koreyst) [![GitHub pull-requests](https://img.shields.io/github/issues-pr/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/pulls/?WT.mc_id=academic-105485-koreyst) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com?WT.mc_id=academic-105485-koreyst) [![GitHub watchers](https://img.shields.io/github/watchers/microsoft/ai-agents-for-beginners.svg?style=social&label=Watch)](https://GitHub.com/microsoft/ai-agents-for-beginners/watchers/?WT.mc_id=academic-105485-koreyst) [![GitHub forks](https://img.shields.io/github/forks/microsoft/ai-agents-for-beginners.svg?style=social&label=Fork)](https://GitHub.com/microsoft/ai-agents-for-beginners/network/?WT.mc_id=academic-105485-koreyst) [![GitHub stars](https://img.shields.io/github/stars/microsoft/ai-agents-for-beginners.svg?style=social&label=Star)](https://GitHub.com/microsoft/ai-agents-for-beginners/stargazers/?WT.mc_id=academic-105485-koreyst) [![Azure AI Discord](https://dcbadge.limes.pink/api/server/kzRShWzttr)](https://discord.gg/kzRShWzttr) ## 🌱 시작하기 이 강의는 AI 에이전트를 구축하는 기본 개념을 다루는 10개의 강의로 구성되어 있습니다. 각 강의는 독립적인 주제를 다루므로 원하는 곳부터 시작할 수 있습니다! Generative AI 모델을 처음 접하는 경우, 21개의 강의로 구성된 [Generative AI For Beginners](https://aka.ms/genai-beginners) 강의를 먼저 확인해 보세요. ### 이 강의의 코드를 실행하려면 이 강의의 각 강의에는 `code_samples` 폴더가 포함된 코드 예제가 있습니다. 이 코드는 다음 서비스를 사용하여 모델을 실행합니다: - [Github Models](https://aka.ms/ai-agents-beginners/github-models) - 무료 / 제한적 - [Azure AI Foundry](https://aka.ms/ai-agents-beginners/ai-foundry) - Azure 계정 필요 또한 이 강의에서는 다음 AI 에이전트 프레임워크와 서비스를 사용합니다: - [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service) - [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) - [AutoGen](https://aka.ms/ai-agents/autogen) 이 강의의 코드를 실행하는 방법에 대한 자세한 내용은 [Course Setup](./00-course-setup/README.md)을 참조하세요. 이 저장소를 [별표(🌟)로 표시하기](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars?WT.mc_id=academic-105485-koreyst)와 [포크하기](https://github.com/microsoft/ai-agents-for-beginners/fork)를 잊지 마세요. ## 🙏 도움을 주고 싶으신가요? 제안 사항이 있거나 철자 또는 코드 오류를 발견하셨나요? [이슈 등록하기](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst) 또는 [풀 리퀘스트 생성하기](https://github.com/microsoft/ai-agents-for-beginners/pulls?WT.mc_id=academic-105485-koreyst) AI 에이전트를 구축하는 데 어려움을 겪거나 질문이 있으시면 [Azure AI Community Discord](https://discord.gg/kzRShWzttr)에 참여하세요. ## 📂 각 강의에는 다음이 포함됩니다 - README에 작성된 강의 내용 (비디오는 2025년 3월 공개 예정) - Azure AI Foundry와 Github Models(무료)을 지원하는 Python 코드 샘플 - 학습을 이어갈 수 있는 추가 리소스 링크 ## 🗃️ 강의 목록 | **강의** | **링크** | **추가 학습** | |----------------------------------------|--------------------------------------------|--------------------| | AI 에이전트와 활용 사례 소개 | [Intro to AI Agents and Use Cases](./01-intro-to-ai-agents/README.md) | Learn More | | 에이전틱 프레임워크 탐구 | [Exploring Agentic Frameworks](./02-explore-agentic-frameworks/README.md) | Learn More | | 에이전틱 디자인 패턴 이해하기 | [Understanding Agentic Design Patterns](./03-agentic-design-patterns/README.md) | Learn More | | 도구 활용 디자인 패턴 | [Tool Use Design Pattern](./04-tool-use/README.md) | Learn More | | 에이전틱 RAG | [Agentic RAG](./05-agentic-rag/README.md) | Learn More | | 신뢰할 수 있는 AI 에이전트 구축하기 | [Building Trustworthy AI Agents](./06-building-trustworthy-agents/README.md) | Learn More | | 계획 디자인 패턴 | [Planning Design Pattern](./07-planning-design/README.md) | Learn More | | 다중 에이전트 디자인 패턴 | [Muilt-Agent Design Pattern](./08-multi-agent/README.md) | Learn More | | 메타인지 설계 패턴 | [Metacognition Design Pattern](./09-metacognition/README.md) | 더 알아보기 | | AI 에이전트 프로덕션 활용 | [AI Agents in Production](./10-ai-agents-production/README.md) | 더 알아보기 | ## 🎒 기타 강의 우리 팀에서 제공하는 다른 강의도 확인해 보세요! - [초보자를 위한 생성형 AI](https://aka.ms/genai-beginners) - [초보자를 위한 머신러닝](https://aka.ms/ml-beginners?WT.mc_id=academic-105485-koreyst) - [초보자를 위한 데이터 과학](https://aka.ms/datascience-beginners?WT.mc_id=academic-105485-koreyst) - [초보자를 위한 AI](https://aka.ms/ai-beginners?WT.mc_id=academic-105485-koreyst) ## 기여하기 이 프로젝트는 기여와 제안을 환영합니다. 대부분의 기여는 기여자 라이선스 계약(Contributor License Agreement, CLA)에 동의해야 합니다. CLA는 여러분이 기여한 내용을 사용할 권리를 우리에게 부여할 수 있는 권리를 보유하고 있음을 선언하는 문서입니다. 자세한 내용은 <https://cla.opensource.microsoft.com>를 참조하세요. 풀 리퀘스트를 제출하면 CLA 봇이 자동으로 여러분이 CLA를 제공해야 하는지 여부를 확인하고 PR에 적절히 표시(예: 상태 확인, 댓글)합니다. 봇이 제공하는 지침을 따르기만 하면 됩니다. 이 작업은 CLA를 사용하는 모든 저장소에서 한 번만 진행하면 됩니다. 이 프로젝트는 [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)를 채택하고 있습니다. 자세한 내용은 [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)를 참조하거나, 추가 질문이나 의견이 있으면 [[email protected]](mailto:[email protected])으로 연락하세요. ## 상표 이 프로젝트에는 프로젝트, 제품, 서비스와 관련된 상표 또는 로고가 포함될 수 있습니다. Microsoft 상표 또는 로고의 허가된 사용은 [Microsoft의 상표 및 브랜드 가이드라인](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general)을 따라야 합니다. 이 프로젝트의 수정된 버전에서 Microsoft 상표 또는 로고를 사용하는 경우 혼란을 초래하거나 Microsoft의 후원을 암시해서는 안 됩니다. 제3자 상표 또는 로고의 사용은 해당 제3자의 정책을 따라야 합니다. **면책 조항**: 이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원어로 작성된 원본 문서를 신뢰할 수 있는 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 오역에 대해 당사는 책임을 지지 않습니다.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/ko/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 7609 }
# 보안 Microsoft는 소프트웨어 제품과 서비스의 보안을 매우 중요하게 생각합니다. 이는 [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin)과 같은 GitHub 조직을 통해 관리되는 모든 소스 코드 저장소를 포함합니다. 만약 [Microsoft의 보안 취약성 정의](https://aka.ms/security.md/definition)에 해당하는 보안 취약성을 Microsoft 소유의 저장소에서 발견했다고 생각되면, 아래 설명된 절차에 따라 보고해 주시기 바랍니다. ## 보안 문제 보고 **공개 GitHub 이슈를 통해 보안 취약성을 보고하지 마십시오.** 대신, Microsoft Security Response Center (MSRC)에 [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report)를 통해 보고해 주십시오. 로그인 없이 제출을 원하시는 경우, [[email protected]](mailto:[email protected])으로 이메일을 보내주시기 바랍니다. 가능하다면, 메시지를 Microsoft의 PGP 키로 암호화하여 보내주십시오. PGP 키는 [Microsoft Security Response Center PGP Key 페이지](https://aka.ms/security.md/msrc/pgp)에서 다운로드할 수 있습니다. 보통 24시간 이내에 응답을 받을 수 있습니다. 만약 그렇지 않은 경우, 원본 메시지가 제대로 전달되었는지 확인하기 위해 이메일로 다시 문의해 주시기 바랍니다. 추가 정보는 [microsoft.com/msrc](https://www.microsoft.com/msrc)에서 확인할 수 있습니다. 문제를 보다 잘 이해하고 범위를 파악할 수 있도록 아래에 나열된 정보를 가능한 한 많이 포함해 주시기 바랍니다: * 문제 유형 (예: 버퍼 오버플로우, SQL 인젝션, 크로스 사이트 스크립팅 등) * 문제와 관련된 소스 파일의 전체 경로 * 영향을 받는 소스 코드의 위치 (태그/브랜치/커밋 또는 직접 URL) * 문제를 재현하기 위해 필요한 특별한 구성 * 문제를 재현하는 단계별 설명 * 개념 증명 또는 익스플로잇 코드 (가능한 경우) * 문제의 영향, 공격자가 이를 어떻게 악용할 수 있는지 포함 이 정보는 보고서를 더 신속히 검토하는 데 도움이 됩니다. 버그 바운티 프로그램에 보고하는 경우, 더 완전한 보고서는 더 높은 보상으로 이어질 수 있습니다. 현재 진행 중인 프로그램에 대한 자세한 내용은 [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) 페이지를 방문해 주십시오. ## 선호하는 언어 모든 소통은 영어로 이루어지기를 선호합니다. ## 정책 Microsoft는 [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd) 원칙을 따릅니다. ``` **면책 조항**: 이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원본 문서의 해당 언어 버전을 신뢰할 수 있는 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/ko/SECURITY.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/SECURITY.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1939 }
# TODO: 이 저장소의 관리자가 아직 이 파일을 편집하지 않았습니다 **저장소 소유자**: 이 제품/프로젝트에 대해 고객 서비스 및 지원(CSS)을 받으시겠습니까? - **CSS 지원 없음:** 문제를 제기하고 도움을 받는 방법에 대한 정보를 포함하여 이 템플릿을 작성하세요. - **CSS 지원 있음:** [aka.ms/onboardsupport](https://aka.ms/onboardsupport)에서 접수 양식을 작성하세요. CSS가 다음 단계를 결정하는 데 도움을 주거나 지원할 것입니다. - **잘 모르겠음?** 답변이 "예"라고 가정하고 접수 양식을 작성하세요. CSS가 결정을 도와드릴 것입니다. *그런 다음 저장소를 게시하기 전에 이 SUPPORT.MD 파일에서 이 첫 번째 제목을 제거하세요.* ## 지원 ## 문제 제기 및 도움 받는 방법 이 프로젝트는 GitHub Issues를 사용하여 버그와 기능 요청을 추적합니다. 중복을 피하기 위해 새 문제를 제기하기 전에 기존 문제를 검색하세요. 새로운 문제를 제기하려면, 버그 또는 기능 요청을 새로운 Issue로 제출하세요. 이 프로젝트를 사용하는 데 대한 도움이나 질문이 있는 경우, **저장소 관리자: 도움을 받기 위해 저장소 소유자나 커뮤니티와 소통하는 방법에 대한 지침을 여기에 삽입하세요. 스택 오버플로 태그 또는 다른 채널일 수 있습니다. 어디에서 사람들을 도울 예정인가요?**. ## Microsoft 지원 정책 이 **프로젝트 또는 제품**에 대한 지원은 위에 나열된 리소스에 한정됩니다. **면책 조항**: 이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원문은 해당 언어로 작성된 문서를 신뢰할 수 있는 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/ko/SUPPORT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/SUPPORT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1037 }
# Código de Conduta de Código Aberto da Microsoft Este projeto adotou o [Código de Conduta de Código Aberto da Microsoft](https://opensource.microsoft.com/codeofconduct/). Recursos: - [Código de Conduta de Código Aberto da Microsoft](https://opensource.microsoft.com/codeofconduct/) - [Perguntas Frequentes sobre o Código de Conduta da Microsoft](https://opensource.microsoft.com/codeofconduct/faq/) - Entre em contato com [[email protected]](mailto:[email protected]) para dúvidas ou preocupações **Aviso Legal**: Este documento foi traduzido utilizando serviços de tradução baseados em IA. Embora nos esforcemos para alcançar precisão, esteja ciente de que traduções automáticas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte autoritativa. Para informações críticas, recomenda-se uma tradução humana profissional. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/pt/CODE_OF_CONDUCT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/CODE_OF_CONDUCT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1010 }
# Agentes de IA para Iniciantes - Um Curso ![IA Generativa para Iniciantes](../../translated_images/repo-thumbnail.fdd5f487bb7274d4a08459d76907ec4914de268c99637e9af082b1d3eb0730e2.pt.png?WT.mc_id=academic-105485-koreyst) ## 10 Aulas ensinando tudo o que você precisa saber para começar a construir Agentes de IA [![Licença do GitHub](https://img.shields.io/github/license/microsoft/ai-agents-for-beginners.svg)](https://github.com/microsoft/ai-agents-for-beginners/blob/master/LICENSE?WT.mc_id=academic-105485-koreyst) [![Contribuidores do GitHub](https://img.shields.io/github/contributors/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/graphs/contributors/?WT.mc_id=academic-105485-koreyst) [![Problemas no GitHub](https://img.shields.io/github/issues/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/issues/?WT.mc_id=academic-105485-koreyst) [![Pull Requests no GitHub](https://img.shields.io/github/issues-pr/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/pulls/?WT.mc_id=academic-105485-koreyst) [![PRs Bem-vindos](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com?WT.mc_id=academic-105485-koreyst) [![Observadores no GitHub](https://img.shields.io/github/watchers/microsoft/ai-agents-for-beginners.svg?style=social&label=Watch)](https://GitHub.com/microsoft/ai-agents-for-beginners/watchers/?WT.mc_id=academic-105485-koreyst) [![Forks no GitHub](https://img.shields.io/github/forks/microsoft/ai-agents-for-beginners.svg?style=social&label=Fork)](https://GitHub.com/microsoft/ai-agents-for-beginners/network/?WT.mc_id=academic-105485-koreyst) [![Estrelas no GitHub](https://img.shields.io/github/stars/microsoft/ai-agents-for-beginners.svg?style=social&label=Star)](https://GitHub.com/microsoft/ai-agents-for-beginners/stargazers/?WT.mc_id=academic-105485-koreyst) [![Azure AI Discord](https://dcbadge.limes.pink/api/server/kzRShWzttr)](https://discord.gg/kzRShWzttr) ## 🌐 Suporte a Múltiplos Idiomas | Idioma | Código | Link para README Traduzido | Última Atualização | |---------------------|--------|------------------------------------------------------|--------------------| | Chinês (Simplificado) | zh | [Tradução para Chinês](../zh/README.md) | 2025-02-13 | | Chinês (Tradicional) | tw | [Tradução para Chinês](../tw/README.md) | 2025-02-13 | | Chinês (Hong Kong) | hk | [Tradução para Chinês](../hk/README.md) | 2025-02-13 | | Francês | fr | [Tradução para Francês](../fr/README.md) | 2025-02-13 | | Japonês | ja | [Tradução para Japonês](../ja/README.md) | 2025-02-13 | | Coreano | ko | [Tradução para Coreano](../ko/README.md) | 2025-02-13 | | Português | pt | [Tradução para Português](../pt/README.md) | 2025-02-13 | | Espanhol | es | [Tradução para Espanhol](../es/README.md) | 2025-02-13 | ## 🌱 Começando Este curso contém 10 aulas cobrindo os fundamentos para construir Agentes de IA. Cada aula aborda um tópico específico, então você pode começar por onde preferir! Se esta for sua primeira vez construindo com modelos de IA Generativa, confira nosso curso [IA Generativa para Iniciantes](https://aka.ms/genai-beginners), que tem 21 aulas sobre como trabalhar com GenAI. ### Para executar o código deste curso Este curso inclui exemplos de código em cada aula que possuem uma pasta `code_samples`. Este código utiliza os seguintes serviços para Modelos: - [Github Models](https://aka.ms/ai-agents-beginners/github-models) - Gratuito / Limitado - [Azure AI Foundry](https://aka.ms/ai-agents-beginners/ai-foundry) - Requer conta Azure Este curso também utiliza os seguintes frameworks e serviços de Agentes de IA: - [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service) - [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) - [AutoGen](https://aka.ms/ai-agents/autogen) Para mais informações sobre como executar o código deste curso, acesse a página de [Configuração do Curso](./00-course-setup/README.md). Não se esqueça de [dar uma estrela (🌟) neste repositório](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars?WT.mc_id=academic-105485-koreyst) e de [fazer um fork deste repositório](https://github.com/microsoft/ai-agents-for-beginners/fork) para executar o código. ## 🙏 Quer ajudar? Tem sugestões ou encontrou erros de digitação ou no código? [Abra um problema](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst) ou [Crie um pull request](https://github.com/microsoft/ai-agents-for-beginners/pulls?WT.mc_id=academic-105485-koreyst). Se você ficar preso ou tiver dúvidas sobre como construir Agentes de IA, junte-se à nossa [Comunidade Azure AI no Discord](https://discord.gg/kzRShWzttr). ## 📂 Cada aula inclui - Uma lição escrita localizada no README (Vídeos disponíveis em março de 2025) - Exemplos de código em Python compatíveis com Azure AI Foundry e Github Models (Gratuitos) - Links para recursos adicionais para continuar seu aprendizado ## 🗃️ Aulas | **Aula** | **Link** | **Aprendizado Adicional** | |---------------------------------------|-------------------------------------------|---------------------------| | Introdução a Agentes de IA e Casos de Uso | [Introdução a Agentes de IA e Casos de Uso](./01-intro-to-ai-agents/README.md) | Saiba Mais | | Explorando Frameworks Agentes | [Explorando Frameworks Agentes](./02-explore-agentic-frameworks/README.md) | Saiba Mais | | Compreendendo Padrões de Design Agentes | [Compreendendo Padrões de Design Agentes](./03-agentic-design-patterns/README.md) | Saiba Mais | | Padrão de Design para Uso de Ferramentas | [Padrão de Design para Uso de Ferramentas](./04-tool-use/README.md) | Saiba Mais | | Agente RAG | [Agente RAG](./05-agentic-rag/README.md) | Saiba Mais | | Construindo Agentes de IA Confiáveis | [Construindo Agentes de IA Confiáveis](./06-building-trustworthy-agents/README.md) | Saiba Mais | | Padrão de Design de Planejamento | [Padrão de Design de Planejamento](./07-planning-design/README.md) | Saiba Mais | | Padrão de Design Multi-Agente | [Padrão de Design Multi-Agente](./08-multi-agent/README.md) | Saiba Mais | | Padrão de Design de Metacognição | [Padrão de Design de Metacognição](./09-metacognition/README.md) | Saiba Mais | | Agentes de IA em Produção | [Agentes de IA em Produção](./10-ai-agents-production/README.md) | Saiba Mais | ## 🎒 Outros Cursos Nossa equipe produz outros cursos! Confira: - [IA Generativa para Iniciantes](https://aka.ms/genai-beginners) - [ML para Iniciantes](https://aka.ms/ml-beginners?WT.mc_id=academic-105485-koreyst) - [Ciência de Dados para Iniciantes](https://aka.ms/datascience-beginners?WT.mc_id=academic-105485-koreyst) - [IA para Iniciantes](https://aka.ms/ai-beginners?WT.mc_id=academic-105485-koreyst) ## Contribuindo Este projeto aceita contribuições e sugestões. A maioria das contribuições exige que você concorde com um Contrato de Licença de Contribuidor (CLA) declarando que você tem o direito de, e realmente está, nos conceder os direitos para usar sua contribuição. Para mais detalhes, visite <https://cla.opensource.microsoft.com>. Quando você enviar um pull request, um bot do CLA determinará automaticamente se você precisa fornecer um CLA e marcará o PR de forma apropriada (por exemplo, verificação de status, comentário). Basta seguir as instruções fornecidas pelo bot. Você só precisará fazer isso uma vez em todos os repositórios que utilizam nosso CLA. Este projeto adotou o [Código de Conduta de Código Aberto da Microsoft](https://opensource.microsoft.com/codeofconduct/). Para mais informações, veja as [Perguntas Frequentes sobre o Código de Conduta](https://opensource.microsoft.com/codeofconduct/faq/) ou entre em contato com [[email protected]](mailto:[email protected]) para quaisquer dúvidas ou comentários adicionais. ## Marcas Registradas Este projeto pode conter marcas registradas ou logotipos de projetos, produtos ou serviços. O uso autorizado de marcas registradas ou logotipos da Microsoft está sujeito e deve seguir as [Diretrizes de Marca e Logotipo da Microsoft](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general). O uso de marcas registradas ou logotipos da Microsoft em versões modificadas deste projeto não deve causar confusão ou implicar patrocínio da Microsoft. Qualquer uso de marcas registradas ou logotipos de terceiros está sujeito às políticas desses terceiros. **Aviso Legal**: Este documento foi traduzido utilizando serviços de tradução baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se a tradução humana profissional. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/pt/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 9596 }
# Segurança A Microsoft leva a segurança de seus produtos e serviços de software muito a sério, incluindo todos os repositórios de código-fonte gerenciados por meio de nossas organizações no GitHub, que incluem [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) e [Xamarin](https://github.com/xamarin). Se você acredita ter encontrado uma vulnerabilidade de segurança em qualquer repositório pertencente à Microsoft que atenda à [definição de vulnerabilidade de segurança da Microsoft](https://aka.ms/security.md/definition), por favor, informe-nos conforme descrito abaixo. ## Relatando Problemas de Segurança **Por favor, não relate vulnerabilidades de segurança por meio de issues públicas no GitHub.** Em vez disso, relate-as ao Centro de Resposta de Segurança da Microsoft (MSRC) em [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report). Se preferir enviar sem fazer login, envie um e-mail para [[email protected]](mailto:[email protected]). Sempre que possível, criptografe sua mensagem com nossa chave PGP; faça o download na [página da Chave PGP do Centro de Resposta de Segurança da Microsoft](https://aka.ms/security.md/msrc/pgp). Você deve receber uma resposta dentro de 24 horas. Caso não receba, por algum motivo, entre em contato novamente por e-mail para garantir que recebemos sua mensagem original. Informações adicionais podem ser encontradas em [microsoft.com/msrc](https://www.microsoft.com/msrc). Inclua as informações solicitadas abaixo (na medida do possível) para nos ajudar a entender melhor a natureza e o alcance do possível problema: * Tipo de problema (ex.: buffer overflow, SQL injection, cross-site scripting, etc.) * Caminhos completos dos arquivos de origem relacionados à manifestação do problema * A localização do código-fonte afetado (tag/branch/commit ou URL direta) * Qualquer configuração especial necessária para reproduzir o problema * Instruções passo a passo para reproduzir o problema * Código de prova de conceito ou exploit (se possível) * Impacto do problema, incluindo como um invasor pode explorar o problema Essas informações nos ajudarão a priorizar sua denúncia de forma mais rápida. Se você estiver relatando como parte de um programa de recompensa por bugs, relatórios mais detalhados podem contribuir para um prêmio maior. Visite a página do [Programa de Recompensa por Bugs da Microsoft](https://aka.ms/security.md/msrc/bounty) para mais detalhes sobre nossos programas ativos. ## Idiomas Preferenciais Preferimos que todas as comunicações sejam feitas em inglês. ## Política A Microsoft segue o princípio de [Divulgação Coordenada de Vulnerabilidades](https://aka.ms/security.md/cvd). **Aviso Legal**: Este documento foi traduzido utilizando serviços de tradução baseados em IA. Embora nos esforcemos para alcançar precisão, esteja ciente de que traduções automáticas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte autoritativa. Para informações críticas, recomenda-se a tradução profissional humana. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/pt/SECURITY.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/SECURITY.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 3297 }
# TODO: O mantenedor deste repositório ainda não editou este arquivo **PROPRIETÁRIO DO REPO**: Você deseja suporte do Customer Service & Support (CSS) para este produto/projeto? - **Sem suporte do CSS:** Preencha este modelo com informações sobre como registrar problemas e obter ajuda. - **Com suporte do CSS:** Preencha um formulário de entrada em [aka.ms/onboardsupport](https://aka.ms/onboardsupport). O CSS trabalhará com você/ajudará a determinar os próximos passos. - **Não tem certeza?** Preencha um formulário de entrada como se a resposta fosse "Sim". O CSS ajudará você a decidir. *Depois, remova este primeiro cabeçalho deste arquivo SUPPORT.MD antes de publicar seu repositório.* ## Suporte ## Como registrar problemas e obter ajuda Este projeto utiliza o GitHub Issues para rastrear bugs e solicitações de funcionalidades. Por favor, pesquise os problemas existentes antes de registrar novos problemas para evitar duplicidades. Para novos problemas, registre seu bug ou solicitação de funcionalidade como um novo Issue. Para obter ajuda e esclarecer dúvidas sobre como usar este projeto, por favor **MANTENEDOR DO REPO: INSIRA INSTRUÇÕES AQUI SOBRE COMO OS PROPRIETÁRIOS DO REPO OU A COMUNIDADE PODEM AJUDAR. PODERIA SER UMA TAG NO STACK OVERFLOW OU OUTRO CANAL. ONDE VOCÊ AJUDARÁ AS PESSOAS?**. ## Política de Suporte da Microsoft O suporte para este **PROJETO ou PRODUTO** é limitado aos recursos listados acima. **Aviso Legal**: Este documento foi traduzido utilizando serviços de tradução baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se a tradução profissional feita por humanos. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/pt/SUPPORT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/SUPPORT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1949 }
# 微軟開源行為準則 此專案採用了 [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)(微軟開源行為準則)。 相關資源: - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) - 如有任何問題或疑慮,請聯繫 [[email protected]](mailto:[email protected]) **免責聲明**: 本文件使用基於機器的人工智能翻譯服務進行翻譯。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文作為權威來源。對於關鍵信息,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或錯誤解釋概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/tw/CODE_OF_CONDUCT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/CODE_OF_CONDUCT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 520 }
# 初學者的 AI Agents 課程 ![Generative AI For Beginners](../../translated_images/repo-thumbnail.fdd5f487bb7274d4a08459d76907ec4914de268c99637e9af082b1d3eb0730e2.tw.png?WT.mc_id=academic-105485-koreyst) ## 10 堂課教你從零開始建立 AI Agents 所需的一切 [![GitHub license](https://img.shields.io/github/license/microsoft/ai-agents-for-beginners.svg)](https://github.com/microsoft/ai-agents-for-beginners/blob/master/LICENSE?WT.mc_id=academic-105485-koreyst) [![GitHub contributors](https://img.shields.io/github/contributors/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/graphs/contributors/?WT.mc_id=academic-105485-koreyst) [![GitHub issues](https://img.shields.io/github/issues/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/issues/?WT.mc_id=academic-105485-koreyst) [![GitHub pull-requests](https://img.shields.io/github/issues-pr/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/pulls/?WT.mc_id=academic-105485-koreyst) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com?WT.mc_id=academic-105485-koreyst) [![GitHub watchers](https://img.shields.io/github/watchers/microsoft/ai-agents-for-beginners.svg?style=social&label=Watch)](https://GitHub.com/microsoft/ai-agents-for-beginners/watchers/?WT.mc_id=academic-105485-koreyst) [![GitHub forks](https://img.shields.io/github/forks/microsoft/ai-agents-for-beginners.svg?style=social&label=Fork)](https://GitHub.com/microsoft/ai-agents-for-beginners/network/?WT.mc_id=academic-105485-koreyst) [![GitHub stars](https://img.shields.io/github/stars/microsoft/ai-agents-for-beginners.svg?style=social&label=Star)](https://GitHub.com/microsoft/ai-agents-for-beginners/stargazers/?WT.mc_id=academic-105485-koreyst) [![Azure AI Discord](https://dcbadge.limes.pink/api/server/kzRShWzttr)](https://discord.gg/kzRShWzttr) ## 🌐 多語言支援 | 語言 | 代碼 | 已翻譯的 README 連結 | 最後更新日期 | |-----------------------|------|-----------------------------------------------------|--------------| | 簡體中文 | zh | [Chinese Translation](../zh/README.md) | 2025-02-13 | | 繁體中文 | tw | [Chinese Translation](./README.md) | 2025-02-13 | | 法文 | fr | [French Translation](../fr/README.md) | 2025-02-13 | | 日文 | ja | [Japanese Translation](../ja/README.md) | 2025-02-13 | | 韓文 | ko | [Korean Translation](../ko/README.md) | 2025-02-13 | | 西班牙文 | es | [Spanish Translation](../es/README.md) | 2025-02-13 | > **注意:** > 這些翻譯是使用開源工具 [co-op-translator](https://github.com/Azure/co-op-translator) 自動生成的,可能包含錯誤或不準確之處。如需重要資訊,請參考原文或尋求專業人工翻譯。如果您希望貢獻或更新翻譯,請訪問此儲存庫,您可以使用簡單的指令輕鬆進行貢獻。 ## 🌱 快速開始 本課程包含 10 堂課,涵蓋建立 AI Agents 的基礎知識。每堂課探討不同的主題,您可以自由選擇從任何地方開始! 如果您是第一次接觸生成式 AI 模型,建議先參考我們的 [Generative AI For Beginners](https://aka.ms/genai-beginners) 課程,該課程包含 21 堂課,專注於使用生成式 AI 建構專案。 ### 如何執行本課程的程式碼 本課程的每堂課都有一個包含程式碼範例的 `code_samples` 資料夾。這些程式碼使用以下模型服務: - [Github Models](https://aka.ms/ai-agents-beginners/github-models) - 免費 / 有限功能 - [Azure AI Foundry](https://aka.ms/ai-agents-beginners/ai-foundry) - 需 Azure 帳戶 本課程也使用以下 AI Agent 框架與服務: - [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service) - [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) - [AutoGen](https://aka.ms/ai-agents/autogen) 如需更多有關執行本課程程式碼的資訊,請參考 [課程設定](./00-course-setup/README.md)。 別忘了 [收藏 (🌟) 這個儲存庫](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars?WT.mc_id=academic-105485-koreyst) 並 [分叉 (fork) 這個儲存庫](https://github.com/microsoft/ai-agents-for-beginners/fork) 來執行程式碼。 ## 🙏 想要幫忙嗎? 有任何建議或發現拼寫或程式碼錯誤?[提出問題](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst) 或 [建立拉取請求](https://github.com/microsoft/ai-agents-for-beginners/pulls?WT.mc_id=academic-105485-koreyst)。 如果您遇到問題或有關於建立 AI Agents 的任何疑問,歡迎加入我們的 [Azure AI 社群 Discord](https://discord.gg/kzRShWzttr)。 ## 📂 每堂課內容包含 - 一份書面課程,位於 README 中(影片將於 2025 年 3 月推出) - 支援 Azure AI Foundry 和 Github Models(免費)的 Python 程式碼範例 - 延伸學習資源的連結 ## 🗃️ 課程清單 | **課程** | **連結** | **延伸學習** | |--------------------------------------|--------------------------------------------|------------------| | AI Agents 與應用場景介紹 | [Intro to AI Agents and Use Cases](./01-intro-to-ai-agents/README.md) | 繼續學習 | | 探索 Agentic 框架 | [Exploring Agentic Frameworks](./02-explore-agentic-frameworks/README.md) | 了解更多 | | 理解 Agentic 設計模式 | [Understanding Agentic Design Patterns](./03-agentic-design-patterns/README.md) | 了解更多 | | 工具使用設計模式 | [Tool Use Design Pattern](./04-tool-use/README.md) | 了解更多 | | Agentic RAG | [Agentic RAG](./05-agentic-rag/README.md) | 了解更多 | | 建立值得信賴的 AI Agent | [Building Trustworthy AI Agents](./06-building-trustworthy-agents/README.md) | 了解更多 | | 規劃設計模式 | [Planning Design Pattern](./07-planning-design/README.md) | 了解更多 | | 多代理設計模式 | [Muilt-Agent Design Pattern](./08-multi-agent/README.md) | 了解更多 | | 後設認知設計模式 | [Metacognition Design Pattern](./09-metacognition/README.md) | 了解更多 | | 生產環境中的 AI Agent | [AI Agents in Production](./10-ai-agents-production/README.md) | 了解更多 | ## 🎒 其他課程 我們的團隊還製作了其他課程!看看以下內容: - [Generative AI for Beginners](https://aka.ms/genai-beginners) - [ML for Beginners](https://aka.ms/ml-beginners?WT.mc_id=academic-105485-koreyst) - [Data Science for Beginners](https://aka.ms/datascience-beginners?WT.mc_id=academic-105485-koreyst) - [AI for Beginners](https://aka.ms/ai-beginners?WT.mc_id=academic-105485-koreyst) ## 貢獻指南 我們歡迎任何貢獻與建議。大多數貢獻需要您同意一份貢獻者授權協議 (CLA),聲明您擁有授權我們使用您貢獻的權利,並且您確實授予了我們這樣的權利。詳情請參考 <https://cla.opensource.microsoft.com>。 當您提交 Pull Request 時,CLA 機器人會自動判斷您是否需要提供 CLA 並適當標註 PR(例如,狀態檢查、評論)。只需按照機器人的指示操作即可。您只需要在所有使用我們 CLA 的 repo 中執行一次這個操作。 此專案已採用 [Microsoft 開源行為準則](https://opensource.microsoft.com/codeofconduct/)。如需更多資訊,請參閱 [行為準則 FAQ](https://opensource.microsoft.com/codeofconduct/faq/),或聯繫 [[email protected]](mailto:[email protected]) 提出任何其他問題或意見。 ## 商標 此專案可能包含專案、產品或服務的商標或標誌。經授權使用 Microsoft 商標或標誌需遵循 [Microsoft 的商標與品牌指南](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general)。修改版專案中使用 Microsoft 商標或標誌不得引起混淆或暗示 Microsoft 的贊助。任何第三方商標或標誌的使用則需遵守該第三方的政策。 **免責聲明**: 本文檔是使用基於機器的人工智能翻譯服務翻譯的。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件作為權威來源。對於關鍵信息,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或誤讀概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/tw/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 7002 }
# 安全性 Microsoft 非常重視我們軟體產品與服務的安全性,這也包括透過我們 GitHub 組織管理的所有原始碼庫,例如 [Microsoft](https://github.com/Microsoft)、[Azure](https://github.com/Azure)、[DotNet](https://github.com/dotnet)、[AspNet](https://github.com/aspnet) 和 [Xamarin](https://github.com/xamarin)。 如果您認為在任何 Microsoft 擁有的儲存庫中發現了符合 [Microsoft 的安全性漏洞定義](https://aka.ms/security.md/definition) 的安全性漏洞,請按照以下說明向我們回報。 ## 回報安全性問題 **請勿透過公開的 GitHub 問題回報安全性漏洞。** 請改為透過 Microsoft Security Response Center (MSRC) 提交回報:[https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report)。 如果您希望在不登入的情況下提交,請發送電子郵件至 [[email protected]](mailto:[email protected])。如果可能,請使用我們的 PGP 金鑰加密您的訊息;您可以從 [Microsoft Security Response Center PGP Key 頁面](https://aka.ms/security.md/msrc/pgp) 下載。 您應該會在 24 小時內收到回應。如果因某些原因未收到回應,請透過電子郵件再次跟進,以確保我們收到您的原始訊息。更多資訊請參閱 [microsoft.com/msrc](https://www.microsoft.com/msrc)。 請盡量提供以下所列的相關資訊(能提供越多越好),以幫助我們更好地理解問題的性質和範圍: * 問題類型(例如:緩衝區溢位、SQL 注入、跨站腳本攻擊等) * 與問題相關的原始檔案完整路徑 * 受影響原始碼的位置(標籤/分支/提交或直接 URL) * 重現問題所需的任何特殊配置 * 重現問題的逐步指導 * 概念驗證或攻擊程式碼(如果可能) * 問題的影響,包括攻擊者可能如何利用該問題 這些資訊將幫助我們更快速地分類您的回報。 如果您是為了漏洞賞金計畫進行回報,提供更完整的報告可能會有助於獲得更高的獎勵。更多詳細資訊請參閱我們的 [Microsoft 漏洞賞金計畫](https://aka.ms/security.md/msrc/bounty) 頁面。 ## 優先語言 我們希望所有的溝通能以英文進行。 ## 政策 Microsoft 遵循 [協調式漏洞揭露](https://aka.ms/security.md/cvd) 原則。 **免責聲明**: 本文件已使用基於人工智能的機器翻譯服務進行翻譯。我們雖然致力於追求準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文語言的原始文件作為權威來源。對於關鍵信息,建議尋求專業人工翻譯。我們對因使用本翻譯而產生的任何誤解或錯誤解讀概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/tw/SECURITY.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/SECURITY.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1473 }
# TODO: 此存放庫的維護者尚未編輯此檔案 **存放庫擁有者**:您希望為此產品/專案提供客戶服務與支援 (CSS) 嗎? - **不需要 CSS 支援**:請填寫此範本,提供關於如何提交問題和獲取幫助的資訊。 - **需要 CSS 支援**:請填寫 [aka.ms/onboardsupport](https://aka.ms/onboardsupport) 上的申請表。CSS 將與您合作,協助確定後續步驟。 - **不確定?** 請像回答「是」一樣填寫申請表。CSS 將協助您進行決策。 *在發佈您的存放庫之前,請從此 SUPPORT.MD 檔案中移除此第一個標題。* ## 支援 ## 如何提交問題與獲取幫助 此專案使用 GitHub Issues 來追蹤錯誤和功能需求。請在提交新問題之前,先搜尋現有的問題,以避免重複。對於新問題,請將您的錯誤或功能需求作為新 Issue 提交。 如果您需要幫助或對使用此專案有任何疑問,請 **存放庫維護者:在此插入指導用戶如何聯繫存放庫擁有者或社群的說明。可以是 Stack Overflow 的標籤或其他管道。您會在哪裡協助用戶?**。 ## Microsoft 支援政策 對此 **專案或產品** 的支援僅限於上面列出的資源。 **免責聲明**: 本文件使用機器翻譯服務進行翻譯。我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件作為權威來源。對於關鍵資訊,建議尋求專業的人工作翻譯。我們對於使用此翻譯而引起的任何誤解或誤讀概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/tw/SUPPORT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/SUPPORT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 703 }
# 微软开源行为准则 本项目已采用 [Microsoft 开源行为准则](https://opensource.microsoft.com/codeofconduct/)。 资源: - [Microsoft 开源行为准则](https://opensource.microsoft.com/codeofconduct/) - [Microsoft 行为准则常见问题](https://opensource.microsoft.com/codeofconduct/faq/) - 如果有任何问题或疑虑,请联系 [[email protected]](mailto:[email protected]) **免责声明**: 本文件通过基于机器的人工智能翻译服务进行翻译。尽管我们努力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的文件作为权威来源。对于关键信息,建议寻求专业人工翻译服务。因使用此翻译而导致的任何误解或误读,我们概不负责。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/zh/CODE_OF_CONDUCT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/CODE_OF_CONDUCT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 455 }
# 初学者的 AI 代理课程 ![生成式 AI 入门](../../translated_images/repo-thumbnail.fdd5f487bb7274d4a08459d76907ec4914de268c99637e9af082b1d3eb0730e2.zh.png?WT.mc_id=academic-105485-koreyst) ## 10 节课程,教您从零开始构建 AI 代理的一切知识 [![GitHub license](https://img.shields.io/github/license/microsoft/ai-agents-for-beginners.svg)](https://github.com/microsoft/ai-agents-for-beginners/blob/master/LICENSE?WT.mc_id=academic-105485-koreyst) [![GitHub contributors](https://img.shields.io/github/contributors/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/graphs/contributors/?WT.mc_id=academic-105485-koreyst) [![GitHub issues](https://img.shields.io/github/issues/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/issues/?WT.mc_id=academic-105485-koreyst) [![GitHub pull-requests](https://img.shields.io/github/issues-pr/microsoft/ai-agents-for-beginners.svg)](https://GitHub.com/microsoft/ai-agents-for-beginners/pulls/?WT.mc_id=academic-105485-koreyst) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com?WT.mc_id=academic-105485-koreyst) [![GitHub watchers](https://img.shields.io/github/watchers/microsoft/ai-agents-for-beginners.svg?style=social&label=Watch)](https://GitHub.com/microsoft/ai-agents-for-beginners/watchers/?WT.mc_id=academic-105485-koreyst) [![GitHub forks](https://img.shields.io/github/forks/microsoft/ai-agents-for-beginners.svg?style=social&label=Fork)](https://GitHub.com/microsoft/ai-agents-for-beginners/network/?WT.mc_id=academic-105485-koreyst) [![GitHub stars](https://img.shields.io/github/stars/microsoft/ai-agents-for-beginners.svg?style=social&label=Star)](https://GitHub.com/microsoft/ai-agents-for-beginners/stargazers/?WT.mc_id=academic-105485-koreyst) [![Azure AI Discord](https://dcbadge.limes.pink/api/server/kzRShWzttr)](https://discord.gg/kzRShWzttr) ## 🌐 多语言支持 | 语言 | 代码 | 翻译后的 README 链接 | 最后更新日期 | |----------------------|------|-----------------------------------------------------|--------------------| | 简体中文 | zh | [中文翻译](./README.md) | 2025-02-13 | | 繁体中文 | tw | [中文翻译](../tw/README.md) | 2025-02-13 | | 法语 | fr | [法语翻译](../fr/README.md) | 2025-02-13 | | 日语 | ja | [日语翻译](../ja/README.md) | 2025-02-13 | | 韩语 | ko | [韩语翻译](../ko/README.md) | 2025-02-13 | | 西班牙语 | es | [西班牙语翻译](../es/README.md) | 2025-02-13 | > **注意:** > 这些翻译是使用开源工具 [co-op-translator](https://github.com/Azure/co-op-translator) 自动生成的,可能存在错误或不准确之处。对于重要信息,请参考原文或寻求专业人工翻译。如果您想贡献或更新翻译,请访问该仓库,您可以通过简单的命令轻松进行贡献。 ## 🌱 快速开始 本课程包含 10 节课,涵盖构建 AI 代理的基础知识。每节课都专注于一个独立主题,因此您可以从任何感兴趣的地方开始! 如果这是您第一次使用生成式 AI 模型进行构建,请查看我们的 [生成式 AI 入门课程](https://aka.ms/genai-beginners),该课程包含 21 节课,讲解如何使用生成式 AI。 ### 如何运行本课程的代码 本课程在每节课中提供了包含 `code_samples` 文件夹的代码示例。这些代码使用以下模型服务: - [Github Models](https://aka.ms/ai-agents-beginners/github-models) - 免费 / 有限 - [Azure AI Foundry](https://aka.ms/ai-agents-beginners/ai-foundry) - 需要 Azure 账号 此外,本课程还使用以下 AI 代理框架和服务: - [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service) - [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) - [AutoGen](https://aka.ms/ai-agents/autogen) 有关运行本课程代码的更多信息,请参阅 [课程设置](./00-course-setup/README.md)。 别忘了 [给这个仓库点星 (🌟)](https://docs.github.com/en/get-started/exploring-projects-on-github/saving-repositories-with-stars?WT.mc_id=academic-105485-koreyst) 和 [fork 这个仓库](https://github.com/microsoft/ai-agents-for-beginners/fork) 来运行代码。 ## 🙏 想要贡献? 您有建议或发现拼写或代码错误吗?请[提交问题](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst)或[创建拉取请求](https://github.com/microsoft/ai-agents-for-beginners/pulls?WT.mc_id=academic-105485-koreyst)。 如果您遇到困难或对构建 AI 代理有任何疑问,请加入我们的 [Azure AI 社区 Discord](https://discord.gg/kzRShWzttr)。 ## 📂 每节课包括 - 写在 README 中的课程内容(视频将于 2025 年 3 月上线) - 支持 Azure AI Foundry 和 Github Models(免费)的 Python 代码示例 - 指向额外学习资源的链接,帮助您继续学习 ## 🗃️ 课程目录 | **课程** | **链接** | **额外学习资源** | |-------------------------------------|------------------------------------------|--------------------| | AI 代理简介及应用场景 | [AI 代理简介及应用场景](./01-intro-to-ai-agents/README.md) | 了解更多 | | 探索 Agentic 框架 | [Exploring Agentic Frameworks](./02-explore-agentic-frameworks/README.md) | 了解更多 | | 理解 Agentic 设计模式 | [Understanding Agentic Design Patterns](./03-agentic-design-patterns/README.md) | 了解更多 | | 工具使用设计模式 | [Tool Use Design Pattern](./04-tool-use/README.md) | 了解更多 | | Agentic RAG | [Agentic RAG](./05-agentic-rag/README.md) | 了解更多 | | 构建可信赖的 AI 代理 | [Building Trustworthy AI Agents](./06-building-trustworthy-agents/README.md) | 了解更多 | | 规划设计模式 | [Planning Design Pattern](./07-planning-design/README.md) | 了解更多 | | 多代理设计模式 | [Muilt-Agent Design Pattern](./08-multi-agent/README.md) | 了解更多 | | 元认知设计模式 | [Metacognition Design Pattern](./09-metacognition/README.md) | 了解更多 | | 生产环境中的 AI 代理 | [AI Agents in Production](./10-ai-agents-production/README.md) | 了解更多 | ## 🎒 其他课程 我们的团队还制作了其他课程!欢迎查看: - [Generative AI for Beginners](https://aka.ms/genai-beginners) - [ML for Beginners](https://aka.ms/ml-beginners?WT.mc_id=academic-105485-koreyst) - [Data Science for Beginners](https://aka.ms/datascience-beginners?WT.mc_id=academic-105485-koreyst) - [AI for Beginners](https://aka.ms/ai-beginners?WT.mc_id=academic-105485-koreyst) ## 贡献指南 本项目欢迎贡献和建议。大多数贡献需要您同意一份贡献者许可协议 (CLA),声明您有权并实际授予我们使用您贡献的权利。详情请访问 <https://cla.opensource.microsoft.com>。 当您提交一个 pull request 时,CLA 机器人会自动判断您是否需要提供 CLA,并相应地标记 PR(例如状态检查、评论)。只需按照机器人提供的指示操作即可。您只需在所有使用我们 CLA 的仓库中执行一次此操作。 本项目采用了 [Microsoft 开源行为准则](https://opensource.microsoft.com/codeofconduct/)。 如需更多信息,请参阅 [行为准则 FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 或通过 [[email protected]](mailto:[email protected]) 联系我们提出其他问题或评论。 ## 商标声明 本项目可能包含项目、产品或服务的商标或徽标。使用 Microsoft 商标或徽标需获得授权,并必须遵循 [Microsoft 的商标和品牌指南](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general)。 在修改版本的项目中使用 Microsoft 商标或徽标不得引起混淆或暗示 Microsoft 的赞助。 任何对第三方商标或徽标的使用均需遵守该第三方的政策。 **免责声明**: 本文档通过基于机器的AI翻译服务翻译而成。尽管我们努力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的文档作为权威来源。对于关键信息,建议寻求专业人工翻译。因使用本翻译而引起的任何误解或误读,我们概不负责。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/zh/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 6893 }
# 安全性 Microsoft 非常重视我们软件产品和服务的安全性,这包括通过我们的 GitHub 组织管理的所有源代码库,这些组织包括 [Microsoft](https://github.com/Microsoft)、[Azure](https://github.com/Azure)、[DotNet](https://github.com/dotnet)、[AspNet](https://github.com/aspnet) 和 [Xamarin](https://github.com/xamarin)。 如果您认为在任何 Microsoft 拥有的代码库中发现了安全漏洞,并且该漏洞符合 [Microsoft 对安全漏洞的定义](https://aka.ms/security.md/definition),请按照以下说明向我们报告。 ## 报告安全问题 **请不要通过公开的 GitHub 问题报告安全漏洞。** 请通过 Microsoft 安全响应中心 (MSRC) 报告安全问题,访问 [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report)。 如果您希望在不登录的情况下提交报告,可以发送电子邮件至 [[email protected]](mailto:[email protected])。 如果可能,请使用我们的 PGP 密钥加密您的消息;您可以从 [Microsoft 安全响应中心 PGP 密钥页面](https://aka.ms/security.md/msrc/pgp) 下载。 您应该会在 24 小时内收到回复。如果由于某种原因未收到,请通过电子邮件进行跟进,以确保我们收到了您的原始消息。更多信息可在 [microsoft.com/msrc](https://www.microsoft.com/msrc) 查阅。 请尽可能提供以下所需信息,以帮助我们更好地理解可能问题的性质和范围: * 问题类型(例如,缓冲区溢出、SQL 注入、跨站脚本攻击等) * 与问题表现相关的源文件的完整路径 * 受影响源代码的位置(标签/分支/提交或直接 URL) * 重现问题所需的任何特殊配置 * 重现问题的逐步说明 * 概念验证代码或漏洞利用代码(如果可能) * 问题的影响,包括攻击者可能如何利用该问题 这些信息将帮助我们更快速地对您的报告进行分类和处理。 如果您是为漏洞奖励计划报告问题,更完整的报告可能会获得更高的奖励金额。有关我们当前活动计划的更多详细信息,请访问 [Microsoft 漏洞奖励计划](https://aka.ms/security.md/msrc/bounty) 页面。 ## 优先语言 我们优先使用英语进行所有交流。 ## 政策 Microsoft 遵循 [协调漏洞披露](https://aka.ms/security.md/cvd) 原则。 **免责声明**: 本文件使用基于机器的人工智能翻译服务进行翻译。尽管我们尽力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。原始语言的文件应被视为权威来源。对于关键信息,建议寻求专业人工翻译。对于因使用本翻译而导致的任何误解或误读,我们概不负责。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/zh/SECURITY.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/SECURITY.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1451 }
# 待办事项:此仓库的维护者尚未编辑此文件 **仓库所有者**:您是否希望为此产品/项目提供客户服务与支持 (CSS)? - **不需要 CSS 支持**:请使用本模板填写有关如何提交问题和获取帮助的信息。 - **需要 CSS 支持**:请填写 [aka.ms/onboardsupport](https://aka.ms/onboardsupport) 上的接收表单。CSS 将与您合作/帮助您确定下一步行动。 - **不确定?** 请按照“需要”填写接收表单。CSS 将帮助您做出决定。 *然后在发布您的仓库之前,从这个 SUPPORT.MD 文件中删除这一部分标题。* ## 支持 ## 如何提交问题并获取帮助 此项目使用 GitHub Issues 来跟踪漏洞和功能请求。在提交新问题之前,请先搜索现有问题以避免重复。对于新问题,请将您的漏洞或功能请求作为一个新 Issue 提交。 如果您需要帮助或对使用此项目有疑问,请 **仓库维护者:在此插入与仓库所有者或社区联系以获取帮助的说明。可以是 Stack Overflow 标签或其他渠道。您会在哪里为人们提供帮助?**。 ## Microsoft 支持政策 对于此 **项目或产品** 的支持仅限于上述列出的资源。 **免责声明**: 本文件使用基于机器的人工智能翻译服务进行翻译。尽管我们努力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的原始文件为权威来源。对于关键信息,建议使用专业人工翻译。因使用本翻译而引起的任何误解或误读,我们概不负责。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/zh/SUPPORT.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/SUPPORT.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 706 }
--- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. iOS] - Browser [e.g. chrome, safari] - Version [e.g. 22] **Smartphone (please complete the following information):** - Device: [e.g. iPhone6] - OS: [e.g. iOS8.1] - Browser [e.g. stock browser, safari] - Version [e.g. 22] **Additional context** Add any other context about the problem here.
{ "source": "microsoft/ai-agents-for-beginners", "title": ".github/workflows/ISSUE_TEMPLATE/bug_report.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/.github/workflows/ISSUE_TEMPLATE/bug_report.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 833 }
```markdown # Kurseinrichtung ## Einführung In dieser Lektion wird erklärt, wie die Codebeispiele dieses Kurses ausgeführt werden können. ## Anforderungen - Ein GitHub-Konto - Python 3.12+ ## Dieses Repository klonen oder forken Um zu beginnen, klonen oder forken Sie bitte das GitHub-Repository. Dadurch erstellen Sie Ihre eigene Version des Kursmaterials, sodass Sie den Code ausführen, testen und anpassen können! Dies können Sie tun, indem Sie auf den Link [fork the repo](https://github.com/microsoft/ai-agents-for-beginners/fork) klicken. Sie sollten nun Ihre eigene geforkte Version dieses Kurses haben, wie unten gezeigt: ![Geforktes Repository](../../../translated_images/forked-repo.eea246a73044cc984a1e462349e36e7336204f00785e3187b7399905feeada07.de.png) ## Abrufen Ihres GitHub Personal Access Token (PAT) Dieser Kurs verwendet derzeit den GitHub Models Marketplace, um kostenlosen Zugriff auf Large Language Models (LLMs) bereitzustellen, die zur Erstellung von KI-Agenten verwendet werden. Um auf diesen Service zuzugreifen, müssen Sie ein GitHub Personal Access Token erstellen. Dies können Sie tun, indem Sie zu Ihren [Personal Access Tokens settings](https://github.com/settings/personal-access-tokens) in Ihrem GitHub-Konto gehen. Wählen Sie die `Fine-grained tokens`-Optionen auf der linken Seite Ihres Bildschirms. Wählen Sie anschließend `Generate new token`. ![Token generieren](../../../translated_images/generate-token.361ec40abe59b84ac68d63c23e2b6854d6fad82bd4e41feb98fc0e6f030e8ef7.de.png) Kopieren Sie Ihren neu erstellten Token. Sie werden diesen nun in Ihre `.env`-Datei einfügen, die in diesem Kurs enthalten ist. ## Hinzufügen zu Ihren Umgebungsvariablen Um Ihre `.env`-Datei zu erstellen, führen Sie den folgenden Befehl in Ihrem Terminal aus: ```bash cp .env.example .env ``` Dieser Befehl kopiert die Beispieldatei und erstellt eine `.env`-Datei in Ihrem Verzeichnis. Öffnen Sie diese Datei und fügen Sie den erstellten Token in das Feld `GITHUB_TOKEN=` der .env-Datei ein. ## Erforderliche Pakete installieren Um sicherzustellen, dass Sie alle erforderlichen Python-Pakete für die Ausführung des Codes haben, führen Sie den folgenden Befehl in Ihrem Terminal aus. Wir empfehlen, eine Python-virtuelle Umgebung zu erstellen, um Konflikte und Probleme zu vermeiden. ```bash pip install -r requirements.txt ``` Dies sollte die benötigten Python-Pakete installieren. Sie sind nun bereit, den Code dieses Kurses auszuführen. Viel Spaß beim Erforschen der Welt der KI-Agenten! Falls Sie Probleme bei der Einrichtung haben, treten Sie unserem [Azure AI Community Discord](https://discord.gg/kzRShWzttr) bei oder [erstellen Sie ein Issue](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst). ``` **Haftungsausschluss**: Dieses Dokument wurde mit KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir haften nicht für Missverständnisse oder Fehlinterpretationen, die aus der Nutzung dieser Übersetzung entstehen.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/00-course-setup/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/00-course-setup/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 3356 }
# Einführung in KI-Agenten und deren Anwendungsfälle Willkommen zum Kurs "KI-Agenten für Anfänger"! Dieser Kurs vermittelt Ihnen grundlegendes Wissen und praktische Beispiele für die Arbeit mit KI-Agenten. Treten Sie der [Azure AI Discord Community](https://discord.gg/kzRShWzttr) bei, um andere Lernende und Entwickler von KI-Agenten kennenzulernen und alle Fragen zu diesem Kurs zu stellen. Zu Beginn des Kurses verschaffen wir uns zunächst ein besseres Verständnis darüber, was KI-Agenten sind und wie wir sie in den Anwendungen und Arbeitsabläufen, die wir entwickeln, einsetzen können. ## Einführung Diese Lektion behandelt: - Was sind KI-Agenten und welche Arten von Agenten gibt es? - Für welche Anwendungsfälle eignen sich KI-Agenten besonders, und wie können sie uns helfen? - Was sind die grundlegenden Bausteine beim Entwerfen agentenbasierter Lösungen? ## Lernziele Nach Abschluss dieser Lektion sollten Sie in der Lage sein: - Die Konzepte von KI-Agenten zu verstehen und zu erkennen, wie sie sich von anderen KI-Lösungen unterscheiden. - KI-Agenten effizient einzusetzen. - Agentenbasierte Lösungen produktiv für Benutzer und Kunden zu entwerfen. ## Definition von KI-Agenten und Typen von KI-Agenten ### Was sind KI-Agenten? KI-Agenten sind **Systeme**, die es **Großen Sprachmodellen (LLMs)** ermöglichen, **Aktionen auszuführen**, indem sie deren Fähigkeiten erweitern und ihnen **Zugang zu Werkzeugen** und **Wissen** geben. Lassen Sie uns diese Definition in kleinere Teile zerlegen: - **System** – Es ist wichtig, Agenten nicht nur als eine einzelne Komponente zu betrachten, sondern als ein System aus vielen Komponenten. Auf der grundlegenden Ebene bestehen die Komponenten eines KI-Agenten aus: - **Umgebung** – Der definierte Raum, in dem der KI-Agent arbeitet. Zum Beispiel könnte die Umgebung eines Reisebuchungs-Agenten das Buchungssystem sein, das der Agent verwendet, um Aufgaben zu erledigen. - **Sensoren** – Umgebungen enthalten Informationen und geben Rückmeldungen. KI-Agenten nutzen Sensoren, um diese Informationen über den aktuellen Zustand der Umgebung zu sammeln und zu interpretieren. Im Beispiel des Reisebuchungs-Agenten könnte das Buchungssystem Informationen wie Hotelverfügbarkeit oder Flugpreise liefern. - **Aktuatoren** – Sobald der KI-Agent den aktuellen Zustand der Umgebung erhält, entscheidet er, welche Aktion für die jeweilige Aufgabe ausgeführt werden soll, um die Umgebung zu verändern. Im Fall des Reisebuchungs-Agenten könnte dies bedeuten, ein verfügbares Zimmer für den Benutzer zu buchen. ![Was sind KI-Agenten?](../../../translated_images/what-are-ai-agents.125520f55950b252a429b04a9f41e0152d4dafa1f1bd9081f4f574631acb759e.de.png?WT.mc_id=academic-105485-koreyst) **Große Sprachmodelle** – Das Konzept von Agenten existierte bereits vor der Entwicklung von LLMs. Der Vorteil beim Aufbau von KI-Agenten mit LLMs liegt in ihrer Fähigkeit, menschliche Sprache und Daten zu interpretieren. Diese Fähigkeit ermöglicht es LLMs, Umgebungsinformationen zu verstehen und einen Plan zur Veränderung der Umgebung zu definieren. **Aktionen ausführen** – Außerhalb von KI-Agenten-Systemen sind LLMs darauf beschränkt, Inhalte oder Informationen basierend auf einer Benutzereingabe zu generieren. Innerhalb von KI-Agenten-Systemen können LLMs Aufgaben ausführen, indem sie die Anfrage des Benutzers interpretieren und die in ihrer Umgebung verfügbaren Werkzeuge nutzen. **Zugang zu Werkzeugen** – Welche Werkzeuge dem LLM zur Verfügung stehen, wird durch 1) die Umgebung, in der es arbeitet, und 2) den Entwickler des KI-Agenten definiert. Im Beispiel des Reisebuchungs-Agenten sind die Werkzeuge des Agenten durch die im Buchungssystem verfügbaren Operationen begrenzt, oder der Entwickler kann den Zugriff des Agenten auf bestimmte Werkzeuge wie Flüge beschränken. **Wissen** – Neben den Informationen, die von der Umgebung bereitgestellt werden, können KI-Agenten auch Wissen aus anderen Systemen, Diensten, Werkzeugen und sogar anderen Agenten abrufen. Im Beispiel des Reisebuchungs-Agenten könnte dieses Wissen Informationen über die Reisevorlieben des Benutzers aus einer Kundendatenbank umfassen. ### Die verschiedenen Arten von Agenten Nachdem wir eine allgemeine Definition von KI-Agenten haben, betrachten wir nun einige spezifische Agententypen und wie sie auf einen Reisebuchungs-Agenten angewendet werden könnten. | **Agententyp** | **Beschreibung** | **Beispiel** | | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Einfache Reflex-Agenten** | Führen sofortige Aktionen basierend auf vordefinierten Regeln aus. | Der Reiseagent interpretiert den Kontext einer E-Mail und leitet Beschwerden über Reisen an den Kundenservice weiter. | | **Modellbasierte Reflex-Agenten** | Führen Aktionen basierend auf einem Modell der Welt und dessen Veränderungen aus. | Der Reiseagent priorisiert Routen mit signifikanten Preisänderungen, basierend auf Zugriff auf historische Preisdaten. | | **Zielorientierte Agenten** | Erstellen Pläne, um bestimmte Ziele zu erreichen, indem sie das Ziel interpretieren und Aktionen bestimmen, um es zu erreichen. | Der Reiseagent bucht eine Reise, indem er die notwendigen Reisevorkehrungen (Auto, öffentliche Verkehrsmittel, Flüge) vom aktuellen Standort bis zum Zielort ermittelt. | | **Nutzenbasierte Agenten** | Berücksichtigen Präferenzen und wägen numerische Kompromisse ab, um Ziele zu erreichen. | Der Reiseagent maximiert den Nutzen, indem er Bequemlichkeit gegenüber Kosten abwägt, wenn er Reisen bucht. | | **Lernende Agenten** | Verbessern sich im Laufe der Zeit, indem sie auf Feedback reagieren und ihre Aktionen entsprechend anpassen. | Der Reiseagent verbessert sich, indem er Kundenfeedback aus Nach-Reise-Umfragen nutzt, um zukünftige Buchungen anzupassen. | | **Hierarchische Agenten** | Bestehen aus mehreren Agenten in einem gestuften System, wobei höherstufige Agenten Aufgaben in Unteraufgaben für niedrigerstufige Agenten aufteilen. | Der Reiseagent storniert eine Reise, indem er die Aufgabe in Unteraufgaben aufteilt (z. B. spezifische Buchungen stornieren) und niedrigere Agenten diese ausführen lässt, die wiederum an den höherstufigen Agenten berichten. | | **Multi-Agenten-Systeme (MAS)** | Agenten erledigen Aufgaben unabhängig, entweder kooperativ oder im Wettbewerb. | Kooperativ: Mehrere Agenten buchen spezifische Reisedienstleistungen wie Hotels, Flüge und Unterhaltung. Wettbewerbsorientiert: Mehrere Agenten verwalten und konkurrieren um einen gemeinsamen Hotelbuchungskalender, um Kunden in das Hotel einzubuchen. | ## Wann sollten KI-Agenten eingesetzt werden? Im vorherigen Abschnitt haben wir das Beispiel eines Reisebuchungs-Agenten genutzt, um zu erklären, wie verschiedene Agententypen in unterschiedlichen Szenarien eingesetzt werden können. Dieses Anwendungsbeispiel wird im gesamten Kurs weiterverwendet. Schauen wir uns die Arten von Anwendungsfällen an, für die sich KI-Agenten am besten eignen: ![Wann sollten KI-Agenten eingesetzt werden?](../../../translated_images/when-to-use-ai-agents.912b9a02e9e0e2af45a3e24faa4e912e334ec23f21f0cf5cb040b7e899b09cd0.de.png?WT.mc_id=academic-105485-koreyst) - **Offene Problemstellungen** – Ermöglicht dem LLM, die notwendigen Schritte zur Erledigung einer Aufgabe zu bestimmen, da diese nicht immer fest in einen Arbeitsablauf programmiert werden können. - **Mehrstufige Prozesse** – Aufgaben, die ein gewisses Maß an Komplexität erfordern, bei denen der KI-Agent Werkzeuge oder Informationen über mehrere Schritte hinweg nutzen muss, anstatt sie in einem einzigen Schritt abzurufen. - **Verbesserung über Zeit** – Aufgaben, bei denen der Agent durch Feedback aus seiner Umgebung oder von Benutzern im Laufe der Zeit besser werden kann, um einen höheren Nutzen zu bieten. Weitere Überlegungen zum Einsatz von KI-Agenten behandeln wir in der Lektion "Vertrauenswürdige KI-Agenten entwickeln". ## Grundlagen agentenbasierter Lösungen ### Entwicklung von Agenten Der erste Schritt bei der Gestaltung eines KI-Agenten-Systems besteht darin, die Werkzeuge, Aktionen und Verhaltensweisen zu definieren. In diesem Kurs konzentrieren wir uns auf die Verwendung des **Azure AI Agent Service**, um unsere Agenten zu definieren. Dieser bietet Funktionen wie: - Auswahl offener Modelle wie OpenAI, Mistral und Llama - Nutzung lizenzierter Daten durch Anbieter wie Tripadvisor - Verwendung standardisierter OpenAPI 3.0-Werkzeuge ### Agentenbasierte Muster Die Kommunikation mit LLMs erfolgt über Prompts. Aufgrund der halbautonomen Natur von KI-Agenten ist es nicht immer möglich oder notwendig, das LLM manuell nach jeder Veränderung in der Umgebung erneut zu prompten. Wir verwenden **agentenbasierte Muster**, die es uns ermöglichen, das LLM über mehrere Schritte hinweg auf skalierbare Weise zu prompten. Dieser Kurs ist in einige der derzeit populären agentenbasierten Muster unterteilt. ### Agentenbasierte Frameworks Agentenbasierte Frameworks ermöglichen es Entwicklern, agentenbasierte Muster durch Code zu implementieren. Diese Frameworks bieten Vorlagen, Plugins und Werkzeuge für eine bessere Zusammenarbeit von KI-Agenten. Diese Vorteile ermöglichen eine bessere Beobachtbarkeit und Fehlerbehebung in KI-Agenten-Systemen. In diesem Kurs werden wir das forschungsgetriebene AutoGen-Framework sowie das produktionsreife Agent-Framework von Semantic Kernel erkunden. **Haftungsausschluss**: Dieses Dokument wurde mit KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, beachten Sie bitte, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir haften nicht für Missverständnisse oder Fehlinterpretationen, die durch die Nutzung dieser Übersetzung entstehen.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/01-intro-to-ai-agents/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/01-intro-to-ai-agents/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 11399 }
```markdown # Erforsche KI-Agenten-Frameworks KI-Agenten-Frameworks sind Softwareplattformen, die die Erstellung, Bereitstellung und Verwaltung von KI-Agenten vereinfachen sollen. Diese Frameworks bieten Entwicklern vorgefertigte Komponenten, Abstraktionen und Werkzeuge, die die Entwicklung komplexer KI-Systeme beschleunigen. Diese Frameworks helfen Entwicklern, sich auf die einzigartigen Aspekte ihrer Anwendungen zu konzentrieren, indem sie standardisierte Ansätze für häufige Herausforderungen in der KI-Agenten-Entwicklung bereitstellen. Sie verbessern die Skalierbarkeit, Zugänglichkeit und Effizienz beim Aufbau von KI-Systemen. ## Einführung Diese Lektion behandelt: - Was sind KI-Agenten-Frameworks und was ermöglichen sie Entwicklern? - Wie können Teams diese Frameworks nutzen, um schnell Prototypen zu erstellen, zu iterieren und die Fähigkeiten meiner Agenten zu verbessern? - Welche Unterschiede gibt es zwischen den von Microsoft entwickelten Frameworks und Tools ([Autogen](https://aka.ms/ai-agents/autogen) / [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) / [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service))? - Kann ich meine bestehenden Azure-Ökosystem-Tools direkt integrieren, oder benötige ich eigenständige Lösungen? - Was ist der Azure AI Agent Service und wie unterstützt er mich? ## Lernziele Die Ziele dieser Lektion sind: - Die Rolle von KI-Agenten-Frameworks in der KI-Entwicklung zu verstehen. - Wie man KI-Agenten-Frameworks einsetzt, um intelligente Agenten zu entwickeln. - Die wichtigsten Funktionen, die durch KI-Agenten-Frameworks ermöglicht werden. - Die Unterschiede zwischen Autogen, Semantic Kernel und Azure AI Agent Service. ## Was sind KI-Agenten-Frameworks und was ermöglichen sie Entwicklern? Traditionelle KI-Frameworks können dabei helfen, KI in Apps zu integrieren und diese Apps auf folgende Weise zu verbessern: - **Personalisierung**: KI kann das Nutzerverhalten und die Vorlieben analysieren, um personalisierte Empfehlungen, Inhalte und Erlebnisse zu bieten. Beispiel: Streaming-Dienste wie Netflix nutzen KI, um Filme und Serien basierend auf der Seh-Historie vorzuschlagen, was die Nutzerbindung und Zufriedenheit erhöht. - **Automatisierung und Effizienz**: KI kann repetitive Aufgaben automatisieren, Arbeitsabläufe optimieren und die betriebliche Effizienz steigern. Beispiel: Kundenservice-Apps nutzen KI-gestützte Chatbots, um häufige Anfragen zu bearbeiten, wodurch Antwortzeiten verkürzt und menschliche Mitarbeiter für komplexere Probleme freigestellt werden. - **Verbesserte Nutzererfahrung**: KI kann die allgemeine Nutzererfahrung verbessern, indem sie intelligente Funktionen wie Spracherkennung, natürliche Sprachverarbeitung und prädiktiven Text bereitstellt. Beispiel: Virtuelle Assistenten wie Siri und Google Assistant nutzen KI, um Sprachbefehle zu verstehen und darauf zu reagieren, was die Interaktion der Nutzer mit ihren Geräten erleichtert. ### Klingt großartig, oder? Warum brauchen wir dann KI-Agenten-Frameworks? KI-Agenten-Frameworks gehen über herkömmliche KI-Frameworks hinaus. Sie sind darauf ausgelegt, die Erstellung intelligenter Agenten zu ermöglichen, die mit Nutzern, anderen Agenten und der Umgebung interagieren können, um spezifische Ziele zu erreichen. Diese Agenten können autonomes Verhalten zeigen, Entscheidungen treffen und sich an veränderte Bedingungen anpassen. Werfen wir einen Blick auf einige der wichtigsten Funktionen, die durch KI-Agenten-Frameworks ermöglicht werden: - **Zusammenarbeit und Koordination von Agenten**: Ermöglicht die Erstellung mehrerer KI-Agenten, die zusammenarbeiten, kommunizieren und koordiniert komplexe Aufgaben lösen können. - **Automatisierung und Verwaltung von Aufgaben**: Bietet Mechanismen zur Automatisierung mehrstufiger Arbeitsabläufe, zur Aufgabenverteilung und zum dynamischen Aufgabenmanagement zwischen Agenten. - **Kontextuelles Verständnis und Anpassung**: Rüstet Agenten mit der Fähigkeit aus, Kontext zu verstehen, sich an sich verändernde Umgebungen anzupassen und Entscheidungen auf Basis von Echtzeitinformationen zu treffen. Zusammenfassend lässt sich sagen, dass Agenten es ermöglichen, mehr zu leisten, Automatisierung auf die nächste Stufe zu heben und intelligentere Systeme zu schaffen, die sich an ihre Umgebung anpassen und aus ihr lernen können. ## Wie kann man die Fähigkeiten eines Agenten schnell prototypisieren, iterieren und verbessern? Dies ist ein schnelllebiges Feld, aber es gibt einige Gemeinsamkeiten, die die meisten KI-Agenten-Frameworks bieten, um Prototypen schnell zu erstellen und zu iterieren. Dazu gehören modulare Komponenten, kollaborative Werkzeuge und Echtzeitlernen. Schauen wir uns diese genauer an: - **Modulare Komponenten nutzen**: KI-Frameworks bieten vorgefertigte Komponenten wie Prompts, Parser und Speichermanagement. - **Kollaborative Werkzeuge einsetzen**: Agenten mit spezifischen Rollen und Aufgaben entwerfen, um kollaborative Arbeitsabläufe zu testen und zu verfeinern. - **In Echtzeit lernen**: Feedback-Schleifen implementieren, bei denen Agenten aus Interaktionen lernen und ihr Verhalten dynamisch anpassen. ### Modulare Komponenten nutzen Frameworks wie LangChain und Microsoft Semantic Kernel bieten vorgefertigte Komponenten wie Prompts, Parser und Speichermanagement. **Wie Teams diese nutzen können**: Teams können diese Komponenten schnell zusammenfügen, um einen funktionalen Prototyp zu erstellen, ohne von Grund auf neu beginnen zu müssen. Dies ermöglicht schnelles Experimentieren und Iterieren. **Wie es in der Praxis funktioniert**: Sie können einen vorgefertigten Parser verwenden, um Informationen aus Benutzereingaben zu extrahieren, ein Speichermodul zum Speichern und Abrufen von Daten und einen Prompt-Generator, um mit Benutzern zu interagieren – alles ohne diese Komponenten selbst entwickeln zu müssen. **Beispielcode**. Schauen wir uns ein Beispiel an, wie ein vorgefertigter Parser verwendet werden kann, um Informationen aus Benutzereingaben zu extrahieren: ```python from langchain import Parser parser = Parser() user_input = "Book a flight from New York to London on July 15th" parsed_data = parser.parse(user_input) print(parsed_data) # Output: {'origin': 'New York', 'destination': 'London', 'date': 'July 15th'} ``` In diesem Beispiel sehen Sie, wie ein vorgefertigter Parser verwendet werden kann, um Schlüsselinformationen aus Benutzereingaben zu extrahieren, wie z. B. den Ursprung, das Ziel und das Datum einer Flugbuchungsanfrage. Dieser modulare Ansatz ermöglicht es, sich auf die übergeordnete Logik zu konzentrieren. ### Kollaborative Werkzeuge einsetzen Frameworks wie CrewAI und Microsoft Autogen erleichtern die Erstellung mehrerer Agenten, die zusammenarbeiten können. **Wie Teams diese nutzen können**: Teams können Agenten mit spezifischen Rollen und Aufgaben entwerfen, um kollaborative Arbeitsabläufe zu testen und zu verfeinern und die Gesamteffizienz des Systems zu verbessern. **Wie es in der Praxis funktioniert**: Sie können ein Team von Agenten erstellen, bei dem jeder Agent eine spezialisierte Funktion hat, wie z. B. Datenabruf, Analyse oder Entscheidungsfindung. Diese Agenten können kommunizieren und Informationen austauschen, um ein gemeinsames Ziel zu erreichen, wie z. B. eine Benutzeranfrage zu beantworten oder eine Aufgabe abzuschließen. **Beispielcode (Autogen)**: ```python # creating agents, then create a round robin schedule where they can work together, in this case in order # Data Retrieval Agent # Data Analysis Agent # Decision Making Agent agent_retrieve = AssistantAgent( name="dataretrieval", model_client=model_client, tools=[retrieve_tool], system_message="Use tools to solve tasks." ) agent_analyze = AssistantAgent( name="dataanalysis", model_client=model_client, tools=[analyze_tool], system_message="Use tools to solve tasks." ) # conversation ends when user says "APPROVE" termination = TextMentionTermination("APPROVE") user_proxy = UserProxyAgent("user_proxy", input_func=input) team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination) stream = team.run_stream(task="Analyze data", max_turns=10) # Use asyncio.run(...) when running in a script. await Console(stream) ``` In diesem Code sehen Sie, wie eine Aufgabe erstellt wird, die mehrere Agenten einbezieht, die zusammenarbeiten, um Daten zu analysieren. Jeder Agent erfüllt eine spezifische Funktion, und die Aufgabe wird durch die Koordination der Agenten ausgeführt, um das gewünschte Ergebnis zu erzielen. Durch die Erstellung dedizierter Agenten mit spezialisierten Rollen können Sie die Effizienz und Leistung von Aufgaben verbessern. ### In Echtzeit lernen Fortschrittliche Frameworks bieten Funktionen für kontextuelles Echtzeitverstehen und Anpassung. **Wie Teams diese nutzen können**: Teams können Feedback-Schleifen implementieren, bei denen Agenten aus Interaktionen lernen und ihr Verhalten dynamisch anpassen, was zu einer kontinuierlichen Verbesserung und Verfeinerung der Fähigkeiten führt. **Wie es in der Praxis funktioniert**: Agenten können Benutzerfeedback, Umweltdaten und Aufgabenergebnisse analysieren, um ihre Wissensbasis zu aktualisieren, Entscheidungsalgorithmen anzupassen und ihre Leistung im Laufe der Zeit zu verbessern. Dieser iterative Lernprozess ermöglicht es Agenten, sich an sich ändernde Bedingungen und Benutzerpräferenzen anzupassen, wodurch die Gesamteffektivität des Systems gesteigert wird. ## Was sind die Unterschiede zwischen den Frameworks Autogen, Semantic Kernel und Azure AI Agent Service? Es gibt viele Möglichkeiten, diese Frameworks zu vergleichen, aber lassen Sie uns einige der wichtigsten Unterschiede in Bezug auf Design, Fähigkeiten und Zielanwendungen betrachten: ## Autogen Ein Open-Source-Framework, entwickelt vom AI Frontiers Lab von Microsoft Research. Es konzentriert sich auf ereignisgesteuerte, verteilte *agentische* Anwendungen und ermöglicht mehrere LLMs, SLMs, Tools und fortgeschrittene Multi-Agent-Designmuster. Autogen basiert auf dem Kernkonzept der Agenten, die autonome Einheiten sind, die ihre Umgebung wahrnehmen, Entscheidungen treffen und Aktionen ausführen können, um bestimmte Ziele zu erreichen. Agenten kommunizieren über asynchrone Nachrichten, was ihnen ermöglicht, unabhängig und parallel zu arbeiten, wodurch die Skalierbarkeit und Reaktionsfähigkeit des Systems verbessert wird. Agenten basieren auf dem [Aktor-Modell](https://en.wikipedia.org/wiki/Actor_model). Laut Wikipedia ist ein Aktor _die grundlegende Baueinheit für parallele Berechnungen. Als Antwort auf eine empfangene Nachricht kann ein Aktor lokale Entscheidungen treffen, weitere Aktoren erstellen, weitere Nachrichten senden und bestimmen, wie auf die nächste empfangene Nachricht reagiert wird_. **Anwendungsfälle**: Automatisierung von Code-Generierung, Datenanalyseaufgaben und Entwicklung maßgeschneiderter Agenten für Planungs- und Forschungsfunktionen. Hier sind einige wichtige Kernkonzepte von Autogen: - **Agenten**: Ein Agent ist eine Softwareeinheit, die: - **Über Nachrichten kommuniziert**, synchron oder asynchron. - **Einen eigenen Zustand aufrechterhält**, der durch eingehende Nachrichten geändert werden kann. - **Aktionen ausführt** als Reaktion auf empfangene Nachrichten oder Änderungen ihres Zustands. Hier ein kurzer Codeausschnitt, wie ein eigener Agent mit Chat-Fähigkeiten erstellt wird: ```python from autogen_agentchat.agents import AssistantAgent from autogen_agentchat.messages import TextMessage from autogen_ext.models.openai import OpenAIChatCompletionClient class MyAssistant(RoutedAgent): def __init__(self, name: str) -> None: super().__init__(name) model_client = OpenAIChatCompletionClient(model="gpt-4o") self._delegate = AssistantAgent(name, model_client=model_client) @message_handler async def handle_my_message_type(self, message: MyMessageType, ctx: MessageContext) -> None: print(f"{self.id.type} received message: {message.content}") response = await self._delegate.on_messages( [TextMessage(content=message.content, source="user")], ctx.cancellation_token ) print(f"{self.id.type} responded: {response.chat_message.content}") ``` In obigem Code ist `MyAssistant` has been created and inherits from `RoutedAgent`. It has a message handler that prints the content of the message and then sends a response using the `AssistantAgent` delegate. Especially note how we assign to `self._delegate` an instance of `AssistantAgent` ein vorgefertigter Agent, der Chat-Abschlüsse bearbeiten kann. Lassen Sie uns Autogen über diesen Agententyp informieren und das Programm starten: ```python # main.py runtime = SingleThreadedAgentRuntime() await MyAgent.register(runtime, "my_agent", lambda: MyAgent()) runtime.start() # Start processing messages in the background. await runtime.send_message(MyMessageType("Hello, World!"), AgentId("my_agent", "default")) ``` Oben wird der Agent mit der Laufzeit registriert und dann eine Nachricht an den Agenten gesendet, was zu folgendem Ergebnis führt: ```text # Output from the console: my_agent received message: Hello, World! my_assistant received message: Hello, World! my_assistant responded: Hello! How can I assist you today? ``` - **Multi-Agenten**: Autogen unterstützt die Erstellung mehrerer Agenten, die zusammenarbeiten können, um komplexe Aufgaben zu lösen. Sie können unterschiedliche Typen von Agenten mit spezialisierten Funktionen und Rollen definieren, z. B. Datenabruf, Analyse, Entscheidungsfindung und Benutzerinteraktion. Sehen wir uns an, wie eine solche Erstellung aussieht: ```python editor_description = "Editor for planning and reviewing the content." # Example of declaring an Agent editor_agent_type = await EditorAgent.register( runtime, editor_topic_type, # Using topic type as the agent type. lambda: EditorAgent( description=editor_description, group_chat_topic_type=group_chat_topic_type, model_client=OpenAIChatCompletionClient( model="gpt-4o-2024-08-06", # api_key="YOUR_API_KEY", ), ), ) # remaining declarations shortened for brevity # Group chat group_chat_manager_type = await GroupChatManager.register( runtime, "group_chat_manager", lambda: GroupChatManager( participant_topic_types=[writer_topic_type, illustrator_topic_type, editor_topic_type, user_topic_type], model_client=OpenAIChatCompletionClient( model="gpt-4o-2024-08-06", # api_key="YOUR_API_KEY", ), participant_descriptions=[ writer_description, illustrator_description, editor_description, user_description ], ), ) ``` Oben wird ein `GroupChatManager` mit der Laufzeit registriert. Dieser Manager ist für die Koordination der Interaktionen zwischen verschiedenen Agententypen wie Autoren, Illustratoren, Redakteuren und Nutzern verantwortlich. - **Agenten-Laufzeit**: Das Framework bietet eine Laufzeitumgebung, die die Kommunikation zwischen Agenten ermöglicht, ihre Identitäten und Lebenszyklen verwaltet und Sicherheits- sowie Datenschutzgrenzen durchsetzt. Dies bedeutet, dass Sie Ihre Agenten in einer sicheren und kontrollierten Umgebung ausführen können, was eine sichere und effiziente Interaktion gewährleistet. Es gibt zwei interessante Laufzeiten: - **Standalone-Laufzeit**: Eine gute Wahl für Einzelprozessanwendungen, bei denen alle Agenten in derselben Programmiersprache implementiert und im selben Prozess ausgeführt werden. Hier ist eine Illustration, wie es funktioniert: ![Standalone-Laufzeit](https://microsoft.github.io/autogen/stable/_images/architecture-standalone.svg) *Agenten kommunizieren über Nachrichten durch die Laufzeit, und die Laufzeit verwaltet den Lebenszyklus der Agenten.* - **Verteilte Agenten-Laufzeit**: Geeignet für Multi-Prozess-Anwendungen, bei denen Agenten in verschiedenen Programmiersprachen implementiert und auf verschiedenen Maschinen ausgeführt werden können. Hier ist eine Illustration, wie es funktioniert: ![Verteilte Laufzeit](https://microsoft.github.io/autogen/stable/_images/architecture-distributed.svg) ``` basierend auf Projektzielen. Ideal für das Verständnis natürlicher Sprache und die Generierung von Inhalten. - **Azure AI Agent Service**: Flexible Modelle, unternehmenssichere Mechanismen, Daten-Speichermethoden. Ideal für die sichere, skalierbare und flexible Bereitstellung von KI-Agenten in Unternehmensanwendungen. ## Kann ich meine bestehenden Azure-Ökosystem-Tools direkt integrieren, oder benötige ich eigenständige Lösungen? Die Antwort ist ja, Sie können Ihre bestehenden Azure-Ökosystem-Tools direkt mit dem Azure AI Agent Service integrieren, insbesondere, da dieser nahtlos mit anderen Azure-Diensten zusammenarbeitet. Sie könnten beispielsweise Bing, Azure AI Search und Azure Functions integrieren. Es gibt auch eine tiefe Integration mit Azure AI Foundry. Für Autogen und Semantic Kernel können Sie ebenfalls mit Azure-Diensten integrieren, allerdings kann es erforderlich sein, die Azure-Dienste aus Ihrem Code aufzurufen. Eine weitere Möglichkeit zur Integration besteht darin, die Azure SDKs zu verwenden, um von Ihren Agenten aus mit Azure-Diensten zu interagieren. Außerdem, wie bereits erwähnt, können Sie den Azure AI Agent Service als Orchestrator für Ihre in Autogen oder Semantic Kernel erstellten Agenten verwenden, was einen einfachen Zugang zum Azure-Ökosystem ermöglicht. ## Referenzen - [1] - [Azure Agent Service](https://techcommunity.microsoft.com/blog/azure-ai-services-blog/introducing-azure-ai-agent-service/4298357) - [2] - [Semantic Kernel and Autogen](https://devblogs.microsoft.com/semantic-kernel/microsofts-agentic-ai-frameworks-autogen-and-semantic-kernel/) - [3] - [Semantic Kernel Agent Framework](https://learn.microsoft.com/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp) - [4] - [Azure AI Agent service](https://learn.microsoft.com/azure/ai-services/agents/overview) - [5] - [Using Azure AI Agent Service with AutoGen / Semantic Kernel to build a multi-agent's solution](https://techcommunity.microsoft.com/blog/educatordeveloperblog/using-azure-ai-agent-service-with-autogen--semantic-kernel-to-build-a-multi-agen/4363121) **Haftungsausschluss**: Dieses Dokument wurde mit KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die aus der Nutzung dieser Übersetzung entstehen.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/02-explore-agentic-frameworks/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/02-explore-agentic-frameworks/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 19237 }
# Prinzipien des Agenten-Designs für KI ## Einführung Es gibt viele Ansätze, um KI-Agentensysteme zu entwickeln. Da Mehrdeutigkeit in der Gestaltung generativer KI eher ein Merkmal als ein Fehler ist, fällt es Ingenieuren manchmal schwer, überhaupt einen Ausgangspunkt zu finden. Wir haben eine Reihe von nutzerzentrierten UX-Design-Prinzipien entwickelt, um Entwicklern zu helfen, kundenorientierte Agentensysteme zu erstellen, die ihre geschäftlichen Anforderungen erfüllen. Diese Designprinzipien sind keine verbindliche Architektur, sondern ein Ausgangspunkt für Teams, die Agentenerfahrungen definieren und entwickeln. Im Allgemeinen sollten Agenten: - Die menschlichen Fähigkeiten erweitern und skalieren (z. B. Brainstorming, Problemlösung, Automatisierung usw.). - Wissenslücken schließen (z. B. Einblick in Wissensbereiche geben, Übersetzungen, usw.). - Zusammenarbeit erleichtern und unterstützen, indem sie sich an unsere individuellen Arbeitspräferenzen anpassen. - Uns zu besseren Versionen unserer selbst machen (z. B. als Lebenscoach/Aufgabenmanager, Unterstützung bei der Entwicklung von Fähigkeiten zur emotionalen Regulierung und Achtsamkeit, Aufbau von Resilienz usw.). ## Dieses Kapitel behandelt - Was sind die Prinzipien des Agenten-Designs? - Welche Richtlinien sollten bei der Umsetzung dieser Prinzipien beachtet werden? - Beispiele für die Anwendung der Designprinzipien ## Lernziele Nach Abschluss dieses Kapitels wirst du in der Lage sein: 1. Zu erklären, was die Prinzipien des Agenten-Designs sind. 2. Die Richtlinien zur Anwendung der Prinzipien des Agenten-Designs zu erläutern. 3. Zu verstehen, wie man einen Agenten mithilfe der Prinzipien des Agenten-Designs entwickelt. ## Die Prinzipien des Agenten-Designs ![Agenten-Design-Prinzipien](../../../translated_images/agentic-design-principles.9f32a64bb6e2aa5a1bdffb70111aa724058bc248b1a3dd3c6661344015604cff.de.png?WT.mc_id=academic-105485-koreyst) ### Agent (Raum) Dies ist die Umgebung, in der der Agent agiert. Diese Prinzipien beeinflussen, wie wir Agenten für den Einsatz in physischen und digitalen Welten gestalten. - **Verbindungen schaffen, nicht zerstören** – Helfen, Menschen mit anderen Menschen, Ereignissen und umsetzbarem Wissen zu verbinden, um Zusammenarbeit und Austausch zu ermöglichen. - Agenten helfen, Ereignisse, Wissen und Menschen miteinander zu verknüpfen. - Agenten bringen Menschen näher zusammen. Sie sind nicht dafür konzipiert, Menschen zu ersetzen oder zu entwerten. - **Leicht zugänglich, aber gelegentlich unsichtbar** – Der Agent agiert größtenteils im Hintergrund und meldet sich nur, wenn es relevant und angemessen ist. - Der Agent ist für autorisierte Nutzer auf jedem Gerät oder jeder Plattform leicht auffindbar und zugänglich. - Der Agent unterstützt multimodale Eingaben und Ausgaben (z. B. Ton, Sprache, Text usw.). - Der Agent kann nahtlos zwischen Vorder- und Hintergrund wechseln, je nach Wahrnehmung der Nutzerbedürfnisse. - Der Agent kann in unsichtbarer Form agieren, jedoch ist sein Hintergrundprozess und die Zusammenarbeit mit anderen Agenten für den Nutzer transparent und kontrollierbar. ### Agent (Zeit) Dies beschreibt, wie der Agent über die Zeit hinweg agiert. Diese Prinzipien beeinflussen, wie wir Agenten gestalten, die über Vergangenheit, Gegenwart und Zukunft hinweg interagieren. - **Vergangenheit**: Reflektion der Geschichte, die sowohl Zustand als auch Kontext umfasst. - Der Agent liefert relevantere Ergebnisse durch die Analyse umfangreicher historischer Daten, die über das Ereignis, die Personen oder Zustände hinausgehen. - Der Agent schafft Verbindungen aus vergangenen Ereignissen und reflektiert aktiv Erinnerungen, um mit aktuellen Situationen umzugehen. - **Jetzt**: Mehr anstoßen als benachrichtigen. - Der Agent verkörpert einen umfassenden Ansatz zur Interaktion mit Menschen. Wenn ein Ereignis eintritt, geht der Agent über statische Benachrichtigungen oder andere Formalitäten hinaus. Der Agent kann Abläufe vereinfachen oder dynamisch Hinweise generieren, um die Aufmerksamkeit des Nutzers im richtigen Moment zu lenken. - Der Agent liefert Informationen basierend auf dem Kontext der Umgebung, sozialen und kulturellen Veränderungen und abgestimmt auf die Absicht des Nutzers. - Die Interaktion mit dem Agenten kann schrittweise erfolgen, sich entwickeln und langfristig an Komplexität gewinnen, um den Nutzer zu stärken. - **Zukunft**: Anpassen und weiterentwickeln. - Der Agent passt sich an verschiedene Geräte, Plattformen und Modalitäten an. - Der Agent passt sich dem Verhalten des Nutzers, dessen Barrierefreiheitsanforderungen an und ist frei anpassbar. - Der Agent wird durch kontinuierliche Nutzerinteraktion geformt und weiterentwickelt. ### Agent (Kern) Dies sind die Schlüsselelemente im Kern des Designs eines Agenten. - **Unsicherheit akzeptieren, aber Vertrauen schaffen**. - Ein gewisses Maß an Unsicherheit des Agenten wird erwartet. Unsicherheit ist ein Kernelement des Agenten-Designs. - Vertrauen und Transparenz sind fundamentale Schichten des Agenten-Designs. - Menschen haben die Kontrolle darüber, wann der Agent ein- oder ausgeschaltet ist, und der Status des Agenten ist jederzeit klar ersichtlich. ## Die Richtlinien zur Umsetzung dieser Prinzipien Wenn du die oben genannten Designprinzipien anwendest, beachte die folgenden Richtlinien: 1. **Transparenz**: Informiere den Nutzer darüber, dass KI beteiligt ist, wie sie funktioniert (einschließlich vergangener Aktionen) und wie Feedback gegeben und das System angepasst werden kann. 2. **Kontrolle**: Gib dem Nutzer die Möglichkeit, das System zu personalisieren, Präferenzen festzulegen und Kontrolle über das System und seine Eigenschaften zu haben (einschließlich der Möglichkeit, Daten zu vergessen). 3. **Konsistenz**: Strebe konsistente, multimodale Erlebnisse über Geräte und Endpunkte hinweg an. Verwende, wo möglich, vertraute UI/UX-Elemente (z. B. Mikrofon-Symbol für Sprachinteraktion) und reduziere die kognitive Belastung des Nutzers so weit wie möglich (z. B. durch prägnante Antworten, visuelle Hilfsmittel und Inhalte wie „Mehr erfahren“). ## Wie man einen Reiseagenten basierend auf diesen Prinzipien und Richtlinien gestaltet Angenommen, du entwickelst einen Reiseagenten. So könntest du die Designprinzipien und Richtlinien anwenden: 1. **Transparenz** – Informiere den Nutzer darüber, dass der Reiseagent ein KI-gestützter Agent ist. Gib grundlegende Anweisungen, wie man startet (z. B. eine „Hallo“-Nachricht, Beispielaufforderungen). Dokumentiere dies klar auf der Produktseite. Zeige die Liste der Aufforderungen, die ein Nutzer in der Vergangenheit gestellt hat. Mach deutlich, wie Feedback gegeben werden kann (Daumen hoch und runter, Feedback-Button usw.). Erkläre klar, ob der Agent Nutzungs- oder Themenbeschränkungen hat. 2. **Kontrolle** – Stelle sicher, dass klar ist, wie der Nutzer den Agenten nach seiner Erstellung anpassen kann, z. B. mit der Systemaufforderung. Erlaube dem Nutzer, die Ausführlichkeit des Agenten, seinen Schreibstil und Einschränkungen, worüber der Agent nicht sprechen sollte, auszuwählen. Erlaube dem Nutzer, zugehörige Dateien oder Daten, Aufforderungen und frühere Konversationen einzusehen und zu löschen. 3. **Konsistenz** – Stelle sicher, dass die Symbole für Aufforderung teilen, Datei oder Foto hinzufügen und jemanden oder etwas markieren standardisiert und erkennbar sind. Verwende das Büroklammer-Symbol, um Datei-Uploads/Teilen mit dem Agenten anzuzeigen, und ein Bild-Symbol, um den Upload von Grafiken anzuzeigen. ## Zusätzliche Ressourcen - [Practices for Governing Agentic AI Systems | OpenAI](https://openai.com) - [The HAX Toolkit Project - Microsoft Research](https://microsoft.com) - [Responsible AI Toolbox](https://responsibleaitoolbox.ai) ``` **Haftungsausschluss**: Dieses Dokument wurde mit KI-basierten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die durch die Nutzung dieser Übersetzung entstehen.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/03-agentic-design-patterns/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/03-agentic-design-patterns/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 8405 }
# Entwurfsmuster für die Nutzung von Tools ## Einführung In dieser Lektion wollen wir folgende Fragen beantworten: - Was ist das Entwurfsmuster für die Nutzung von Tools? - Für welche Anwendungsfälle kann es eingesetzt werden? - Welche Elemente/Bausteine sind notwendig, um das Entwurfsmuster umzusetzen? - Welche besonderen Überlegungen sind bei der Nutzung des Entwurfsmusters für die Entwicklung vertrauenswürdiger KI-Agenten zu beachten? ## Lernziele Nach Abschluss dieser Lektion wirst du in der Lage sein: - Das Entwurfsmuster für die Nutzung von Tools und dessen Zweck zu definieren. - Anwendungsfälle zu identifizieren, in denen das Entwurfsmuster anwendbar ist. - Die wichtigsten Elemente zu verstehen, die für die Implementierung des Entwurfsmusters erforderlich sind. - Überlegungen zur Sicherstellung der Vertrauenswürdigkeit von KI-Agenten, die dieses Entwurfsmuster verwenden, zu erkennen. ## Was ist das Entwurfsmuster für die Nutzung von Tools? Das **Entwurfsmuster für die Nutzung von Tools** konzentriert sich darauf, LLMs die Fähigkeit zu geben, mit externen Tools zu interagieren, um bestimmte Ziele zu erreichen. Tools sind Code, der von einem Agenten ausgeführt werden kann, um Aktionen durchzuführen. Ein Tool kann eine einfache Funktion wie ein Taschenrechner oder ein API-Aufruf zu einem Drittanbieterdienst wie eine Aktienkursabfrage oder eine Wettervorhersage sein. Im Kontext von KI-Agenten sind Tools so konzipiert, dass sie von Agenten als Antwort auf **modellgenerierte Funktionsaufrufe** ausgeführt werden. ## Für welche Anwendungsfälle kann es eingesetzt werden? KI-Agenten können Tools nutzen, um komplexe Aufgaben zu erledigen, Informationen abzurufen oder Entscheidungen zu treffen. Das Entwurfsmuster für die Nutzung von Tools wird oft in Szenarien eingesetzt, die eine dynamische Interaktion mit externen Systemen wie Datenbanken, Webdiensten oder Code-Interpretern erfordern. Diese Fähigkeit ist für eine Vielzahl von Anwendungsfällen nützlich, darunter: - **Dynamische Informationsbeschaffung:** Agenten können externe APIs oder Datenbanken abfragen, um aktuelle Daten abzurufen (z. B. Abfragen einer SQLite-Datenbank für Datenanalysen, Abrufen von Aktienkursen oder Wetterinformationen). - **Codeausführung und -interpretation:** Agenten können Code oder Skripte ausführen, um mathematische Probleme zu lösen, Berichte zu erstellen oder Simulationen durchzuführen. - **Workflow-Automatisierung:** Automatisierung von sich wiederholenden oder mehrstufigen Workflows durch die Integration von Tools wie Aufgabenplanern, E-Mail-Diensten oder Datenpipelines. - **Kundensupport:** Agenten können mit CRM-Systemen, Ticketplattformen oder Wissensdatenbanken interagieren, um Benutzeranfragen zu lösen. - **Inhaltsgenerierung und -bearbeitung:** Agenten können Tools wie Grammatikprüfer, Textzusammenfasser oder Inhaltsbewertungstools nutzen, um bei der Erstellung von Inhalten zu helfen. ## Welche Elemente/Bausteine sind notwendig, um das Entwurfsmuster für die Nutzung von Tools umzusetzen? ### Funktions-/Toolaufrufe Der Funktionsaufruf ist der primäre Mechanismus, mit dem wir großen Sprachmodellen (LLMs) die Interaktion mit Tools ermöglichen. Häufig werden die Begriffe „Funktion“ und „Tool“ synonym verwendet, da „Funktionen“ (wiederverwendbare Codeblöcke) die „Tools“ sind, die Agenten verwenden, um Aufgaben auszuführen. Damit der Code einer Funktion aufgerufen werden kann, muss ein LLM die Benutzeranfrage mit der Beschreibung der Funktion vergleichen. Dazu wird ein Schema mit den Beschreibungen aller verfügbaren Funktionen an das LLM gesendet. Das LLM wählt dann die passendste Funktion für die Aufgabe aus und gibt deren Namen und Argumente zurück. Die ausgewählte Funktion wird aufgerufen, ihre Antwort wird an das LLM zurückgesendet, das die Informationen verwendet, um auf die Benutzeranfrage zu antworten. Um Funktionsaufrufe für Agenten zu implementieren, benötigen Entwickler: 1. Ein LLM-Modell, das Funktionsaufrufe unterstützt 2. Ein Schema, das Funktionsbeschreibungen enthält 3. Den Code für jede beschriebene Funktion Lass uns das Beispiel der Abfrage der aktuellen Uhrzeit in einer Stadt verwenden, um dies zu veranschaulichen: - **Initialisierung eines LLMs, das Funktionsaufrufe unterstützt:** Nicht alle Modelle unterstützen Funktionsaufrufe, daher ist es wichtig zu überprüfen, ob das von dir verwendete LLM dies tut. [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling) unterstützt Funktionsaufrufe. Wir können damit beginnen, den Azure OpenAI-Client zu initialisieren. ```python # Initialize the Azure OpenAI client client = AzureOpenAI( azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), api_version="2024-05-01-preview" ) ``` - **Erstellen eines Funktionsschemas:** Als Nächstes definieren wir ein JSON-Schema, das den Funktionsnamen, eine Beschreibung der Funktion sowie die Namen und Beschreibungen der Funktionsparameter enthält. Dieses Schema übergeben wir dann zusammen mit der Benutzeranfrage an den oben erstellten Client, um die Uhrzeit in San Francisco zu finden. Wichtig ist, dass ein **Toolaufruf** zurückgegeben wird, **nicht** die endgültige Antwort auf die Frage. Wie bereits erwähnt, gibt das LLM den Namen der Funktion zurück, die es für die Aufgabe ausgewählt hat, sowie die Argumente, die an sie übergeben werden. ```python # Function description for the model to read tools = [ { "type": "function", "function": { "name": "get_current_time", "description": "Get the current time in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name, e.g. San Francisco", }, }, "required": ["location"], }, } } ] ``` ```python # Initial user message messages = [{"role": "user", "content": "What's the current time in San Francisco"}] # First API call: Ask the model to use the function response = client.chat.completions.create( model=deployment_name, messages=messages, tools=tools, tool_choice="auto", ) # Process the model's response response_message = response.choices[0].message messages.append(response_message) print("Model's response:") print(response_message) ``` ```bash Model's response: ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')]) ``` - **Der Funktionscode, der zur Durchführung der Aufgabe erforderlich ist:** Nachdem das LLM entschieden hat, welche Funktion ausgeführt werden soll, muss der Code, der die Aufgabe ausführt, implementiert und ausgeführt werden. Wir können den Code implementieren, um die aktuelle Uhrzeit in Python abzurufen. Außerdem müssen wir den Code schreiben, um den Namen und die Argumente aus der response_message zu extrahieren, um das endgültige Ergebnis zu erhalten. ```python def get_current_time(location): """Get the current time for a given location""" print(f"get_current_time called with location: {location}") location_lower = location.lower() for key, timezone in TIMEZONE_DATA.items(): if key in location_lower: print(f"Timezone found for {key}") current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p") return json.dumps({ "location": location, "current_time": current_time }) print(f"No timezone data found for {location_lower}") return json.dumps({"location": location, "current_time": "unknown"}) ``` ```python # Handle function calls if response_message.tool_calls: for tool_call in response_message.tool_calls: if tool_call.function.name == "get_current_time": function_args = json.loads(tool_call.function.arguments) time_response = get_current_time( location=function_args.get("location") ) messages.append({ "tool_call_id": tool_call.id, "role": "tool", "name": "get_current_time", "content": time_response, }) else: print("No tool calls were made by the model.") # Second API call: Get the final response from the model final_response = client.chat.completions.create( model=deployment_name, messages=messages, ) return final_response.choices[0].message.content ``` ```bash get_current_time called with location: San Francisco Timezone found for san francisco The current time in San Francisco is 09:24 AM. ``` Der Funktionsaufruf steht im Mittelpunkt der meisten, wenn nicht aller Designs für die Tool-Nutzung von Agenten. Die Implementierung von Grund auf kann jedoch manchmal eine Herausforderung sein. Wie wir in [Lektion 2](../../../02-explore-agentic-frameworks) gelernt haben, bieten agentische Frameworks uns vorgefertigte Bausteine zur Implementierung der Tool-Nutzung. ### Beispiele für die Nutzung von Tools mit agentischen Frameworks - ### **[Semantic Kernel](https://learn.microsoft.com/azure/ai-services/agents/overview)** Semantic Kernel ist ein Open-Source-KI-Framework für .NET-, Python- und Java-Entwickler, die mit großen Sprachmodellen (LLMs) arbeiten. Es vereinfacht die Nutzung von Funktionsaufrufen, indem es deine Funktionen und deren Parameter automatisch durch einen Prozess namens [Serialisierung](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions) beschreibt. Außerdem übernimmt es die Kommunikation zwischen dem Modell und deinem Code. Ein weiterer Vorteil eines agentischen Frameworks wie Semantic Kernel ist, dass es den Zugriff auf vorgefertigte Tools wie [File Search](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step4_assistant_tool_file_search.py) und [Code Interpreter](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py) ermöglicht. Das folgende Diagramm zeigt den Prozess des Funktionsaufrufs mit Semantic Kernel: ![Funktionsaufruf](../../../translated_images/functioncalling-diagram.b5493ea5154ad8e3e4940d2e36a49101eec1398948e5d1039942203b4f5a4209.de.png) In Semantic Kernel werden Funktionen/Tools als [Plugins](https://learn.microsoft.com/semantic-kernel/concepts/plugins/?pivots=programming-language-python) bezeichnet. Wir können die `get_current_time` function we saw earlier into a plugin by turning it into a class with the function in it. We can also import the `kernel_function`-Dekorator verwenden, der die Beschreibung der Funktion enthält. Wenn du dann einen Kernel mit dem GetCurrentTimePlugin erstellst, serialisiert der Kernel die Funktion und ihre Parameter automatisch und erstellt dabei das Schema, das an das LLM gesendet wird. ```python from semantic_kernel.functions import kernel_function class GetCurrentTimePlugin: async def __init__(self, location): self.location = location @kernel_function( description="Get the current time for a given location" ) def get_current_time(location: str = ""): ... ``` ```python from semantic_kernel import Kernel # Create the kernel kernel = Kernel() # Create the plugin get_current_time_plugin = GetCurrentTimePlugin(location) # Add the plugin to the kernel kernel.add_plugin(get_current_time_plugin) ``` - ### **[Azure AI Agent Service](https://learn.microsoft.com/azure/ai-services/agents/overview)** Der Azure AI Agent Service ist ein neues agentisches Framework, das Entwicklern dabei helfen soll, hochwertige, erweiterbare KI-Agenten sicher zu erstellen, bereitzustellen und zu skalieren, ohne die zugrunde liegenden Rechen- und Speicherressourcen verwalten zu müssen. Es ist besonders nützlich für Unternehmensanwendungen, da es ein vollständig verwalteter Dienst mit Sicherheit auf Unternehmensniveau ist. Im Vergleich zur direkten Entwicklung mit der LLM-API bietet der Azure AI Agent Service einige Vorteile, darunter: - Automatische Toolaufrufe – kein Parsen eines Toolaufrufs, Ausführen des Tools und Verarbeiten der Antwort erforderlich; all dies erfolgt nun serverseitig - Sicher verwaltete Daten – anstelle der Verwaltung des eigenen Gesprächsstatus kann man sich auf Threads verlassen, um alle benötigten Informationen zu speichern - Tools out-of-the-box – Tools, die zur Interaktion mit Datenquellen verwendet werden können, wie Bing, Azure AI Search und Azure Functions. Die im Azure AI Agent Service verfügbaren Tools lassen sich in zwei Kategorien unterteilen: 1. Wissenstools: - [Grounding mit Bing Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview) - [File Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/file-search?tabs=python&pivots=overview) - [Azure AI Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search) 2. Aktionstools: - [Funktionsaufrufe](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/function-calling?tabs=python&pivots=overview) - [Code Interpreter](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/code-interpreter?tabs=python&pivots=overview) - [Von OpenAI definierte Tools](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/openapi-spec?tabs=python&pivots=overview) - [Azure Functions](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-functions?pivots=overview) Der Agent Service ermöglicht die Nutzung dieser Tools zusammen als `toolset`. It also utilizes `threads` which keep track of the history of messages from a particular conversation. Imagine you are a sales agent at a company called Contoso. You want to develop a conversational agent that can answer questions about your sales data. The image below illustrates how you could use Azure AI Agent Service to analyze your sales data: ![Agentic Service In Action](../../../translated_images/agent-service-in-action.8c2d8aa8e9d91feeb29549b3fde529f8332b243875154d03907616a69198afbc.de.jpg?WT.mc_id=academic-105485-koreyst) To use any of these tools with the service we can create a client and define a tool or toolset. To implement this practically we can use the Python code below. The LLM will be able to look at the toolset and decide whether to use the user created function, `fetch_sales_data_using_sqlite_query` oder des vorgefertigten Code Interpreters, abhängig von der Benutzeranfrage. ```python import os from azure.ai.projects import AIProjectClient from azure.identity import DefaultAzureCredential from fecth_sales_data_functions import fetch_sales_data_using_sqlite_query # fetch_sales_data_using_sqlite_query function which can be found in a fecth_sales_data_functions.py file. from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool project_client = AIProjectClient.from_connection_string( credential=DefaultAzureCredential(), conn_str=os.environ["PROJECT_CONNECTION_STRING"], ) # Initialize function calling agent with the fetch_sales_data_using_sqlite_query function and adding it to the toolset fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query) toolset = ToolSet() toolset.add(fetch_data_function) # Initialize Code Interpreter tool and adding it to the toolset. code_interpreter = code_interpreter = CodeInterpreterTool() toolset = ToolSet() toolset.add(code_interpreter) agent = project_client.agents.create_agent( model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent", toolset=toolset ) ``` ## Welche besonderen Überlegungen sind bei der Nutzung des Entwurfsmusters für die Entwicklung vertrauenswürdiger KI-Agenten zu beachten? Ein häufiges Anliegen bei SQL, das dynamisch von LLMs generiert wird, ist die Sicherheit, insbesondere das Risiko von SQL-Injection oder bösartigen Aktionen, wie das Löschen oder Manipulieren der Datenbank. Obwohl diese Bedenken berechtigt sind, können sie effektiv durch die richtige Konfiguration der Datenbankzugriffsrechte gemindert werden. Bei den meisten Datenbanken bedeutet dies, die Datenbank als schreibgeschützt zu konfigurieren. Für Datenbankdienste wie PostgreSQL oder Azure SQL sollte der App eine schreibgeschützte (SELECT) Rolle zugewiesen werden. Das Ausführen der App in einer sicheren Umgebung erhöht den Schutz weiter. In Unternehmensszenarien werden Daten typischerweise aus operativen Systemen in eine schreibgeschützte Datenbank oder ein Data Warehouse mit einer benutzerfreundlichen Schema extrahiert und transformiert. Dieser Ansatz stellt sicher, dass die Daten sicher sind, für Leistung und Zugänglichkeit optimiert und dass die App eingeschränkten, schreibgeschützten Zugriff hat. ## Zusätzliche Ressourcen - [Azure AI Agents Service Workshop](https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/) - [Contoso Creative Writer Multi-Agent Workshop](https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop) - [Semantic Kernel Function Calling Tutorial](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions) - [Semantic Kernel Code Interpreter](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py) - [Autogen Tools](https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html) ``` **Haftungsausschluss**: Dieses Dokument wurde mit KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir haften nicht für Missverständnisse oder Fehlinterpretationen, die sich aus der Nutzung dieser Übersetzung ergeben.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/04-tool-use/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/04-tool-use/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 19454 }
# Agentic RAG Diese Lektion bietet einen umfassenden Überblick über Agentic Retrieval-Augmented Generation (Agentic RAG), ein aufstrebendes KI-Paradigma, bei dem große Sprachmodelle (LMs) eigenständig ihre nächsten Schritte planen, während sie Informationen aus externen Quellen abrufen. Im Gegensatz zu statischen Mustern des Abrufens und Lesens umfasst Agentic RAG iterative Aufrufe an das LLM, unterbrochen durch Werkzeug- oder Funktionsaufrufe und strukturierte Ausgaben. Das System bewertet Ergebnisse, verfeinert Abfragen, ruft bei Bedarf zusätzliche Werkzeuge auf und setzt diesen Zyklus fort, bis eine zufriedenstellende Lösung erreicht ist. ## Einführung Diese Lektion umfasst: - **Agentic RAG verstehen:** Einblick in das aufkommende Paradigma in der KI, bei dem große Sprachmodelle (LLMs) eigenständig ihre nächsten Schritte planen und Informationen aus externen Datenquellen abrufen. - **Iterativer Maker-Checker-Ansatz:** Verständnis des iterativen Zyklus von LLM-Aufrufen, unterbrochen durch Werkzeug- oder Funktionsaufrufe und strukturierte Ausgaben, um die Korrektheit zu verbessern und fehlerhafte Abfragen zu behandeln. - **Praktische Anwendungen erkunden:** Identifikation von Szenarien, in denen Agentic RAG besonders effektiv ist, wie z. B. in korrektheitsorientierten Umgebungen, bei komplexen Datenbankinteraktionen und in erweiterten Workflows. ## Lernziele Nach Abschluss dieser Lektion wirst du wissen/verstehen, wie man: - **Agentic RAG versteht:** Einblick in das aufkommende Paradigma in der KI, bei dem große Sprachmodelle (LLMs) eigenständig ihre nächsten Schritte planen und Informationen aus externen Datenquellen abrufen. - **Iterativer Maker-Checker-Ansatz:** Verstehen des Konzepts eines iterativen Zyklus von LLM-Aufrufen, unterbrochen durch Werkzeug- oder Funktionsaufrufe und strukturierte Ausgaben, um die Korrektheit zu verbessern und fehlerhafte Abfragen zu behandeln. - **Den Denkprozess übernehmen:** Das System versteht, wie es seinen Denkprozess eigenständig steuert und Entscheidungen darüber trifft, wie es Probleme angeht, ohne auf vordefinierte Pfade angewiesen zu sein. - **Workflow:** Verstehen, wie ein agentisches Modell eigenständig Markttrendberichte abruft, Wettbewerbsdaten identifiziert, interne Verkaufsmetriken korreliert, Erkenntnisse synthetisiert und die Strategie evaluiert. - **Iterative Schleifen, Werkzeugintegration und Gedächtnis:** Lernen, wie das System auf einem iterativen Interaktionsmuster basiert, den Zustand und das Gedächtnis über die Schritte hinweg beibehält, um wiederholte Schleifen zu vermeiden und fundierte Entscheidungen zu treffen. - **Umgang mit Fehlern und Selbstkorrektur:** Erforschung der robusten Selbstkorrekturmechanismen des Systems, einschließlich Iteration und erneuter Abfrage, Nutzung von Diagnosetools und Rückgriff auf menschliche Aufsicht. - **Grenzen der Eigenständigkeit:** Verständnis der Einschränkungen von Agentic RAG mit Schwerpunkt auf domänenspezifischer Autonomie, Abhängigkeit von Infrastruktur und Einhaltung von Richtlinien. - **Praktische Anwendungsfälle und Nutzen:** Identifikation von Szenarien, in denen Agentic RAG besonders effektiv ist, wie z. B. in korrektheitsorientierten Umgebungen, bei komplexen Datenbankinteraktionen und in erweiterten Workflows. - **Governance, Transparenz und Vertrauen:** Lernen, wie wichtig Governance und Transparenz sind, einschließlich erklärbarer Argumentation, Kontrolle von Verzerrungen und menschlicher Aufsicht. ## Was ist Agentic RAG? Agentic Retrieval-Augmented Generation (Agentic RAG) ist ein aufstrebendes KI-Paradigma, bei dem große Sprachmodelle (LLMs) eigenständig ihre nächsten Schritte planen, während sie Informationen aus externen Quellen abrufen. Im Gegensatz zu statischen Mustern des Abrufens und Lesens umfasst Agentic RAG iterative Aufrufe an das LLM, unterbrochen durch Werkzeug- oder Funktionsaufrufe und strukturierte Ausgaben. Das System bewertet Ergebnisse, verfeinert Abfragen, ruft bei Bedarf zusätzliche Werkzeuge auf und setzt diesen Zyklus fort, bis eine zufriedenstellende Lösung erreicht ist. Dieser iterative "Maker-Checker"-Ansatz verbessert die Korrektheit, behandelt fehlerhafte Abfragen und sorgt für qualitativ hochwertige Ergebnisse. Das System übernimmt aktiv seinen Denkprozess, indem es fehlgeschlagene Abfragen neu schreibt, verschiedene Abrufmethoden wählt und mehrere Werkzeuge integriert—wie etwa Vektorsuche in Azure AI Search, SQL-Datenbanken oder benutzerdefinierte APIs—bevor es seine Antwort finalisiert. Das unterscheidende Merkmal eines agentischen Systems ist seine Fähigkeit, seinen Denkprozess eigenständig zu steuern. Traditionelle RAG-Implementierungen verlassen sich auf vordefinierte Pfade, während ein agentisches System die Abfolge der Schritte autonom auf Basis der Qualität der gefundenen Informationen bestimmt. ## Definition von Agentic Retrieval-Augmented Generation (Agentic RAG) Agentic Retrieval-Augmented Generation (Agentic RAG) ist ein aufstrebendes Paradigma in der KI-Entwicklung, bei dem LLMs nicht nur Informationen aus externen Datenquellen abrufen, sondern auch eigenständig ihre nächsten Schritte planen. Im Gegensatz zu statischen Abruf-Lese-Mustern oder sorgfältig geskripteten Prompt-Sequenzen umfasst Agentic RAG einen iterativen Zyklus von LLM-Aufrufen, unterbrochen durch Werkzeug- oder Funktionsaufrufe und strukturierte Ausgaben. Das System bewertet bei jedem Schritt die erzielten Ergebnisse, entscheidet, ob es seine Abfragen verfeinern muss, ruft bei Bedarf zusätzliche Werkzeuge auf und setzt diesen Zyklus fort, bis es eine zufriedenstellende Lösung erreicht. Dieser iterative "Maker-Checker"-Ansatz ist darauf ausgelegt, die Korrektheit zu verbessern, fehlerhafte Abfragen an strukturierte Datenbanken (z. B. NL2SQL) zu behandeln und ausgewogene, qualitativ hochwertige Ergebnisse sicherzustellen. Anstatt sich ausschließlich auf sorgfältig entwickelte Prompt-Ketten zu verlassen, übernimmt das System aktiv seinen Denkprozess. Es kann fehlgeschlagene Abfragen neu schreiben, verschiedene Abrufmethoden wählen und mehrere Werkzeuge integrieren—wie etwa Vektorsuche in Azure AI Search, SQL-Datenbanken oder benutzerdefinierte APIs—bevor es seine Antwort finalisiert. Dies macht komplexe Orchestrierungsrahmen überflüssig. Stattdessen kann eine relativ einfache Schleife aus „LLM-Aufruf → Werkzeugnutzung → LLM-Aufruf → …“ zu ausgefeilten und fundierten Ergebnissen führen. ![Agentic RAG Core Loop](../../../05-agentic-rag/images/agentic-rag-core-loop.png) ## Den Denkprozess übernehmen Das unterscheidende Merkmal, das ein System "agentisch" macht, ist seine Fähigkeit, seinen Denkprozess eigenständig zu steuern. Traditionelle RAG-Implementierungen hängen oft davon ab, dass Menschen einen Pfad für das Modell vordefinieren: eine Denkweise, die festlegt, was wann abgerufen werden soll. Ein wirklich agentisches System hingegen entscheidet intern, wie es das Problem angeht. Es führt nicht einfach ein Skript aus, sondern bestimmt autonom die Abfolge der Schritte auf Basis der Qualität der gefundenen Informationen. Zum Beispiel: Wenn das System aufgefordert wird, eine Produktstartstrategie zu erstellen, verlässt es sich nicht nur auf einen Prompt, der den gesamten Forschungs- und Entscheidungsworkflow vorgibt. Stattdessen entscheidet das agentische Modell eigenständig: 1. Aktuelle Markttrendberichte mit Bing Web Grounding abzurufen. 2. Relevante Wettbewerbsdaten mit Azure AI Search zu identifizieren. 3. Historische interne Verkaufsmetriken mit Azure SQL Database zu korrelieren. 4. Die Erkenntnisse zu einer kohärenten Strategie zu synthetisieren, orchestriert über Azure OpenAI Service. 5. Die Strategie auf Lücken oder Inkonsistenzen zu überprüfen und gegebenenfalls eine weitere Abrufrunde einzuleiten. All diese Schritte—Abfragen verfeinern, Quellen auswählen, iterieren, bis eine zufriedenstellende Antwort erreicht ist—werden vom Modell entschieden, nicht von einem Menschen vorgegeben. ## Iterative Schleifen, Werkzeugintegration und Gedächtnis ![Tool Integration Architecture](../../../05-agentic-rag/images/tool-integration.png) Ein agentisches System basiert auf einem iterativen Interaktionsmuster: - **Erster Aufruf:** Das Ziel des Nutzers (auch User Prompt genannt) wird dem LLM präsentiert. - **Werkzeugaufruf:** Wenn das Modell feststellt, dass Informationen fehlen oder Anweisungen unklar sind, wählt es ein Werkzeug oder eine Abrufmethode—wie eine Abfrage an eine Vektordatenbank (z. B. Azure AI Search Hybrid Search über private Daten) oder einen strukturierten SQL-Aufruf—um mehr Kontext zu sammeln. - **Bewertung & Verfeinerung:** Nach Überprüfung der zurückgegebenen Daten entscheidet das Modell, ob die Informationen ausreichen. Falls nicht, verfeinert es die Abfrage, versucht ein anderes Werkzeug oder passt seinen Ansatz an. - **Wiederholen, bis zufriedenstellend:** Dieser Zyklus wird fortgesetzt, bis das Modell feststellt, dass es genügend Klarheit und Beweise hat, um eine fundierte Antwort zu liefern. - **Gedächtnis & Zustand:** Da das System den Zustand und das Gedächtnis über die Schritte hinweg beibehält, kann es sich an vorherige Versuche und deren Ergebnisse erinnern, wiederholte Schleifen vermeiden und fundiertere Entscheidungen treffen, während es voranschreitet. Im Laufe der Zeit entsteht so ein Gefühl des fortschreitenden Verständnisses, das es dem Modell ermöglicht, komplexe, mehrstufige Aufgaben zu bewältigen, ohne dass ein Mensch ständig eingreifen oder den Prompt umformen muss. ## Umgang mit Fehlern und Selbstkorrektur Die Eigenständigkeit von Agentic RAG umfasst auch robuste Selbstkorrekturmechanismen. Wenn das System auf Sackgassen stößt—wie das Abrufen irrelevanter Dokumente oder das Auftreten fehlerhafter Abfragen—kann es: - **Iterieren und erneut abfragen:** Anstatt minderwertige Antworten zurückzugeben, versucht das Modell neue Suchstrategien, schreibt Datenbankabfragen um oder prüft alternative Datensätze. - **Diagnosetools nutzen:** Das System kann zusätzliche Funktionen aufrufen, die ihm helfen, seine Denkschritte zu debuggen oder die Korrektheit der abgerufenen Daten zu bestätigen. Tools wie Azure AI Tracing sind entscheidend, um eine robuste Beobachtbarkeit und Überwachung zu ermöglichen. - **Auf menschliche Aufsicht zurückgreifen:** In hochkritischen oder wiederholt scheiternden Szenarien könnte das Modell Unsicherheit signalisieren und menschliche Anleitung anfordern. Sobald der Mensch korrigierendes Feedback gibt, kann das Modell diese Lektion für die Zukunft übernehmen. Dieser iterative und dynamische Ansatz ermöglicht es dem Modell, sich kontinuierlich zu verbessern und sicherzustellen, dass es nicht nur ein Einweg-System ist, sondern eines, das aus seinen Fehlern innerhalb einer Sitzung lernt. ![Self Correction Mechanism](../../../05-agentic-rag/images/self-correction.png) ## Grenzen der Eigenständigkeit Trotz seiner Eigenständigkeit innerhalb einer Aufgabe ist Agentic RAG nicht mit einer allgemeinen künstlichen Intelligenz (Artificial General Intelligence) gleichzusetzen. Seine "agentischen" Fähigkeiten sind auf die von menschlichen Entwicklern bereitgestellten Werkzeuge, Datenquellen und Richtlinien beschränkt. Es kann keine eigenen Werkzeuge erfinden oder über die gesetzten Domänengrenzen hinausgehen. Stattdessen glänzt es darin, die vorhandenen Ressourcen dynamisch zu orchestrieren. Wichtige Unterschiede zu fortgeschritteneren KI-Formen umfassen: 1. **Domänenspezifische Autonomie:** Agentic RAG-Systeme konzentrieren sich darauf, benutzerdefinierte Ziele innerhalb einer bekannten Domäne zu erreichen, indem sie Strategien wie Abfrageumformung oder Werkzeugauswahl anwenden, um Ergebnisse zu verbessern. 2. **Infrastrukturabhängigkeit:** Die Fähigkeiten des Systems hängen von den von Entwicklern integrierten Werkzeugen und Daten ab. Es kann diese Grenzen ohne menschliches Eingreifen nicht überschreiten. 3. **Einhaltung von Richtlinien:** Ethische Richtlinien, Compliance-Regeln und Geschäftspolitiken bleiben von großer Bedeutung. Die Freiheit des Agenten ist immer durch Sicherheitsmaßnahmen und Überwachungsmechanismen eingeschränkt (hoffentlich?). ## Praktische Anwendungsfälle und Nutzen Agentic RAG glänzt in Szenarien, die iterative Verfeinerung und Präzision erfordern: 1. **Korrektheitsorientierte Umgebungen:** In Bereichen wie Compliance-Prüfungen, regulatorischer Analyse oder juristischer Recherche kann das agentische Modell Fakten wiederholt überprüfen, mehrere Quellen konsultieren und Abfragen umschreiben, bis es eine gründlich geprüfte Antwort liefert. 2. **Komplexe Datenbankinteraktionen:** Bei der Arbeit mit strukturierten Daten, bei denen Abfragen häufig scheitern oder angepasst werden müssen, kann das System eigenständig seine Abfragen mithilfe von Azure SQL oder Microsoft Fabric OneLake verfeinern, um sicherzustellen, dass die endgültige Abfrage mit der Benutzerabsicht übereinstimmt. 3. **Erweiterte Workflows:** Länger laufende Sitzungen können sich weiterentwickeln, wenn neue Informationen auftauchen. Agentic RAG kann kontinuierlich neue Daten integrieren und Strategien anpassen, während es mehr über den Problemraum lernt. ## Governance, Transparenz und Vertrauen Da diese Systeme eigenständiger in ihrer Argumentation werden, sind Governance und Transparenz von entscheidender Bedeutung: - **Erklärbare Argumentation:** Das Modell kann eine Prüfspur der getätigten Abfragen, der konsultierten Quellen und der Argumentationsschritte bereitstellen, die zu seiner Schlussfolgerung geführt haben. Tools wie Azure AI Content Safety und Azure AI Tracing / GenAIOps können helfen, Transparenz zu gewährleisten und Risiken zu minimieren. - **Kontrolle von Verzerrungen und ausgewogene Abrufe:** Entwickler können Abrufstrategien anpassen, um sicherzustellen, dass ausgewogene, repräsentative Datenquellen berücksichtigt werden, und regelmäßig Ausgaben überprüfen, um Verzerrungen oder unausgewogene Muster zu erkennen, unter Verwendung benutzerdefinierter Modelle für fortgeschrittene Datenwissenschaftsorganisationen mit Azure Machine Learning. - **Menschliche Aufsicht und Compliance:** Für sensible Aufgaben bleibt die menschliche Überprüfung unerlässlich. Agentic RAG ersetzt nicht das menschliche Urteilsvermögen bei kritischen Entscheidungen—es ergänzt es, indem es gründlicher geprüfte Optionen liefert. Werkzeuge, die einen klaren Aktionsverlauf aufzeichnen, sind unerlässlich. Ohne sie kann das Debuggen eines mehrstufigen Prozesses sehr schwierig sein. Siehe folgendes Beispiel von Literal AI (Unternehmen hinter Chainlit) für einen Agent-Lauf: ![AgentRunExample](../../../05-agentic-rag/images/AgentRunExample.png) ![AgentRunExample2](../../../05-agentic-rag/images/AgentRunExample2.png) ## Fazit Agentic RAG stellt eine natürliche Weiterentwicklung in der Art und Weise dar, wie KI-Systeme komplexe, datenintensive Aufgaben bewältigen. Durch die Einführung eines iterativen Interaktionsmusters, die autonome Auswahl von Werkzeugen und die Verfeinerung von Abfragen, bis ein qualitativ hochwertiges Ergebnis erzielt wird, geht das System über statisches Prompt-Following hinaus und wird zu einem anpassungsfähigen, kontextbewussten Entscheidungsträger. Obwohl es weiterhin durch menschlich definierte Infrastrukturen und ethische Richtlinien begrenzt ist, ermöglichen diese agentischen Fähigkeiten reichhaltigere, dynamischere und letztlich nützlichere KI-Interaktionen sowohl für Unternehmen als auch für Endbenutzer. ## Zusätzliche Ressourcen - Implementierung von Retrieval Augmented Generation (RAG) mit Azure OpenAI Service: Erfahre, wie du deine eigenen Daten mit dem Azure OpenAI Service nutzen kannst. [Dieses Microsoft Learn-Modul bietet eine umfassende Anleitung zur Implementierung von RAG](https://learn.microsoft.com/training/modules/use-own-data-azure-openai) - Evaluation generativer KI-Anwendungen mit Azure AI Foundry: Dieser Artikel behandelt die Bewertung und den Vergleich von Modellen anhand öffentlich verfügbarer Datensätze, einschließlich [Agentic AI-Anwendungen und RAG-Architekturen](https://learn.microsoft.com/azure/ai-studio/concepts/evaluation-approach-gen-ai) - [Was ist Agentic RAG | Weaviate](https://weaviate.io/blog/what-is-agentic-rag) - [Agentic RAG: Ein vollständiger Leitfaden zu Agent-Based Retrieval Augmented Generation – News von Generation RAG](https://ragaboutit.com/agentic-rag-a-complete-guide-to-agent-based-retrieval-augmented-generation/) - [Agentic RAG: Steigere dein RAG mit Abfrageumformung und Selbstabfrage! Hugging Face Open-Source AI Cookbook](https://huggingface.co/learn/cookbook/agent_rag) - [Agentische Ebenen zu RAG hinzufügen](https://youtu.be/aQ4yQXeB1Ss?si=2HUqBzHoeB5tR04U) - [Die Zukunft von Wissensassistenten: Jerry Liu](https://www.youtube.com/watch?v=zeAyuLc_f3Q&t=244s) - [Wie man Agentic RAG-Systeme baut](https://www.youtube.com/watch?v=AOSjiXP1jmQ) - [Verwendung des Azure AI Foundry Agent Service zur Skalierung deiner KI-Agenten](https://ignite.microsoft.com/sessions/BRK102?source=sessions) ### Wissenschaftliche Arbeiten - [2303.17651 Self-Refine: Iterative Refinement with Self-Feedback](https://arxiv.org/abs/2303.17651) - [2303.11366 Reflexion: Language Agents with Verbal Reinforcement Learning](https://arxiv.org/abs/2303.11366) - [2305.11738 CRITIC: Large Language Models Can Self-Correct with Tool-Interactive Critiquing](https://arxiv.org/abs/2305.11738) ``` **Haftungsausschluss**: Dieses Dokument wurde mit KI-basierten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, beachten Sie bitte, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die durch die Nutzung dieser Übersetzung entstehen.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/05-agentic-rag/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/05-agentic-rag/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 17983 }
```markdown # Vertrauenswürdige KI-Agenten entwickeln ## Einführung In dieser Lektion werden folgende Themen behandelt: - Wie man sichere und effektive KI-Agenten erstellt und bereitstellt. - Wichtige Sicherheitsaspekte bei der Entwicklung von KI-Agenten. - Wie man Datenschutz und Privatsphäre der Nutzer bei der Entwicklung von KI-Agenten sicherstellt. ## Lernziele Nach Abschluss dieser Lektion wirst du in der Lage sein: - Risiken bei der Erstellung von KI-Agenten zu erkennen und zu mindern. - Sicherheitsmaßnahmen zu implementieren, um sicherzustellen, dass Daten und Zugriffe ordnungsgemäß verwaltet werden. - KI-Agenten zu erstellen, die den Datenschutz wahren und eine qualitativ hochwertige Nutzererfahrung bieten. ## Sicherheit Beginnen wir mit dem Aufbau sicherer agentenbasierter Anwendungen. Sicherheit bedeutet, dass der KI-Agent wie vorgesehen funktioniert. Als Entwickler von agentenbasierten Anwendungen haben wir Methoden und Werkzeuge, um die Sicherheit zu maximieren: ### Aufbau eines Meta-Prompting-Systems Wenn du jemals eine KI-Anwendung mit großen Sprachmodellen (LLMs) entwickelt hast, weißt du, wie wichtig es ist, ein robustes System-Prompt oder eine Systemnachricht zu entwerfen. Diese Prompts legen die Meta-Regeln, Anweisungen und Richtlinien fest, wie das LLM mit dem Nutzer und den Daten interagieren soll. Für KI-Agenten ist das System-Prompt noch wichtiger, da die KI-Agenten hochspezifische Anweisungen benötigen, um die Aufgaben zu erfüllen, die wir für sie entworfen haben. Um skalierbare System-Prompts zu erstellen, können wir ein Meta-Prompting-System verwenden, um einen oder mehrere Agenten in unserer Anwendung zu erstellen: ![Aufbau eines Meta-Prompting-Systems](../../../translated_images/building-a-metaprompting-system.aa7d6de2100b0ef48c3e1926dab6903026b22fc9d27fc4327162fbbb9caf960f.de.png) #### Schritt 1: Erstelle ein Meta- oder Template-Prompt Das Meta-Prompt wird von einem LLM verwendet, um die System-Prompts für die Agenten zu generieren, die wir erstellen. Wir entwerfen es als Vorlage, damit wir bei Bedarf effizient mehrere Agenten erstellen können. Hier ist ein Beispiel für ein Meta-Prompt, das wir dem LLM geben würden: ```plaintext You are an expert at creating AI agent assitants. You will be provided a company name, role, responsibilites and other information that you will use to provide a system prompt for. To create the system prompt, be descriptive as possible and provide a structure that a system using an LLM can better understand the role and responsibilites of the AI assistant. ``` #### Schritt 2: Erstelle ein Basis-Prompt Der nächste Schritt besteht darin, ein Basis-Prompt zu erstellen, das den KI-Agenten beschreibt. Du solltest die Rolle des Agenten, die Aufgaben, die er erledigen soll, und andere Verantwortlichkeiten des Agenten einbeziehen. Hier ist ein Beispiel: ```plaintext You are a travel agent for Contoso Travel with that is great at booking flights for customers. To help customers you can perform the following tasks: lookup available flights, book flights, ask for preferences in seating and times for flights, cancel any previously booked flights and alert customers on any delays or cancellations of flights. ``` #### Schritt 3: Basis-Prompt dem LLM bereitstellen Nun können wir dieses Prompt optimieren, indem wir das Meta-Prompt als System-Prompt und unser Basis-Prompt verwenden. Das Ergebnis ist ein besser gestaltetes Prompt, das unsere KI-Agenten besser leitet: ```markdown **Company Name:** Contoso Travel **Role:** Travel Agent Assistant **Objective:** You are an AI-powered travel agent assistant for Contoso Travel, specializing in booking flights and providing exceptional customer service. Your main goal is to assist customers in finding, booking, and managing their flights, all while ensuring that their preferences and needs are met efficiently. **Key Responsibilities:** 1. **Flight Lookup:** - Assist customers in searching for available flights based on their specified destination, dates, and any other relevant preferences. - Provide a list of options, including flight times, airlines, layovers, and pricing. 2. **Flight Booking:** - Facilitate the booking of flights for customers, ensuring that all details are correctly entered into the system. - Confirm bookings and provide customers with their itinerary, including confirmation numbers and any other pertinent information. 3. **Customer Preference Inquiry:** - Actively ask customers for their preferences regarding seating (e.g., aisle, window, extra legroom) and preferred times for flights (e.g., morning, afternoon, evening). - Record these preferences for future reference and tailor suggestions accordingly. 4. **Flight Cancellation:** - Assist customers in canceling previously booked flights if needed, following company policies and procedures. - Notify customers of any necessary refunds or additional steps that may be required for cancellations. 5. **Flight Monitoring:** - Monitor the status of booked flights and alert customers in real-time about any delays, cancellations, or changes to their flight schedule. - Provide updates through preferred communication channels (e.g., email, SMS) as needed. **Tone and Style:** - Maintain a friendly, professional, and approachable demeanor in all interactions with customers. - Ensure that all communication is clear, informative, and tailored to the customer's specific needs and inquiries. **User Interaction Instructions:** - Respond to customer queries promptly and accurately. - Use a conversational style while ensuring professionalism. - Prioritize customer satisfaction by being attentive, empathetic, and proactive in all assistance provided. **Additional Notes:** - Stay updated on any changes to airline policies, travel restrictions, and other relevant information that could impact flight bookings and customer experience. - Use clear and concise language to explain options and processes, avoiding jargon where possible for better customer understanding. This AI assistant is designed to streamline the flight booking process for customers of Contoso Travel, ensuring that all their travel needs are met efficiently and effectively. ``` #### Schritt 4: Iterieren und Verbessern Der Wert dieses Meta-Prompting-Systems liegt darin, die Erstellung von Prompts für mehrere Agenten zu vereinfachen und die Prompts im Laufe der Zeit zu verbessern. Es ist selten, dass ein Prompt beim ersten Mal für den gesamten Anwendungsfall funktioniert. Kleine Anpassungen und Verbesserungen vorzunehmen, indem man das Basis-Prompt ändert und es durch das System laufen lässt, ermöglicht es, Ergebnisse zu vergleichen und zu bewerten. ## Bedrohungen verstehen Um vertrauenswürdige KI-Agenten zu entwickeln, ist es wichtig, die Risiken und Bedrohungen für deinen KI-Agenten zu verstehen und zu mindern. Schauen wir uns einige der verschiedenen Bedrohungen für KI-Agenten an und wie du besser planen und dich darauf vorbereiten kannst. ![Bedrohungen verstehen](../../../translated_images/understanding-threats.f8fbe6fe11e025b3085fc91e82d975937ad1d672260a2aeed40458aa41798d0e.de.png) ### Aufgaben und Anweisungen **Beschreibung:** Angreifer versuchen, die Anweisungen oder Ziele des KI-Agenten durch Eingaben oder Manipulationen zu ändern. **Abwehrmaßnahmen**: Führe Validierungsprüfungen und Eingabefilter durch, um potenziell gefährliche Prompts zu erkennen, bevor sie vom KI-Agenten verarbeitet werden. Da diese Angriffe in der Regel häufige Interaktionen mit dem Agenten erfordern, ist die Begrenzung der Anzahl der Gesprächsrunden eine weitere Möglichkeit, diese Angriffe zu verhindern. ### Zugriff auf kritische Systeme **Beschreibung**: Wenn ein KI-Agent Zugriff auf Systeme und Dienste hat, die sensible Daten speichern, können Angreifer die Kommunikation zwischen dem Agenten und diesen Diensten kompromittieren. Dies können direkte Angriffe oder indirekte Versuche sein, Informationen über diese Systeme durch den Agenten zu erlangen. **Abwehrmaßnahmen**: KI-Agenten sollten nur bei Bedarf Zugriff auf Systeme haben, um solche Angriffe zu verhindern. Die Kommunikation zwischen Agent und System sollte ebenfalls sicher sein. Die Implementierung von Authentifizierung und Zugriffskontrollen ist eine weitere Möglichkeit, diese Informationen zu schützen. ### Überlastung von Ressourcen und Diensten **Beschreibung:** KI-Agenten können auf verschiedene Tools und Dienste zugreifen, um Aufgaben zu erledigen. Angreifer können diese Fähigkeit nutzen, um diese Dienste durch eine hohe Anzahl von Anfragen über den KI-Agenten anzugreifen, was zu Systemausfällen oder hohen Kosten führen kann. **Abwehrmaßnahmen:** Implementiere Richtlinien, um die Anzahl der Anfragen, die ein KI-Agent an einen Dienst senden kann, zu begrenzen. Die Begrenzung der Anzahl der Gesprächsrunden und Anfragen an deinen KI-Agenten ist eine weitere Möglichkeit, solche Angriffe zu verhindern. ### Manipulation der Wissensbasis **Beschreibung:** Dieser Angriff zielt nicht direkt auf den KI-Agenten ab, sondern auf die Wissensbasis und andere Dienste, die der KI-Agent nutzen wird. Dies könnte die Korruption von Daten oder Informationen beinhalten, die der KI-Agent zur Erfüllung einer Aufgabe verwendet, was zu voreingenommenen oder unbeabsichtigten Antworten für den Nutzer führen kann. **Abwehrmaßnahmen:** Führe regelmäßige Überprüfungen der Daten durch, die der KI-Agent in seinen Arbeitsabläufen verwenden wird. Stelle sicher, dass der Zugriff auf diese Daten sicher ist und nur von vertrauenswürdigen Personen geändert werden kann, um solche Angriffe zu vermeiden. ### Kaskadierende Fehler **Beschreibung:** KI-Agenten greifen auf verschiedene Tools und Dienste zu, um Aufgaben zu erledigen. Fehler, die durch Angreifer verursacht werden, können zu Ausfällen anderer Systeme führen, mit denen der KI-Agent verbunden ist, wodurch der Angriff weiter verbreitet und schwerer zu beheben wird. **Abwehrmaßnahmen**: Eine Möglichkeit, dies zu vermeiden, besteht darin, den KI-Agenten in einer begrenzten Umgebung wie einem Docker-Container auszuführen, um direkte Systemangriffe zu verhindern. Das Erstellen von Fallback-Mechanismen und Wiederholungslogik, wenn bestimmte Systeme mit einem Fehler reagieren, ist eine weitere Möglichkeit, größere Systemausfälle zu verhindern. ## Mensch in der Schleife (Human-in-the-Loop) Eine weitere effektive Methode, um vertrauenswürdige KI-Agentensysteme zu entwickeln, ist die Nutzung eines Human-in-the-Loop-Ansatzes. Dies schafft einen Ablauf, bei dem Nutzer während der Ausführung Feedback an die Agenten geben können. Nutzer agieren im Wesentlichen als Agent in einem Multi-Agenten-System und können den laufenden Prozess genehmigen oder abbrechen. ![Mensch in der Schleife](../../../translated_images/human-in-the-loop.e9edbe8f6d42041b4213421410823250aa750fe8bdba5601d69ed46f3ff6489d.de.png) Hier ist ein Code-Snippet, das AutoGen verwendet, um zu zeigen, wie dieses Konzept implementiert wird: ```python # Create the agents. model_client = OpenAIChatCompletionClient(model="gpt-4o-mini") assistant = AssistantAgent("assistant", model_client=model_client) user_proxy = UserProxyAgent("user_proxy", input_func=input) # Use input() to get user input from console. # Create the termination condition which will end the conversation when the user says "APPROVE". termination = TextMentionTermination("APPROVE") # Create the team. team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination) # Run the conversation and stream to the console. stream = team.run_stream(task="Write a 4-line poem about the ocean.") # Use asyncio.run(...) when running in a script. await Console(stream) ``` ``` **Haftungsausschluss**: Dieses Dokument wurde mit KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die aus der Nutzung dieser Übersetzung resultieren.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/06-building-trustworthy-agents/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/06-building-trustworthy-agents/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 12378 }
# Planungsdesign ## Einführung In dieser Lektion behandeln wir: * Wie man ein klares übergeordnetes Ziel definiert und eine komplexe Aufgabe in überschaubare Teilaufgaben aufteilt. * Die Nutzung strukturierter Ausgaben für zuverlässigere und maschinenlesbare Antworten. * Die Anwendung eines ereignisgesteuerten Ansatzes zur Bewältigung dynamischer Aufgaben und unerwarteter Eingaben. ## Lernziele Nach Abschluss dieser Lektion wirst du verstehen: * Wie man ein übergeordnetes Ziel für einen KI-Agenten definiert, sodass dieser genau weiß, was erreicht werden soll. * Wie man eine komplexe Aufgabe in handhabbare Teilaufgaben zerlegt und diese in eine logische Reihenfolge bringt. * Wie man Agenten mit den richtigen Werkzeugen (z. B. Suchtools oder Datenanalysetools) ausstattet, entscheidet, wann und wie diese verwendet werden, und unerwartete Situationen bewältigt. * Wie man Ergebnisse von Teilaufgaben bewertet, die Leistung misst und Maßnahmen iteriert, um das Endergebnis zu verbessern. ## Das übergeordnete Ziel definieren und eine Aufgabe aufteilen ![Ziele und Aufgaben definieren](../../../translated_images/defining-goals-tasks.dcc1181bbdb194704ae0fb3363371562949e8b03fd2fadc256218aaadf84a9f4.de.png) Die meisten Aufgaben in der realen Welt sind zu komplex, um sie in einem einzigen Schritt zu lösen. Ein KI-Agent benötigt ein prägnantes Ziel, um seine Planung und Aktionen zu leiten. Betrachten wir beispielsweise das Ziel: "Erstelle einen 3-tägigen Reiseplan." Auch wenn es einfach formuliert ist, benötigt es dennoch Verfeinerung. Je klarer das Ziel definiert ist, desto besser können der Agent (und eventuelle menschliche Mitarbeiter) sich darauf konzentrieren, das richtige Ergebnis zu erzielen, z. B. einen umfassenden Reiseplan mit Flugoptionen, Hotelempfehlungen und Vorschlägen für Aktivitäten. ### Aufgabenzerlegung Große oder komplexe Aufgaben werden überschaubarer, wenn sie in kleinere, zielorientierte Teilaufgaben aufgeteilt werden. Für das Beispiel des Reiseplans könnte man das Ziel wie folgt zerlegen: * Flugbuchung * Hotelbuchung * Mietwagen * Personalisierung Jede Teilaufgabe kann dann von spezialisierten Agenten oder Prozessen bearbeitet werden. Ein Agent könnte sich beispielsweise auf die Suche nach den besten Flugangeboten spezialisieren, ein anderer auf Hotelbuchungen usw. Ein koordinierender oder „nachgelagerter“ Agent kann diese Ergebnisse dann zu einem zusammenhängenden Reiseplan für den Endnutzer zusammenfügen. Dieser modulare Ansatz ermöglicht auch schrittweise Verbesserungen. Zum Beispiel könnte man spezialisierte Agenten für Restaurantempfehlungen oder lokale Aktivitätsvorschläge hinzufügen und den Reiseplan im Laufe der Zeit weiter verfeinern. ### Strukturierte Ausgabe Große Sprachmodelle (LLMs) können strukturierte Ausgaben (z. B. JSON) generieren, die von nachgelagerten Agenten oder Diensten leichter analysiert und verarbeitet werden können. Dies ist besonders nützlich in einem Multi-Agenten-Kontext, in dem Aufgaben nach der Planungsausgabe bearbeitet werden. Sieh dir diesen [Blogpost](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/cookbook/structured-output-agent.html) für einen kurzen Überblick an. Im Folgenden ein Beispiel eines Python-Snippets, das zeigt, wie ein einfacher Planungsagent ein Ziel in Teilaufgaben zerlegt und einen strukturierten Plan erstellt: ### Planungsagent mit Multi-Agenten-Orchestrierung In diesem Beispiel erhält ein Semantic Router Agent eine Benutzeranfrage (z. B. "Ich brauche einen Hotelplan für meine Reise."). Der Planer: * Erhält den Hotelplan: Der Planer nimmt die Nachricht des Benutzers entgegen und erstellt basierend auf einem System-Prompt (einschließlich Details zu verfügbaren Agenten) einen strukturierten Reiseplan. * Listet Agenten und deren Werkzeuge auf: Das Agentenregister enthält eine Liste von Agenten (z. B. für Flug, Hotel, Mietwagen und Aktivitäten) zusammen mit den Funktionen oder Tools, die sie anbieten. * Leitet den Plan an die entsprechenden Agenten weiter: Abhängig von der Anzahl der Teilaufgaben sendet der Planer die Nachricht entweder direkt an einen spezialisierten Agenten (für Einzelaufgabenszenarien) oder koordiniert über einen Gruppenchat-Manager für die Zusammenarbeit mehrerer Agenten. * Fasst das Ergebnis zusammen: Schließlich fasst der Planer den erstellten Plan zur besseren Übersicht zusammen. Im Folgenden ein Python-Codebeispiel, das diese Schritte illustriert: ```python from pydantic import BaseModel from enum import Enum from typing import List, Optional, Union class AgentEnum(str, Enum): FlightBooking = "flight_booking" HotelBooking = "hotel_booking" CarRental = "car_rental" ActivitiesBooking = "activities_booking" DestinationInfo = "destination_info" DefaultAgent = "default_agent" GroupChatManager = "group_chat_manager" # Travel SubTask Model class TravelSubTask(BaseModel): task_details: str assigned_agent: AgentEnum # we want to assign the task to the agent class TravelPlan(BaseModel): main_task: str subtasks: List[TravelSubTask] is_greeting: bool import json import os from typing import Optional from autogen_core.models import UserMessage, SystemMessage, AssistantMessage from autogen_ext.models.openai import AzureOpenAIChatCompletionClient # Create the client with type-checked environment variables client = AzureOpenAIChatCompletionClient( azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"), model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"), api_version=os.getenv("AZURE_OPENAI_API_VERSION"), azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), ) from pprint import pprint # Define the user message messages = [ SystemMessage(content="""You are an planner agent. Your job is to decide which agents to run based on the user's request. Below are the available agents specialised in different tasks: - FlightBooking: For booking flights and providing flight information - HotelBooking: For booking hotels and providing hotel information - CarRental: For booking cars and providing car rental information - ActivitiesBooking: For booking activities and providing activity information - DestinationInfo: For providing information about destinations - DefaultAgent: For handling general requests""", source="system"), UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"), ] response = await client.create(messages=messages, extra_create_args={"response_format": TravelPlan}) # Ensure the response content is a valid JSON string before loading it response_content: Optional[str] = response.content if isinstance(response.content, str) else None if response_content is None: raise ValueError("Response content is not a valid JSON string") # Print the response content after loading it as JSON pprint(json.loads(response_content)) ``` Im Anschluss daran zeigt die Ausgabe des obigen Codes, wie diese strukturierte Ausgabe an `assigned_agent` weitergeleitet und der Reiseplan für den Endnutzer zusammengefasst werden kann: ```json { "is_greeting": "False", "main_task": "Plan a family trip from Singapore to Melbourne.", "subtasks": [ { "assigned_agent": "flight_booking", "task_details": "Book round-trip flights from Singapore to Melbourne." }, { "assigned_agent": "hotel_booking", "task_details": "Find family-friendly hotels in Melbourne." }, { "assigned_agent": "car_rental", "task_details": "Arrange a car rental suitable for a family of four in Melbourne." }, { "assigned_agent": "activities_booking", "task_details": "List family-friendly activities in Melbourne." }, { "assigned_agent": "destination_info", "task_details": "Provide information about Melbourne as a travel destination." } ] } ``` Ein Beispiel-Notebook mit dem obigen Codebeispiel ist [hier](../../../07-planning-design/code_samples/07-autogen.ipynb) verfügbar. ### Iterative Planung Einige Aufgaben erfordern einen iterativen Prozess oder eine Neuplanung, bei dem das Ergebnis einer Teilaufgabe die nächste beeinflusst. Beispielsweise könnte der Agent, wenn er beim Buchen von Flügen ein unerwartetes Datenformat entdeckt, seine Strategie anpassen müssen, bevor er mit der Hotelbuchung fortfährt. Auch Benutzerfeedback (z. B. wenn ein Mensch entscheidet, dass er einen früheren Flug bevorzugt) kann eine teilweise Neuplanung auslösen. Dieser dynamische, iterative Ansatz stellt sicher, dass die endgültige Lösung mit den realen Einschränkungen und den sich ändernden Benutzerpräferenzen übereinstimmt. Beispiel-Code: ```python from autogen_core.models import UserMessage, SystemMessage, AssistantMessage #.. same as previous code and pass on the user history, current plan messages = [ SystemMessage(content="""You are a planner agent to optimize the Your job is to decide which agents to run based on the user's request. Below are the available agents specialised in different tasks: - FlightBooking: For booking flights and providing flight information - HotelBooking: For booking hotels and providing hotel information - CarRental: For booking cars and providing car rental information - ActivitiesBooking: For booking activities and providing activity information - DestinationInfo: For providing information about destinations - DefaultAgent: For handling general requests""", source="system"), UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melboune", source="user"), AssistantMessage(content=f"Previous travel plan - {TravelPlan}", source="assistant") ] # .. re-plan and send the tasks to respective agents ``` Für eine umfassendere Planung lies dir den Magnetic One [Blogpost](https://www.microsoft.com/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks) durch, der die Lösung komplexer Aufgaben beschreibt. ## Zusammenfassung In diesem Artikel haben wir ein Beispiel dafür betrachtet, wie man einen Planer erstellen kann, der dynamisch die verfügbaren definierten Agenten auswählt. Die Ausgabe des Planers zerlegt die Aufgaben und weist sie den Agenten zu, damit sie ausgeführt werden können. Es wird davon ausgegangen, dass die Agenten Zugriff auf die Funktionen/Tools haben, die für die Ausführung der Aufgabe erforderlich sind. Zusätzlich zu den Agenten kannst du andere Muster wie Reflexion, Zusammenfassung oder Round-Robin-Chat einbinden, um die Lösung weiter anzupassen. ## Zusätzliche Ressourcen * Der Einsatz von o1-Reasoning-Modellen hat sich bei der Planung komplexer Aufgaben als äußerst fortschrittlich erwiesen – TODO: Beispiel teilen? * Autogen Magnetic One – Ein generalistisches Multi-Agenten-System zur Lösung komplexer Aufgaben, das beeindruckende Ergebnisse bei mehreren anspruchsvollen agentischen Benchmarks erzielt hat. Referenz: [autogen-magentic-one](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-magentic-one). In dieser Implementierung erstellt der Orchestrator einen aufgabenspezifischen Plan und delegiert diese Aufgaben an die verfügbaren Agenten. Neben der Planung verwendet der Orchestrator auch einen Mechanismus zur Fortschrittsüberwachung und passt den Plan bei Bedarf an. **Haftungsausschluss**: Dieses Dokument wurde mit KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die aus der Nutzung dieser Übersetzung entstehen.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/07-planning-design/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/07-planning-design/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 12164 }
# Multi-Agent-Designmuster Sobald Sie an einem Projekt arbeiten, das mehrere Agenten umfasst, müssen Sie das Multi-Agent-Designmuster in Betracht ziehen. Es ist jedoch nicht sofort ersichtlich, wann der Wechsel zu mehreren Agenten sinnvoll ist und welche Vorteile dies bietet. ## Einführung In dieser Lektion wollen wir die folgenden Fragen beantworten: - Für welche Szenarien sind Multi-Agent-Systeme geeignet? - Welche Vorteile bieten Multi-Agent-Systeme gegenüber einem einzigen Agenten, der mehrere Aufgaben übernimmt? - Was sind die Bausteine zur Implementierung des Multi-Agent-Designmusters? - Wie können wir nachvollziehen, wie die verschiedenen Agenten miteinander interagieren? ## Lernziele Nach dieser Lektion sollten Sie in der Lage sein: - Szenarien zu identifizieren, in denen Multi-Agent-Systeme anwendbar sind. - Die Vorteile von Multi-Agent-Systemen gegenüber einem einzelnen Agenten zu erkennen. - Die Bausteine zur Implementierung des Multi-Agent-Designmusters zu verstehen. Was ist der größere Zusammenhang? *Multi-Agenten sind ein Designmuster, das es mehreren Agenten ermöglicht, zusammenzuarbeiten, um ein gemeinsames Ziel zu erreichen.* Dieses Muster wird in verschiedenen Bereichen häufig verwendet, darunter Robotik, autonome Systeme und verteiltes Rechnen. ## Szenarien, in denen Multi-Agent-Systeme anwendbar sind Welche Szenarien eignen sich also gut für den Einsatz von Multi-Agenten? Die Antwort lautet, dass es viele Szenarien gibt, in denen der Einsatz mehrerer Agenten von Vorteil ist, insbesondere in den folgenden Fällen: - **Hohe Arbeitslasten**: Große Arbeitslasten können in kleinere Aufgaben aufgeteilt und verschiedenen Agenten zugewiesen werden, wodurch parallele Verarbeitung und schnellere Fertigstellung ermöglicht werden. Ein Beispiel hierfür ist die Verarbeitung großer Datenmengen. - **Komplexe Aufgaben**: Komplexe Aufgaben können, ähnlich wie große Arbeitslasten, in kleinere Teilaufgaben zerlegt und verschiedenen Agenten zugewiesen werden, die jeweils auf einen spezifischen Aspekt der Aufgabe spezialisiert sind. Ein gutes Beispiel hierfür sind autonome Fahrzeuge, bei denen verschiedene Agenten für Navigation, Hinderniserkennung und Kommunikation mit anderen Fahrzeugen zuständig sind. - **Vielfältige Expertise**: Unterschiedliche Agenten können über unterschiedliche Fachkenntnisse verfügen, wodurch sie verschiedene Aspekte einer Aufgabe effektiver bewältigen können als ein einzelner Agent. Ein Beispiel hierfür ist der Gesundheitsbereich, in dem Agenten Diagnosen, Behandlungspläne und Patientenüberwachung verwalten können. ## Vorteile von Multi-Agent-Systemen gegenüber einem einzelnen Agenten Ein System mit einem einzelnen Agenten könnte für einfache Aufgaben gut funktionieren, aber für komplexere Aufgaben bieten mehrere Agenten einige Vorteile: - **Spezialisierung**: Jeder Agent kann auf eine spezifische Aufgabe spezialisiert sein. Ein einzelner Agent ohne Spezialisierung könnte zwar alles erledigen, aber bei komplexen Aufgaben überfordert sein oder falsche Entscheidungen treffen. - **Skalierbarkeit**: Es ist einfacher, Systeme durch Hinzufügen weiterer Agenten zu skalieren, als einen einzelnen Agenten zu überlasten. - **Fehlertoleranz**: Wenn ein Agent ausfällt, können andere weiterhin funktionieren und die Zuverlässigkeit des Systems sicherstellen. Betrachten wir ein Beispiel: Eine Reise für einen Benutzer zu buchen. Ein System mit einem einzelnen Agenten müsste alle Aspekte des Buchungsprozesses übernehmen, von der Flugsuche bis zur Hotel- und Mietwagenbuchung. Um dies zu bewältigen, müsste der Agent Werkzeuge für alle diese Aufgaben besitzen. Dies könnte zu einem komplexen und monolithischen System führen, das schwer zu warten und zu skalieren ist. Ein Multi-Agent-System hingegen könnte spezialisierte Agenten für die Flugsuche, die Hotelbuchung und die Mietwagenbuchung haben. Dies würde das System modularer, wartungsfreundlicher und skalierbarer machen. Vergleichen Sie dies mit einem Reisebüro, das entweder von einem kleinen Familienbetrieb oder als Franchise geführt wird. Der Familienbetrieb hätte einen einzelnen Agenten, der alle Aspekte des Buchungsprozesses übernimmt, während das Franchise verschiedene Agenten für die unterschiedlichen Aufgaben hätte. ## Bausteine zur Implementierung des Multi-Agent-Designmusters Bevor Sie das Multi-Agent-Designmuster implementieren können, müssen Sie die Bausteine verstehen, aus denen das Muster besteht. Machen wir dies konkreter, indem wir erneut das Beispiel einer Reisebuchung betrachten. In diesem Fall wären die Bausteine: - **Agentenkommunikation**: Agenten für die Flugsuche, die Hotelbuchung und die Mietwagenbuchung müssen kommunizieren und Informationen über die Präferenzen und Einschränkungen des Benutzers austauschen. Sie müssen Protokolle und Methoden für diese Kommunikation festlegen. Konkret bedeutet dies, dass der Agent für die Flugsuche mit dem Agenten für die Hotelbuchung kommunizieren muss, um sicherzustellen, dass das Hotel für dieselben Daten wie der Flug gebucht wird. Das bedeutet, dass Sie entscheiden müssen, *welche Agenten Informationen austauschen und wie sie dies tun*. - **Koordinationsmechanismen**: Agenten müssen ihre Aktionen koordinieren, um sicherzustellen, dass die Präferenzen und Einschränkungen des Benutzers erfüllt werden. Eine Präferenz könnte sein, dass der Benutzer ein Hotel in der Nähe des Flughafens möchte, während eine Einschränkung sein könnte, dass Mietwagen nur am Flughafen verfügbar sind. Dies bedeutet, dass der Agent für die Hotelbuchung mit dem Agenten für die Mietwagenbuchung koordinieren muss, um die Präferenzen und Einschränkungen des Benutzers zu erfüllen. Sie müssen also entscheiden, *wie die Agenten ihre Aktionen koordinieren*. - **Agentenarchitektur**: Agenten müssen eine interne Struktur haben, um Entscheidungen zu treffen und aus ihren Interaktionen mit dem Benutzer zu lernen. Beispielsweise muss der Agent für die Flugsuche eine interne Struktur haben, um Entscheidungen darüber zu treffen, welche Flüge dem Benutzer empfohlen werden. Sie müssen also entscheiden, *wie die Agenten Entscheidungen treffen und aus ihren Interaktionen mit dem Benutzer lernen*. Ein Beispiel, wie ein Agent lernen und sich verbessern könnte, ist, dass der Agent für die Flugsuche ein maschinelles Lernmodell verwendet, um Flüge basierend auf den bisherigen Präferenzen des Benutzers zu empfehlen. - **Sichtbarkeit der Multi-Agent-Interaktionen**: Sie müssen nachvollziehen können, wie die verschiedenen Agenten miteinander interagieren. Dazu benötigen Sie Werkzeuge und Techniken, um die Aktivitäten und Interaktionen der Agenten zu verfolgen. Dies könnte in Form von Logging- und Überwachungstools, Visualisierungstools und Leistungsmetriken erfolgen. - **Multi-Agent-Muster**: Es gibt verschiedene Muster zur Implementierung von Multi-Agent-Systemen, wie zentrale, dezentrale und hybride Architekturen. Sie müssen das Muster auswählen, das am besten zu Ihrem Anwendungsfall passt. - **Mensch in der Schleife**: In den meisten Fällen wird ein Mensch in den Prozess eingebunden sein, und Sie müssen den Agenten Anweisungen geben, wann sie menschliche Eingriffe anfordern sollen. Dies könnte in Form eines Benutzers geschehen, der ein bestimmtes Hotel oder einen bestimmten Flug anfordert, den die Agenten nicht empfohlen haben, oder um Bestätigung bittet, bevor ein Flug oder Hotel gebucht wird. ## Sichtbarkeit der Multi-Agent-Interaktionen Es ist wichtig, dass Sie nachvollziehen können, wie die verschiedenen Agenten miteinander interagieren. Diese Sichtbarkeit ist entscheidend für das Debuggen, die Optimierung und die Sicherstellung der Effektivität des Gesamtsystems. Um dies zu erreichen, benötigen Sie Werkzeuge und Techniken, um die Aktivitäten und Interaktionen der Agenten zu verfolgen. Dies könnte in Form von Logging- und Überwachungstools, Visualisierungstools und Leistungsmetriken erfolgen. Betrachten wir beispielsweise die Buchung einer Reise für einen Benutzer. Sie könnten ein Dashboard haben, das den Status jedes Agenten, die Präferenzen und Einschränkungen des Benutzers sowie die Interaktionen zwischen den Agenten anzeigt. Dieses Dashboard könnte die Reisedaten des Benutzers, die vom Flugagenten empfohlenen Flüge, die vom Hotelagenten empfohlenen Hotels und die vom Mietwagenagenten empfohlenen Mietwagen anzeigen. Dies würde Ihnen einen klaren Überblick darüber geben, wie die Agenten miteinander interagieren und ob die Präferenzen und Einschränkungen des Benutzers erfüllt werden. Schauen wir uns die einzelnen Aspekte genauer an: - **Logging- und Überwachungstools**: Sie möchten, dass jede Aktion eines Agenten protokolliert wird. Ein Logeintrag könnte Informationen über den Agenten enthalten, der die Aktion ausgeführt hat, die ausgeführte Aktion, den Zeitpunkt der Aktion und das Ergebnis der Aktion. Diese Informationen können dann für Debugging, Optimierung und mehr verwendet werden. - **Visualisierungstools**: Visualisierungstools können Ihnen helfen, die Interaktionen zwischen Agenten auf eine intuitivere Weise zu sehen. Zum Beispiel könnten Sie ein Diagramm haben, das den Informationsfluss zwischen Agenten zeigt. Dies könnte Ihnen helfen, Engpässe, Ineffizienzen und andere Probleme im System zu identifizieren. - **Leistungsmetriken**: Leistungsmetriken können Ihnen helfen, die Effektivität des Multi-Agent-Systems zu verfolgen. Zum Beispiel könnten Sie die Zeit messen, die für die Erledigung einer Aufgabe benötigt wird, die Anzahl der pro Zeiteinheit erledigten Aufgaben und die Genauigkeit der Empfehlungen der Agenten. Diese Informationen können Ihnen helfen, Verbesserungsmöglichkeiten zu identifizieren und das System zu optimieren. ## Multi-Agent-Muster Schauen wir uns einige konkrete Muster an, die wir zur Erstellung von Multi-Agent-Anwendungen verwenden können. Hier sind einige interessante Muster, die es zu berücksichtigen gilt: ### Gruppenchat Dieses Muster ist nützlich, wenn Sie eine Gruppenchat-Anwendung erstellen möchten, in der mehrere Agenten miteinander kommunizieren können. Typische Anwendungsfälle für dieses Muster sind Teamzusammenarbeit, Kundensupport und soziale Netzwerke. In diesem Muster repräsentiert jeder Agent einen Benutzer im Gruppenchat, und Nachrichten werden zwischen Agenten mithilfe eines Nachrichtenprotokolls ausgetauscht. Die Agenten können Nachrichten an den Gruppenchat senden, Nachrichten aus dem Gruppenchat empfangen und auf Nachrichten anderer Agenten antworten. Dieses Muster kann mit einer zentralisierten Architektur implementiert werden, bei der alle Nachrichten über einen zentralen Server geleitet werden, oder mit einer dezentralisierten Architektur, bei der Nachrichten direkt ausgetauscht werden. ![Gruppenchat](../../../translated_images/multi-agent-group-chat.82d537c5c8dc833abbd252033e60874bc9d00df7193888b3377f8426449a0b20.de.png) ### Übergabe Dieses Muster ist nützlich, wenn Sie eine Anwendung erstellen möchten, in der mehrere Agenten Aufgaben aneinander übergeben können. Typische Anwendungsfälle für dieses Muster sind Kundensupport, Aufgabenmanagement und Workflow-Automatisierung. In diesem Muster repräsentiert jeder Agent eine Aufgabe oder einen Schritt in einem Workflow, und Agenten können Aufgaben basierend auf vordefinierten Regeln an andere Agenten übergeben. ![Übergabe](../../../translated_images/multi-agent-hand-off.ed4f0a5a58614a8a3e962fc476187e630a3ba309d066e460f017b503d0b84cfc.de.png) ### Kollaboratives Filtern Dieses Muster ist nützlich, wenn Sie eine Anwendung erstellen möchten, in der mehrere Agenten zusammenarbeiten, um Benutzern Empfehlungen zu geben. Der Grund, warum mehrere Agenten zusammenarbeiten, ist, dass jeder Agent über unterschiedliche Fachkenntnisse verfügt und auf verschiedene Weise zum Empfehlungsprozess beitragen kann. Nehmen wir ein Beispiel, bei dem ein Benutzer eine Empfehlung für die beste Aktie auf dem Markt wünscht: - **Branchenexperte**: Ein Agent könnte ein Experte in einer bestimmten Branche sein. - **Technische Analyse**: Ein anderer Agent könnte Experte für technische Analysen sein. - **Fundamentalanalyse**: Ein weiterer Agent könnte Experte für Fundamentalanalysen sein. Durch die Zusammenarbeit können diese Agenten dem Benutzer eine umfassendere Empfehlung geben. ![Empfehlung](../../../translated_images/multi-agent-filtering.719217d169391ddb118bbb726b19d4d89ee139f960f8749ccb2400efb4d0ce79.de.png) ## Szenario: Rückerstattungsprozess Betrachten wir ein Szenario, in dem ein Kunde eine Rückerstattung für ein Produkt anfordert. Es können mehrere Agenten an diesem Prozess beteiligt sein. Lassen Sie uns diese in spezifische Agenten für diesen Prozess und allgemeine Agenten, die auch in anderen Prozessen verwendet werden können, unterteilen. **Agenten spezifisch für den Rückerstattungsprozess**: Nachfolgend einige Agenten, die am Rückerstattungsprozess beteiligt sein könnten: - **Kundenagent**: Dieser Agent repräsentiert den Kunden und ist für die Einleitung des Rückerstattungsprozesses verantwortlich. - **Verkäuferagent**: Dieser Agent repräsentiert den Verkäufer und ist für die Bearbeitung der Rückerstattung verantwortlich. - **Zahlungsagent**: Dieser Agent repräsentiert den Zahlungsprozess und ist für die Rückerstattung der Zahlung des Kunden zuständig. - **Klärungsagent**: Dieser Agent repräsentiert den Klärungsprozess und ist für die Lösung von Problemen zuständig, die während des Rückerstattungsprozesses auftreten. - **Compliance-Agent**: Dieser Agent repräsentiert den Compliance-Prozess und stellt sicher, dass der Rückerstattungsprozess den Vorschriften und Richtlinien entspricht. **Allgemeine Agenten**: Diese Agenten können auch in anderen Geschäftsbereichen verwendet werden. - **Versandagent**: Dieser Agent repräsentiert den Versandprozess und ist für den Rückversand des Produkts an den Verkäufer verantwortlich. Dieser Agent kann sowohl für den Rückerstattungsprozess als auch für den allgemeinen Versand eines Produkts, z. B. bei einem Kauf, verwendet werden. - **Feedback-Agent**: Dieser Agent repräsentiert den Feedback-Prozess und ist für das Sammeln von Kundenfeedback zuständig. Feedback kann jederzeit eingeholt werden, nicht nur während des Rückerstattungsprozesses. - **Eskalationsagent**: Dieser Agent repräsentiert den Eskalationsprozess und ist für die Eskalation von Problemen an eine höhere Supportebene zuständig. Dieser Agent kann für jeden Prozess verwendet werden, bei dem Probleme eskaliert werden müssen. - **Benachrichtigungsagent**: Dieser Agent repräsentiert den Benachrichtigungsprozess und ist für das Senden von Benachrichtigungen an den Kunden in verschiedenen Phasen des Rückerstattungsprozesses zuständig. - **Analyseagent**: Dieser Agent repräsentiert den Analyseprozess und analysiert Daten, die mit dem Rückerstattungsprozess zusammenhängen. - **Audit-Agent**: Dieser Agent repräsentiert den Audit-Prozess und ist für die Prüfung des Rückerstattungsprozesses zuständig, um sicherzustellen, dass er korrekt durchgeführt wird. - **Berichtsagent**: Dieser Agent repräsentiert den Berichtsprozess und erstellt Berichte über den Rückerstattungsprozess. - **Wissensagent**: Dieser Agent repräsentiert den Wissensprozess und pflegt eine Wissensdatenbank mit Informationen, die mit dem Rückerstattungsprozess zusammenhängen. Dieser Agent könnte sowohl über Rückerstattungen als auch über andere Geschäftsbereiche informiert sein. - **Sicherheitsagent**: Dieser Agent repräsentiert den Sicherheitsprozess und stellt die Sicherheit des Rückerstattungsprozesses sicher. - **Qualitätsagent**: Dieser Agent repräsentiert den Qualitätsprozess und stellt die Qualität des Rückerstattungsprozesses sicher. Es gibt eine ganze Reihe von Agenten, sowohl für den spezifischen Rückerstattungsprozess als auch für allgemeine Agenten, die in anderen Geschäftsbereichen verwendet werden können. Hoffentlich gibt Ihnen dies eine Vorstellung davon, wie Sie entscheiden können, welche Agenten Sie in Ihrem Multi-Agent-System verwenden möchten. ## Aufgabe Was wäre eine gute Aufgabe für diese Lektion? Entwerfen Sie ein Multi-Agent-System für einen Kundensupportprozess. Identifizieren Sie die Agenten, die an diesem Prozess beteiligt sind, ihre Rollen und Verantwortlichkeiten sowie ihre Interaktionen miteinander. Berücksichtigen Sie sowohl Agenten, die spezifisch für den Kundensupportprozess sind, als auch allgemeine Agenten, die in anderen Geschäftsbereichen verwendet werden können. > Überlegen Sie, bevor Sie die Lösung unten lesen. Sie könnten mehr Agenten benötigen, als Sie denken. > TIP: Denken Sie an die verschiedenen Phasen des Kundensupportprozesses und berücksichtigen Sie auch Agenten, die für jedes System benötigt werden. ## Lösung [Solution](./solution/solution.md) ## Wissensfragen Frage: Wann sollten Sie den Einsatz von Multi-Agenten in Betracht ziehen? - [] A1: Wenn Sie eine geringe Arbeitslast und eine einfache Aufgabe haben. - [] A2: Wenn Sie eine hohe Arbeitslast haben. - [] A3: Wenn Sie eine einfache Aufgabe haben. [Solution quiz](./solution/solution-quiz.md) ## Zusammenfassung In dieser Lektion haben wir das Multi-Agent-Designmuster untersucht, einschließlich der Szenarien, in denen Multi-Agent-Systeme anwendbar sind, der Vorteile von Multi-Agent-Systemen gegenüber einem einzelnen Agenten, der Bausteine zur Implementierung des Multi-Agent-Designmusters und der Nachvollziehbarkeit der Interaktionen zwischen den verschiedenen Agenten. ## Zusätzliche Ressourcen - [Autogen design patterns](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/design-patterns/intro.html) - [Agentic design patterns](https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/) ``` **Haftungsausschluss**: Dieses Dokument wurde mithilfe von KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die aus der Nutzung dieser Übersetzung resultieren.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/08-multi-agent/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/08-multi-agent/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 18318 }
# Metakognition bei KI-Agenten ## Einführung Willkommen zur Lektion über Metakognition bei KI-Agenten! Dieses Kapitel richtet sich an Anfänger, die neugierig darauf sind, wie KI-Agenten über ihre eigenen Denkprozesse nachdenken können. Am Ende dieser Lektion werden Sie die wichtigsten Konzepte verstehen und praktische Beispiele zur Anwendung von Metakognition im Design von KI-Agenten haben. ## Lernziele Nach Abschluss dieser Lektion werden Sie in der Lage sein: 1. Die Auswirkungen von Denk-Schleifen in Agentendefinitionen zu verstehen. 2. Planungs- und Bewertungstechniken anzuwenden, um selbstkorrigierende Agenten zu unterstützen. 3. Eigene Agenten zu erstellen, die in der Lage sind, Code zu manipulieren, um Aufgaben zu erfüllen. ## Einführung in Metakognition Metakognition bezieht sich auf höhere kognitive Prozesse, die das Nachdenken über das eigene Denken beinhalten. Für KI-Agenten bedeutet dies, dass sie in der Lage sind, ihre Handlungen basierend auf Selbstbewusstsein und vergangenen Erfahrungen zu bewerten und anzupassen. ### Was ist Metakognition? Metakognition, oder "Denken über das Denken", ist ein höherer kognitiver Prozess, der Selbstbewusstsein und Selbstregulierung der eigenen kognitiven Prozesse umfasst. Im Bereich der KI befähigt Metakognition Agenten dazu, ihre Strategien und Handlungen zu bewerten und anzupassen, was zu verbesserten Problemlösungs- und Entscheidungsfähigkeiten führt. Durch das Verständnis von Metakognition können Sie KI-Agenten entwerfen, die nicht nur intelligenter, sondern auch anpassungsfähiger und effizienter sind. ### Bedeutung der Metakognition bei KI-Agenten Metakognition spielt eine entscheidende Rolle im Design von KI-Agenten aus mehreren Gründen: ![Bedeutung der Metakognition](../../../09-metacognition/images/importance-of-metacognition.png) - **Selbstreflexion**: Agenten können ihre eigene Leistung bewerten und Bereiche zur Verbesserung identifizieren. - **Anpassungsfähigkeit**: Agenten können ihre Strategien basierend auf vergangenen Erfahrungen und sich ändernden Umgebungen modifizieren. - **Fehlerkorrektur**: Agenten können Fehler eigenständig erkennen und korrigieren, was zu genaueren Ergebnissen führt. - **Ressourcenmanagement**: Agenten können den Einsatz von Ressourcen wie Zeit und Rechenleistung durch Planung und Bewertung optimieren. ## Komponenten eines KI-Agenten Bevor wir uns mit metakognitiven Prozessen befassen, ist es wichtig, die grundlegenden Komponenten eines KI-Agenten zu verstehen. Ein KI-Agent besteht typischerweise aus: - **Persona**: Die Persönlichkeit und Eigenschaften des Agenten, die definieren, wie er mit Benutzern interagiert. - **Werkzeuge**: Die Fähigkeiten und Funktionen, die der Agent ausführen kann. - **Fähigkeiten**: Das Wissen und die Expertise, die der Agent besitzt. Diese Komponenten arbeiten zusammen, um eine "Expertise-Einheit" zu schaffen, die spezifische Aufgaben ausführen kann. **Beispiel**: Betrachten Sie einen Reiseagenten, der nicht nur Ihre Reise plant, sondern seinen Weg basierend auf Echtzeitdaten und früheren Kundenerfahrungen anpasst. ### Beispiel: Metakognition in einem Reiseagenten-Service Stellen Sie sich vor, Sie entwerfen einen Reiseagenten-Service, der von KI betrieben wird. Dieser Agent, "Reiseagent", hilft Benutzern bei der Planung ihrer Urlaube. Um Metakognition einzubeziehen, muss der Reiseagent seine Handlungen basierend auf Selbstbewusstsein und vergangenen Erfahrungen bewerten und anpassen. #### Aktuelle Aufgabe Die aktuelle Aufgabe besteht darin, einem Benutzer bei der Planung einer Reise nach Paris zu helfen. #### Schritte zur Erledigung der Aufgabe 1. **Benutzervorlieben erfassen**: Den Benutzer nach seinen Reisedaten, Budget, Interessen (z. B. Museen, Küche, Shopping) und spezifischen Anforderungen fragen. 2. **Informationen abrufen**: Nach Flugoptionen, Unterkünften, Attraktionen und Restaurants suchen, die den Vorlieben des Benutzers entsprechen. 3. **Empfehlungen generieren**: Einen personalisierten Reiseplan mit Flugdaten, Hotelreservierungen und vorgeschlagenen Aktivitäten bereitstellen. 4. **Anpassung basierend auf Feedback**: Den Benutzer um Feedback zu den Empfehlungen bitten und notwendige Anpassungen vornehmen. #### Benötigte Ressourcen - Zugriff auf Datenbanken für Flug- und Hotelbuchungen. - Informationen über Pariser Attraktionen und Restaurants. - Feedback-Daten von früheren Interaktionen mit Benutzern. #### Erfahrung und Selbstreflexion Der Reiseagent nutzt Metakognition, um seine Leistung zu bewerten und aus vergangenen Erfahrungen zu lernen. Zum Beispiel: 1. **Analyse des Benutzerfeedbacks**: Der Reiseagent überprüft das Feedback der Benutzer, um festzustellen, welche Empfehlungen gut ankamen und welche nicht. Er passt seine zukünftigen Vorschläge entsprechend an. 2. **Anpassungsfähigkeit**: Wenn ein Benutzer zuvor eine Abneigung gegen überfüllte Orte geäußert hat, vermeidet der Reiseagent, beliebte Touristenorte zu Stoßzeiten in der Zukunft zu empfehlen. 3. **Fehlerkorrektur**: Wenn der Reiseagent in einer früheren Buchung einen Fehler gemacht hat, z. B. ein Hotel vorgeschlagen hat, das ausgebucht war, lernt er, die Verfügbarkeit vor der Empfehlung gründlicher zu prüfen. #### Praktisches Entwicklerbeispiel Hier ist ein vereinfachtes Beispiel, wie der Code des Reiseagenten aussehen könnte, wenn er Metakognition einbezieht: ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): # Search for flights, hotels, and attractions based on preferences flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) # Analyze feedback and adjust future recommendations self.user_preferences = adjust_preferences(self.user_preferences, feedback) # Example usage travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} travel_agent.adjust_based_on_feedback(feedback) ``` #### Warum Metakognition wichtig ist - **Selbstreflexion**: Agenten können ihre Leistung analysieren und Verbesserungsmöglichkeiten identifizieren. - **Anpassungsfähigkeit**: Agenten können Strategien basierend auf Feedback und sich ändernden Bedingungen anpassen. - **Fehlerkorrektur**: Agenten können Fehler eigenständig erkennen und beheben. - **Ressourcenmanagement**: Agenten können Ressourcen wie Zeit und Rechenleistung optimieren. Durch die Integration von Metakognition kann der Reiseagent personalisiertere und genauere Reiseempfehlungen liefern, was die gesamte Benutzererfahrung verbessert. --- ## 2. Planung bei Agenten Planung ist ein kritischer Bestandteil des Verhaltens von KI-Agenten. Sie beinhaltet das Festlegen der Schritte, die erforderlich sind, um ein Ziel zu erreichen, unter Berücksichtigung des aktuellen Zustands, der Ressourcen und möglicher Hindernisse. ### Elemente der Planung - **Aktuelle Aufgabe**: Die Aufgabe klar definieren. - **Schritte zur Erledigung der Aufgabe**: Die Aufgabe in überschaubare Schritte unterteilen. - **Benötigte Ressourcen**: Notwendige Ressourcen identifizieren. - **Erfahrung**: Vergangene Erfahrungen nutzen, um die Planung zu informieren. **Beispiel**: Hier sind die Schritte, die der Reiseagent unternehmen muss, um einem Benutzer effektiv bei der Reiseplanung zu helfen: ### Schritte für den Reiseagenten 1. **Benutzervorlieben erfassen** - Den Benutzer nach Details zu seinen Reisedaten, Budget, Interessen und spezifischen Anforderungen fragen. - Beispiele: „Wann möchten Sie reisen?“ „Was ist Ihr Budgetrahmen?“ „Welche Aktivitäten genießen Sie im Urlaub?“ 2. **Informationen abrufen** - Nach relevanten Reiseoptionen basierend auf den Vorlieben des Benutzers suchen. - **Flüge**: Nach verfügbaren Flügen innerhalb des Budgets und der bevorzugten Reisedaten suchen. - **Unterkünfte**: Hotels oder Mietunterkünfte finden, die den Vorlieben des Benutzers in Bezug auf Lage, Preis und Ausstattung entsprechen. - **Attraktionen und Restaurants**: Beliebte Attraktionen, Aktivitäten und Essensmöglichkeiten identifizieren, die den Interessen des Benutzers entsprechen. 3. **Empfehlungen generieren** - Die abgerufenen Informationen zu einem personalisierten Reiseplan zusammenstellen. - Details wie Flugoptionen, Hotelreservierungen und vorgeschlagene Aktivitäten bereitstellen, die auf die Vorlieben des Benutzers zugeschnitten sind. 4. **Reiseplan dem Benutzer präsentieren** - Den vorgeschlagenen Reiseplan dem Benutzer zur Überprüfung teilen. - Beispiel: „Hier ist ein vorgeschlagener Reiseplan für Ihre Reise nach Paris. Er enthält Flugdaten, Hotelbuchungen und eine Liste empfohlener Aktivitäten und Restaurants. Lassen Sie mich wissen, was Sie denken!“ 5. **Feedback einholen** - Den Benutzer nach Feedback zum vorgeschlagenen Reiseplan fragen. - Beispiele: „Gefällt Ihnen die Flugauswahl?“ „Ist das Hotel für Ihre Bedürfnisse geeignet?“ „Gibt es Aktivitäten, die Sie hinzufügen oder entfernen möchten?“ 6. **Anpassung basierend auf Feedback** - Den Reiseplan basierend auf dem Feedback des Benutzers anpassen. - Notwendige Änderungen an Flug-, Unterkunfts- und Aktivitätsempfehlungen vornehmen, um die Vorlieben des Benutzers besser zu erfüllen. 7. **Endgültige Bestätigung** - Den aktualisierten Reiseplan dem Benutzer zur endgültigen Bestätigung präsentieren. - Beispiel: „Ich habe die Anpassungen basierend auf Ihrem Feedback vorgenommen. Hier ist der aktualisierte Reiseplan. Sieht alles gut aus?“ 8. **Buchungen und Bestätigungen** - Sobald der Benutzer den Reiseplan genehmigt hat, Flüge, Unterkünfte und geplante Aktivitäten buchen. - Bestätigungsdetails an den Benutzer senden. 9. **Laufende Unterstützung bieten** - Verfügbar bleiben, um dem Benutzer bei Änderungen oder zusätzlichen Anfragen vor und während der Reise zu helfen. - Beispiel: „Wenn Sie während Ihrer Reise weitere Unterstützung benötigen, können Sie mich jederzeit kontaktieren!“ ### Beispielinteraktion ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) self.user_preferences = adjust_preferences(self.user_preferences, feedback) # Example usage within a booing request travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} travel_agent.adjust_based_on_feedback(feedback) ``` ## 3. Korrektives RAG-System Zunächst beginnen wir mit dem Verständnis des Unterschieds zwischen dem RAG-Tool und dem präventiven Kontextladen. ![RAG vs Kontextladen](../../../09-metacognition/images/rag-vs-context.png) ### Retrieval-Augmented Generation (RAG) RAG kombiniert ein Abrufsystem mit einem generativen Modell. Wenn eine Anfrage gestellt wird, ruft das Abrufsystem relevante Dokumente oder Daten aus einer externen Quelle ab, und diese abgerufenen Informationen werden verwendet, um die Eingabe für das generative Modell zu ergänzen. Dies hilft dem Modell, genauere und kontextbezogenere Antworten zu generieren. In einem RAG-System ruft der Agent relevante Informationen aus einer Wissensdatenbank ab und nutzt sie, um geeignete Antworten oder Aktionen zu generieren. ### Korrektiver RAG-Ansatz Der korrektive RAG-Ansatz konzentriert sich darauf, RAG-Techniken zu nutzen, um Fehler zu korrigieren und die Genauigkeit von KI-Agenten zu verbessern. Dies umfasst: 1. **Prompting-Technik**: Spezifische Prompts verwenden, um den Agenten beim Abrufen relevanter Informationen zu leiten. 2. **Werkzeug**: Algorithmen und Mechanismen implementieren, die es dem Agenten ermöglichen, die Relevanz der abgerufenen Informationen zu bewerten und genaue Antworten zu generieren. 3. **Bewertung**: Die Leistung des Agenten kontinuierlich bewerten und Anpassungen vornehmen, um die Genauigkeit und Effizienz zu verbessern. #### Beispiel: Korrektiver RAG in einem Suchagenten Betrachten Sie einen Suchagenten, der Informationen aus dem Web abruft, um Benutzeranfragen zu beantworten. Der korrektive RAG-Ansatz könnte Folgendes umfassen: 1. **Prompting-Technik**: Suchanfragen basierend auf der Benutzereingabe formulieren. 2. **Werkzeug**: Algorithmen für die Verarbeitung natürlicher Sprache und maschinelles Lernen verwenden, um Suchergebnisse zu bewerten und zu filtern. 3. **Bewertung**: Benutzerfeedback analysieren, um Ungenauigkeiten in den abgerufenen Informationen zu identifizieren und zu korrigieren. ### Korrektiver RAG im Reiseagenten Korrektives RAG (Retrieval-Augmented Generation) verbessert die Fähigkeit einer KI, Informationen abzurufen und zu generieren, während Ungenauigkeiten korrigiert werden. Sehen wir uns an, wie der Reiseagent den korrektiven RAG-Ansatz nutzen kann, um genauere und relevantere Reiseempfehlungen bereitzustellen. Dies umfasst: - **Prompting-Technik**: Spezifische Prompts verwenden, um den Agenten beim Abrufen relevanter Informationen zu leiten. - **Werkzeug**: Algorithmen und Mechanismen implementieren, die es dem Agenten ermöglichen, die Relevanz der abgerufenen Informationen zu bewerten und genaue Antworten zu generieren. - **Bewertung**: Die Leistung des Agenten kontinuierlich bewerten und Anpassungen vornehmen, um die Genauigkeit und Effizienz zu verbessern. #### Schritte zur Implementierung des korrektiven RAG im Reiseagenten 1. **Erste Benutzerinteraktion** - Der Reiseagent erfasst die anfänglichen Vorlieben des Benutzers, wie Zielort, Reisedaten, Budget und Interessen. - Beispiel: ```python preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } ``` 2. **Abruf von Informationen** - Der Reiseagent ruft Informationen über Flüge, Unterkünfte, Attraktionen und Restaurants basierend auf den Benutzerpräferenzen ab. - Beispiel: ```python flights = search_flights(preferences) hotels = search_hotels(preferences) attractions = search_attractions(preferences) ``` 3. **Generierung erster Empfehlungen** - Der Reiseagent verwendet die abgerufenen Informationen, um einen personalisierten Reiseplan zu erstellen. - Beispiel: ```python itinerary = create_itinerary(flights, hotels, attractions) print("Suggested Itinerary:", itinerary) ``` 4. **Feedback des Benutzers einholen** - Der Reiseagent bittet den Benutzer um Feedback zu den ersten Empfehlungen. - Beispiel: ```python feedback = { "liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"] } ``` 5. **Korrektiver RAG-Prozess** - **Prompting-Technik**: ... ``` ```markdown Der Reiseagent formuliert neue Suchanfragen basierend auf Benutzerfeedback. - Beispiel: ```python if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] ``` - **Tool**: Der Reiseagent verwendet Algorithmen, um neue Suchergebnisse zu bewerten und zu filtern, wobei der Schwerpunkt auf der Relevanz basierend auf Benutzerfeedback liegt. - Beispiel: ```python new_attractions = search_attractions(preferences) new_itinerary = create_itinerary(flights, hotels, new_attractions) print("Updated Itinerary:", new_itinerary) ``` - **Bewertung**: Der Reiseagent bewertet kontinuierlich die Relevanz und Genauigkeit seiner Empfehlungen, indem er Benutzerfeedback analysiert und notwendige Anpassungen vornimmt. - Beispiel: ```python def adjust_preferences(preferences, feedback): if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] return preferences preferences = adjust_preferences(preferences, feedback) ``` #### Praktisches Beispiel Hier ist ein vereinfachtes Python-Codebeispiel, das den Corrective-RAG-Ansatz im Reiseagenten integriert: ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) self.user_preferences = adjust_preferences(self.user_preferences, feedback) new_itinerary = self.generate_recommendations() return new_itinerary # Example usage travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} new_itinerary = travel_agent.adjust_based_on_feedback(feedback) print("Updated Itinerary:", new_itinerary) ``` ### Präventives Kontext-Laden Präventives Kontext-Laden beinhaltet das Laden relevanter Kontext- oder Hintergrundinformationen in das Modell, bevor eine Anfrage verarbeitet wird. Dies bedeutet, dass das Modell von Anfang an Zugriff auf diese Informationen hat, was ihm hilft, fundiertere Antworten zu generieren, ohne während des Prozesses zusätzliche Daten abrufen zu müssen. Hier ist ein vereinfachtes Beispiel, wie ein präventives Kontext-Laden für eine Reiseagenten-Anwendung in Python aussehen könnte: ```python class TravelAgent: def __init__(self): # Pre-load popular destinations and their information self.context = { "Paris": {"country": "France", "currency": "Euro", "language": "French", "attractions": ["Eiffel Tower", "Louvre Museum"]}, "Tokyo": {"country": "Japan", "currency": "Yen", "language": "Japanese", "attractions": ["Tokyo Tower", "Shibuya Crossing"]}, "New York": {"country": "USA", "currency": "Dollar", "language": "English", "attractions": ["Statue of Liberty", "Times Square"]}, "Sydney": {"country": "Australia", "currency": "Dollar", "language": "English", "attractions": ["Sydney Opera House", "Bondi Beach"]} } def get_destination_info(self, destination): # Fetch destination information from pre-loaded context info = self.context.get(destination) if info: return f"{destination}:\nCountry: {info['country']}\nCurrency: {info['currency']}\nLanguage: {info['language']}\nAttractions: {', '.join(info['attractions'])}" else: return f"Sorry, we don't have information on {destination}." # Example usage travel_agent = TravelAgent() print(travel_agent.get_destination_info("Paris")) print(travel_agent.get_destination_info("Tokyo")) ``` #### Erklärung 1. **Initialisierung (`__init__` method)**: The `TravelAgent` class pre-loads a dictionary containing information about popular destinations such as Paris, Tokyo, New York, and Sydney. This dictionary includes details like the country, currency, language, and major attractions for each destination. 2. **Retrieving Information (`get_destination_info` method)**: When a user queries about a specific destination, the `get_destination_info` Methode ruft die relevanten Informationen aus dem vorab geladenen Kontext-Wörterbuch ab. Durch das Vorladen des Kontexts kann die Reiseagenten-Anwendung schnell auf Benutzeranfragen reagieren, ohne diese Informationen in Echtzeit aus einer externen Quelle abrufen zu müssen. Dies macht die Anwendung effizienter und reaktionsschneller. ### Bootstrapping des Plans mit einem Ziel vor der Iteration Das Bootstrapping eines Plans mit einem Ziel beinhaltet, mit einem klaren Ziel oder einem gewünschten Ergebnis zu beginnen. Durch die Definition dieses Ziels im Voraus kann das Modell es als Leitprinzip während des gesamten iterativen Prozesses nutzen. Dies stellt sicher, dass jede Iteration dem gewünschten Ergebnis näher kommt, was den Prozess effizienter und fokussierter macht. Hier ist ein Beispiel, wie Sie für einen Reiseagenten einen Reiseplan mit einem Ziel bootstrappen könnten, bevor Sie iterieren: ### Szenario Ein Reiseagent möchte für einen Kunden einen individuell angepassten Urlaub planen. Das Ziel ist es, einen Reiseplan zu erstellen, der die Zufriedenheit des Kunden basierend auf seinen Vorlieben und seinem Budget maximiert. ### Schritte 1. Definieren Sie die Vorlieben und das Budget des Kunden. 2. Bootstrappen Sie den initialen Plan basierend auf diesen Vorlieben. 3. Iterieren Sie, um den Plan zu verfeinern und die Zufriedenheit des Kunden zu optimieren. #### Python-Code ```python class TravelAgent: def __init__(self, destinations): self.destinations = destinations def bootstrap_plan(self, preferences, budget): plan = [] total_cost = 0 for destination in self.destinations: if total_cost + destination['cost'] <= budget and self.match_preferences(destination, preferences): plan.append(destination) total_cost += destination['cost'] return plan def match_preferences(self, destination, preferences): for key, value in preferences.items(): if destination.get(key) != value: return False return True def iterate_plan(self, plan, preferences, budget): for i in range(len(plan)): for destination in self.destinations: if destination not in plan and self.match_preferences(destination, preferences) and self.calculate_cost(plan, destination) <= budget: plan[i] = destination break return plan def calculate_cost(self, plan, new_destination): return sum(destination['cost'] for destination in plan) + new_destination['cost'] # Example usage destinations = [ {"name": "Paris", "cost": 1000, "activity": "sightseeing"}, {"name": "Tokyo", "cost": 1200, "activity": "shopping"}, {"name": "New York", "cost": 900, "activity": "sightseeing"}, {"name": "Sydney", "cost": 1100, "activity": "beach"}, ] preferences = {"activity": "sightseeing"} budget = 2000 travel_agent = TravelAgent(destinations) initial_plan = travel_agent.bootstrap_plan(preferences, budget) print("Initial Plan:", initial_plan) refined_plan = travel_agent.iterate_plan(initial_plan, preferences, budget) print("Refined Plan:", refined_plan) ``` #### Code-Erklärung 1. **Initialisierung (`__init__` method)**: The `TravelAgent` class is initialized with a list of potential destinations, each having attributes like name, cost, and activity type. 2. **Bootstrapping the Plan (`bootstrap_plan` method)**: This method creates an initial travel plan based on the client's preferences and budget. It iterates through the list of destinations and adds them to the plan if they match the client's preferences and fit within the budget. 3. **Matching Preferences (`match_preferences` method)**: This method checks if a destination matches the client's preferences. 4. **Iterating the Plan (`iterate_plan` method)**: This method refines the initial plan by trying to replace each destination in the plan with a better match, considering the client's preferences and budget constraints. 5. **Calculating Cost (`calculate_cost` Methode)**: Diese Methode berechnet die Gesamtkosten des aktuellen Plans, einschließlich eines potenziellen neuen Ziels. #### Beispielverwendung - **Initialer Plan**: Der Reiseagent erstellt einen initialen Plan basierend auf den Vorlieben des Kunden für Sightseeing und einem Budget von 2000 $. - **Verfeinerter Plan**: Der Reiseagent iteriert den Plan und optimiert ihn basierend auf den Vorlieben und dem Budget des Kunden. Durch das Bootstrapping des Plans mit einem klaren Ziel (z. B. Maximierung der Kundenzufriedenheit) und die Iteration zur Verfeinerung des Plans kann der Reiseagent eine individuell angepasste und optimierte Reiseroute für den Kunden erstellen. Dieser Ansatz stellt sicher, dass der Reiseplan von Anfang an mit den Vorlieben und dem Budget des Kunden übereinstimmt und sich mit jeder Iteration verbessert. ### Nutzung von LLM zur Neuanordnung und Bewertung Large Language Models (LLMs) können zur Neuanordnung und Bewertung verwendet werden, indem sie die Relevanz und Qualität abgerufener Dokumente oder generierter Antworten bewerten. #### So funktioniert es: **Abruf:** Der erste Abrufschritt ruft eine Reihe von Kandidatendokumenten oder -antworten basierend auf der Anfrage ab. **Neuanordnung:** Das LLM bewertet diese Kandidaten und ordnet sie basierend auf ihrer Relevanz und Qualität neu. Dieser Schritt stellt sicher, dass die relevantesten und qualitativ hochwertigsten Informationen zuerst präsentiert werden. **Bewertung:** Das LLM weist jedem Kandidaten eine Bewertung zu, die seine Relevanz und Qualität widerspiegelt. Dies hilft bei der Auswahl der besten Antwort oder des besten Dokuments für den Benutzer. Durch die Nutzung von LLMs zur Neuanordnung und Bewertung kann das System genauere und kontextuell relevantere Informationen bereitstellen, was die Benutzererfahrung insgesamt verbessert. Hier ist ein Beispiel, wie ein Reiseagent ein Large Language Model (LLM) zur Neuanordnung und Bewertung von Reisezielen basierend auf Benutzerpräferenzen in Python verwenden könnte: #### Szenario - Reisen basierend auf Präferenzen Ein Reiseagent möchte einem Kunden die besten Reiseziele basierend auf seinen Vorlieben empfehlen. Das LLM hilft, die Ziele neu zu ordnen und zu bewerten, um sicherzustellen, dass die relevantesten Optionen präsentiert werden. #### Schritte: 1. Sammeln Sie die Benutzerpräferenzen. 2. Rufen Sie eine Liste potenzieller Reiseziele ab. 3. Verwenden Sie das LLM, um die Ziele basierend auf den Benutzerpräferenzen neu zu ordnen und zu bewerten. Hier ist, wie Sie das vorherige Beispiel aktualisieren können, um Azure OpenAI Services zu verwenden: #### Anforderungen 1. Sie benötigen ein Azure-Abonnement. 2. Erstellen Sie eine Azure OpenAI-Ressource und erhalten Sie Ihren API-Schlüssel. #### Beispiel-Python-Code ```python import requests import json class TravelAgent: def __init__(self, destinations): self.destinations = destinations def get_recommendations(self, preferences, api_key, endpoint): # Generate a prompt for the Azure OpenAI prompt = self.generate_prompt(preferences) # Define headers and payload for the request headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {api_key}' } payload = { "prompt": prompt, "max_tokens": 150, "temperature": 0.7 } # Call the Azure OpenAI API to get the re-ranked and scored destinations response = requests.post(endpoint, headers=headers, json=payload) response_data = response.json() # Extract and return the recommendations recommendations = response_data['choices'][0]['text'].strip().split('\n') return recommendations def generate_prompt(self, preferences): prompt = "Here are the travel destinations ranked and scored based on the following user preferences:\n" for key, value in preferences.items(): prompt += f"{key}: {value}\n" prompt += "\nDestinations:\n" for destination in self.destinations: prompt += f"- {destination['name']}: {destination['description']}\n" return prompt # Example usage destinations = [ {"name": "Paris", "description": "City of lights, known for its art, fashion, and culture."}, {"name": "Tokyo", "description": "Vibrant city, famous for its modernity and traditional temples."}, {"name": "New York", "description": "The city that never sleeps, with iconic landmarks and diverse culture."}, {"name": "Sydney", "description": "Beautiful harbour city, known for its opera house and stunning beaches."}, ] preferences = {"activity": "sightseeing", "culture": "diverse"} api_key = 'your_azure_openai_api_key' endpoint = 'https://your-endpoint.com/openai/deployments/your-deployment-name/completions?api-version=2022-12-01' travel_agent = TravelAgent(destinations) recommendations = travel_agent.get_recommendations(preferences, api_key, endpoint) print("Recommended Destinations:") for rec in recommendations: print(rec) ``` #### Code-Erklärung - Präferenz-Bucher 1. **Initialisierung**: Der `TravelAgent` class is initialized with a list of potential travel destinations, each having attributes like name and description. 2. **Getting Recommendations (`get_recommendations` method)**: This method generates a prompt for the Azure OpenAI service based on the user's preferences and makes an HTTP POST request to the Azure OpenAI API to get re-ranked and scored destinations. 3. **Generating Prompt (`generate_prompt` method)**: This method constructs a prompt for the Azure OpenAI, including the user's preferences and the list of destinations. The prompt guides the model to re-rank and score the destinations based on the provided preferences. 4. **API Call**: The `requests` library is used to make an HTTP POST request to the Azure OpenAI API endpoint. The response contains the re-ranked and scored destinations. 5. **Example Usage**: The travel agent collects user preferences (e.g., interest in sightseeing and diverse culture) and uses the Azure OpenAI service to get re-ranked and scored recommendations for travel destinations. Make sure to replace `your_azure_openai_api_key` with your actual Azure OpenAI API key and `https://your-endpoint.com/...` mit der tatsächlichen Endpunkt-URL Ihrer Azure OpenAI-Bereitstellung. Durch die Nutzung des LLM zur Neuanordnung und Bewertung kann der Reiseagent personalisiertere und relevantere Reiseempfehlungen für Kunden bereitstellen und so deren Gesamterfahrung verbessern. ``` ```markdown die besten Museen in Paris?"). - **Navigationsabsicht**: Der Benutzer möchte zu einer bestimmten Website oder Seite navigieren (z. B. "Offizielle Website des Louvre-Museums"). - **Transaktionsabsicht**: Der Benutzer beabsichtigt, eine Transaktion durchzuführen, wie z. B. einen Flug zu buchen oder einen Kauf zu tätigen (z. B. "Buche einen Flug nach Paris"). 2. **Kontextbewusstsein**: - Die Analyse des Kontexts der Benutzeranfrage hilft, ihre Absicht genau zu identifizieren. Dies umfasst die Berücksichtigung früherer Interaktionen, Benutzerpräferenzen und der spezifischen Details der aktuellen Anfrage. 3. **Natural Language Processing (NLP)**: - NLP-Techniken werden eingesetzt, um die natürlichen Sprachabfragen der Benutzer zu verstehen und zu interpretieren. Dazu gehören Aufgaben wie die Erkennung von Entitäten, Sentimentanalyse und Abfrageparsing. 4. **Personalisierung**: - Die Personalisierung der Suchergebnisse basierend auf der Historie, den Vorlieben und dem Feedback des Benutzers erhöht die Relevanz der abgerufenen Informationen. #### Praktisches Beispiel: Suche mit Absicht im Reiseagenten Nehmen wir den Reiseagenten als Beispiel, um zu sehen, wie die Suche mit Absicht implementiert werden kann. 1. **Erfassung von Benutzerpräferenzen** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Verstehen der Benutzerabsicht** ```python def identify_intent(query): if "book" in query or "purchase" in query: return "transactional" elif "website" in query or "official" in query: return "navigational" else: return "informational" ``` 3. **Kontextbewusstsein** ```python def analyze_context(query, user_history): # Combine current query with user history to understand context context = { "current_query": query, "user_history": user_history } return context ``` 4. **Suchen und Personalisieren von Ergebnissen** ```python def search_with_intent(query, preferences, user_history): intent = identify_intent(query) context = analyze_context(query, user_history) if intent == "informational": search_results = search_information(query, preferences) elif intent == "navigational": search_results = search_navigation(query) elif intent == "transactional": search_results = search_transaction(query, preferences) personalized_results = personalize_results(search_results, user_history) return personalized_results def search_information(query, preferences): # Example search logic for informational intent results = search_web(f"best {preferences['interests']} in {preferences['destination']}") return results def search_navigation(query): # Example search logic for navigational intent results = search_web(query) return results def search_transaction(query, preferences): # Example search logic for transactional intent results = search_web(f"book {query} to {preferences['destination']}") return results def personalize_results(results, user_history): # Example personalization logic personalized = [result for result in results if result not in user_history] return personalized[:10] # Return top 10 personalized results ``` 5. **Beispielanwendung** ```python travel_agent = Travel_Agent() preferences = { "destination": "Paris", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) user_history = ["Louvre Museum website", "Book flight to Paris"] query = "best museums in Paris" results = search_with_intent(query, preferences, user_history) print("Search Results:", results) ``` --- ## 4. Code als Werkzeug generieren Codegenerierende Agenten nutzen KI-Modelle, um Code zu schreiben und auszuführen, komplexe Probleme zu lösen und Aufgaben zu automatisieren. ### Codegenerierende Agenten Codegenerierende Agenten verwenden generative KI-Modelle, um Code zu schreiben und auszuführen. Diese Agenten können komplexe Probleme lösen, Aufgaben automatisieren und wertvolle Einblicke liefern, indem sie Code in verschiedenen Programmiersprachen generieren und ausführen. #### Praktische Anwendungen 1. **Automatisierte Codegenerierung**: Erstellen von Codeschnipseln für spezifische Aufgaben wie Datenanalyse, Web-Scraping oder maschinelles Lernen. 2. **SQL als RAG**: Verwendung von SQL-Abfragen zum Abrufen und Verarbeiten von Daten aus Datenbanken. 3. **Problemlösung**: Erstellen und Ausführen von Code zur Lösung spezifischer Probleme, wie z. B. Optimierung von Algorithmen oder Datenanalyse. #### Beispiel: Codegenerierender Agent für Datenanalyse Stellen Sie sich vor, Sie entwerfen einen codegenerierenden Agenten. So könnte er funktionieren: 1. **Aufgabe**: Analysieren eines Datensatzes, um Trends und Muster zu identifizieren. 2. **Schritte**: - Laden des Datensatzes in ein Datenanalysetool. - Generieren von SQL-Abfragen zum Filtern und Aggregieren der Daten. - Ausführen der Abfragen und Abrufen der Ergebnisse. - Verwenden der Ergebnisse zur Erstellung von Visualisierungen und Erkenntnissen. 3. **Erforderliche Ressourcen**: Zugriff auf den Datensatz, Datenanalysetools und SQL-Funktionen. 4. **Erfahrung**: Verwenden früherer Analyseergebnisse, um die Genauigkeit und Relevanz zukünftiger Analysen zu verbessern. ### Beispiel: Codegenerierender Agent für Reiseagenten In diesem Beispiel entwerfen wir einen codegenerierenden Agenten, Reiseagenten, um Benutzern bei der Reiseplanung zu helfen, indem er Code generiert und ausführt. Dieser Agent kann Aufgaben wie das Abrufen von Reiseoptionen, Filtern von Ergebnissen und Erstellen eines Reiseplans mit generativer KI übernehmen. #### Übersicht des codegenerierenden Agenten 1. **Erfassung von Benutzerpräferenzen**: Erfasst Benutzereingaben wie Zielort, Reisedaten, Budget und Interessen. 2. **Codegenerierung zum Abrufen von Daten**: Generiert Codeschnipsel, um Daten zu Flügen, Hotels und Attraktionen abzurufen. 3. **Ausführen des generierten Codes**: Führt den generierten Code aus, um Echtzeitinformationen abzurufen. 4. **Erstellung eines Reiseplans**: Stellt die abgerufenen Daten in einem personalisierten Reiseplan zusammen. 5. **Anpassung basierend auf Feedback**: Erhält Benutzerfeedback und generiert bei Bedarf Code neu, um die Ergebnisse zu verfeinern. #### Schrittweise Implementierung 1. **Erfassung von Benutzerpräferenzen** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Codegenerierung zum Abrufen von Daten** ```python def generate_code_to_fetch_data(preferences): # Example: Generate code to search for flights based on user preferences code = f""" def search_flights(): import requests response = requests.get('https://api.example.com/flights', params={preferences}) return response.json() """ return code def generate_code_to_fetch_hotels(preferences): # Example: Generate code to search for hotels code = f""" def search_hotels(): import requests response = requests.get('https://api.example.com/hotels', params={preferences}) return response.json() """ return code ``` 3. **Ausführen des generierten Codes** ```python def execute_code(code): # Execute the generated code using exec exec(code) result = locals() return result travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) flight_code = generate_code_to_fetch_data(preferences) hotel_code = generate_code_to_fetch_hotels(preferences) flights = execute_code(flight_code) hotels = execute_code(hotel_code) print("Flight Options:", flights) print("Hotel Options:", hotels) ``` 4. **Erstellung eines Reiseplans** ```python def generate_itinerary(flights, hotels, attractions): itinerary = { "flights": flights, "hotels": hotels, "attractions": attractions } return itinerary attractions = search_attractions(preferences) itinerary = generate_itinerary(flights, hotels, attractions) print("Suggested Itinerary:", itinerary) ``` 5. **Anpassung basierend auf Feedback** ```python def adjust_based_on_feedback(feedback, preferences): # Adjust preferences based on user feedback if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] return preferences feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} updated_preferences = adjust_based_on_feedback(feedback, preferences) # Regenerate and execute code with updated preferences updated_flight_code = generate_code_to_fetch_data(updated_preferences) updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences) updated_flights = execute_code(updated_flight_code) updated_hotels = execute_code(updated_hotel_code) updated_itinerary = generate_itinerary(updated_flights, updated_hotels, attractions) print("Updated Itinerary:", updated_itinerary) ``` ### Nutzung von Umweltbewusstsein und logischem Denken Basierend auf dem Schema der Tabelle kann der Abfragegenerierungsprozess durch Nutzung von Umweltbewusstsein und logischem Denken verbessert werden. Hier ein Beispiel, wie dies umgesetzt werden kann: 1. **Verständnis des Schemas**: Das System versteht das Schema der Tabelle und verwendet diese Informationen, um die Abfragegenerierung zu untermauern. 2. **Anpassung basierend auf Feedback**: Das System passt Benutzerpräferenzen basierend auf Feedback an und überlegt, welche Felder im Schema aktualisiert werden müssen. 3. **Generieren und Ausführen von Abfragen**: Das System generiert und führt Abfragen aus, um aktualisierte Flug- und Hoteldaten basierend auf den neuen Präferenzen abzurufen. Hier ist ein aktualisiertes Python-Code-Beispiel, das diese Konzepte integriert: ```python def adjust_based_on_feedback(feedback, preferences, schema): # Adjust preferences based on user feedback if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] # Reasoning based on schema to adjust other related preferences for field in schema: if field in preferences: preferences[field] = adjust_based_on_environment(feedback, field, schema) return preferences def adjust_based_on_environment(feedback, field, schema): # Custom logic to adjust preferences based on schema and feedback if field in feedback["liked"]: return schema[field]["positive_adjustment"] elif field in feedback["disliked"]: return schema[field]["negative_adjustment"] return schema[field]["default"] def generate_code_to_fetch_data(preferences): # Generate code to fetch flight data based on updated preferences return f"fetch_flights(preferences={preferences})" def generate_code_to_fetch_hotels(preferences): # Generate code to fetch hotel data based on updated preferences return f"fetch_hotels(preferences={preferences})" def execute_code(code): # Simulate execution of code and return mock data return {"data": f"Executed: {code}"} def generate_itinerary(flights, hotels, attractions): # Generate itinerary based on flights, hotels, and attractions return {"flights": flights, "hotels": hotels, "attractions": attractions} # Example schema schema = { "favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"}, "avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"} } # Example usage preferences = {"favorites": "sightseeing", "avoid": "crowded places"} feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} updated_preferences = adjust_based_on_feedback(feedback, preferences, schema) # Regenerate and execute code with updated preferences updated_flight_code = generate_code_to_fetch_data(updated_preferences) updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences) updated_flights = execute_code(updated_flight_code) updated_hotels = execute_code(updated_hotel_code) updated_itinerary = generate_itinerary(updated_flights, updated_hotels, feedback["liked"]) print("Updated Itinerary:", updated_itinerary) ``` #### Erklärung - Buchung basierend auf Feedback 1. **Schema-Bewusstsein**: Die `schema` dictionary defines how preferences should be adjusted based on feedback. It includes fields like `favorites` and `avoid`, with corresponding adjustments. 2. **Adjusting Preferences (`adjust_based_on_feedback` method)**: This method adjusts preferences based on user feedback and the schema. 3. **Environment-Based Adjustments (`adjust_based_on_environment`-Methode)**: Diese Methode passt die Anpassungen basierend auf dem Schema und Feedback an. 4. **Generieren und Ausführen von Abfragen**: Das System generiert Code, um aktualisierte Flug- und Hoteldaten basierend auf den angepassten Präferenzen abzurufen, und simuliert die Ausführung dieser Abfragen. 5. **Erstellung eines Reiseplans**: Das System erstellt einen aktualisierten Reiseplan basierend auf den neuen Flug-, Hotel- und Attraktionsdaten. Durch die Umweltbewusstheit und das logische Denken basierend auf dem Schema kann das System genauere und relevantere Abfragen generieren, was zu besseren Reiseempfehlungen und einer persönlicheren Benutzererfahrung führt. ### Verwendung von SQL als Retrieval-Augmented Generation (RAG)-Technik SQL (Structured Query Language) ist ein leistungsstarkes Werkzeug zur Interaktion mit Datenbanken. Wenn SQL als Teil eines Retrieval-Augmented Generation (RAG)-Ansatzes verwendet wird, kann es relevante Daten aus Datenbanken abrufen, um Antworten oder Aktionen in KI-Agenten zu informieren und zu generieren. Lassen Sie uns untersuchen, wie SQL als RAG-Technik im Kontext von Reiseagenten verwendet werden kann. #### Schlüsselkonzepte 1. **Datenbankinteraktion**: - SQL wird verwendet, um Datenbanken abzufragen, relevante Informationen abzurufen und Daten zu manipulieren. - Beispiel: Abrufen von Flugdaten, Hotelinformationen und Attraktionen aus einer Reisedatenbank. 2. **Integration mit RAG**: - SQL-Abfragen werden basierend auf Benutzereingaben und -präferenzen generiert. - Die abgerufenen Daten werden dann verwendet, um personalisierte Empfehlungen oder Aktionen zu generieren. 3. **Dynamische Abfragegenerierung**: - Der KI-Agent generiert dynamische SQL-Abfragen basierend auf dem Kontext und den Bedürfnissen des Benutzers. - Beispiel: Anpassen von SQL-Abfragen, um Ergebnisse basierend auf Budget, Daten und Interessen zu filtern. #### Anwendungen - **Automatisierte Codegenerierung**: Erstellen von Codeschnipseln für spezifische Aufgaben. - **SQL als RAG**: Verwendung von SQL-Abfragen zur Datenmanipulation. - **Problemlösung**: Erstellen und Ausführen von Code zur Problemlösung. **Beispiel**: Ein Datenanalyse-Agent: 1. **Aufgabe**: Analysieren eines Datensatzes, um Trends zu finden. 2. **Schritte**: - Laden des Datensatzes. - Generieren von SQL-Abfragen zum Filtern von Daten. - Ausführen von Abfragen und Abrufen von Ergebnissen. - Generieren von Visualisierungen und Erkenntnissen. 3. **Ressourcen**: Zugriff auf den Datensatz, SQL-Funktionen. 4. **Erfahrung**: Verwenden vergangener Ergebnisse, um zukünftige Analysen zu verbessern. #### Praktisches Beispiel: Verwendung von SQL im Reiseagenten 1. **Erfassung von Benutzerpräferenzen** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Generieren von SQL-Abfragen** ```python def generate_sql_query(table, preferences): query = f"SELECT * FROM {table} WHERE " conditions = [] for key, value in preferences.items(): conditions.append(f"{key}='{value}'") query += " AND ".join(conditions) return query ``` 3. **Ausführen von SQL-Abfragen** ```python import sqlite3 def execute_sql_query(query, database="travel.db"): connection = sqlite3.connect(database) cursor = connection.cursor() cursor.execute(query) results = cursor.fetchall() connection.close() return results ``` 4. **Generieren von Empfehlungen** ```python def generate_recommendations(preferences): flight_query = generate_sql_query("flights", preferences) hotel_query = generate_sql_query("hotels", preferences) attraction_query = generate_sql_query("attractions", preferences) flights = execute_sql_query(flight_query) hotels = execute_sql_query(hotel_query) attractions = execute_sql_query(attraction_query) itinerary = { "flights": flights, "hotels": hotels, "attractions": attractions } return itinerary travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = generate_recommendations(preferences) print("Suggested Itinerary:", itinerary) ``` #### Beispiel-SQL-Abfragen 1. **Flugabfrage** ```sql SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate'; ``` 2. **Hotelabfrage** ```sql SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate'; ``` 3. **Attraktionsabfrage** ```sql SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine'; ``` Durch die Nutzung von SQL als Teil der Retrieval-Augmented Generation (RAG)-Technik können KI-Agenten wie Reiseagenten dynamisch relevante Daten abrufen und nutzen, um genaue und personalisierte Empfehlungen bereitzustellen. ### Fazit Metakognition ist ein leistungsstarkes Werkzeug, das die Fähigkeiten von KI-Agenten erheblich verbessern kann. Durch die Integration metakognitiver Prozesse können Sie Agenten entwerfen, die intelligenter, anpassungsfähiger und effizienter sind. Verwenden Sie die zusätzlichen Ressourcen, um die faszinierende Welt der Metakognition in KI-Agenten weiter zu erkunden. ``` **Haftungsausschluss**: Dieses Dokument wurde mit KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die sich aus der Nutzung dieser Übersetzung ergeben.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/09-metacognition/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/09-metacognition/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 51899 }
# KI-Agenten in der Produktion ## Einführung Diese Lektion behandelt: - Wie Sie die Bereitstellung Ihres KI-Agenten in der Produktion effektiv planen. - Häufige Fehler und Probleme, die bei der Bereitstellung Ihres KI-Agenten in der Produktion auftreten können. - Wie Sie die Kosten verwalten und gleichzeitig die Leistung Ihres KI-Agenten aufrechterhalten können. ## Lernziele Nach Abschluss dieser Lektion wissen Sie, wie Sie: - Techniken anwenden können, um die Leistung, Kosten und Effektivität eines KI-Agentensystems in der Produktion zu verbessern. - Ihre KI-Agenten bewerten können und verstehen, was dabei zu beachten ist. - Kosten kontrollieren können, wenn Sie KI-Agenten in die Produktion bringen. Es ist wichtig, vertrauenswürdige KI-Agenten bereitzustellen. Schauen Sie sich dazu auch die Lektion "Vertrauenswürdige KI-Agenten erstellen" an. ## Bewertung von KI-Agenten Vor, während und nach der Bereitstellung von KI-Agenten ist es entscheidend, ein geeignetes System zur Bewertung Ihrer KI-Agenten zu haben. Dies stellt sicher, dass Ihr System mit Ihren und den Zielen Ihrer Nutzer übereinstimmt. Um einen KI-Agenten zu bewerten, ist es wichtig, nicht nur die Ausgabe des Agenten zu analysieren, sondern das gesamte System, in dem Ihr KI-Agent arbeitet. Dies umfasst unter anderem: - Die anfängliche Modellanfrage. - Die Fähigkeit des Agenten, die Absicht des Nutzers zu erkennen. - Die Fähigkeit des Agenten, das richtige Tool zur Aufgabenbewältigung auszuwählen. - Die Antwort des Tools auf die Anfrage des Agenten. - Die Fähigkeit des Agenten, die Antwort des Tools zu interpretieren. - Das Feedback des Nutzers auf die Antwort des Agenten. So können Sie Verbesserungsbereiche auf eine modulare Weise identifizieren. Anschließend können Sie die Auswirkungen von Änderungen an Modellen, Prompts, Tools und anderen Komponenten effizienter überwachen. ## Häufige Probleme und mögliche Lösungen bei KI-Agenten | **Problem** | **Mögliche Lösung** | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | KI-Agent führt Aufgaben nicht konsistent aus | - Verfeinern Sie den Prompt, der dem KI-Agenten gegeben wird; seien Sie klar in den Zielen.<br>- Überlegen Sie, ob das Aufteilen der Aufgaben in Teilaufgaben und deren Bearbeitung durch mehrere Agenten hilfreich sein könnte. | | KI-Agent gerät in Endlosschleifen | - Stellen Sie klare Abbruchbedingungen und -kriterien bereit, damit der Agent weiß, wann der Prozess beendet werden soll.<br>- Für komplexe Aufgaben, die logisches Denken und Planung erfordern, verwenden Sie ein größeres Modell, das auf solche Aufgaben spezialisiert ist. | | Tool-Anfragen des KI-Agenten funktionieren nicht gut | - Testen und validieren Sie die Ausgabe des Tools außerhalb des Agentensystems.<br>- Verfeinern Sie die definierten Parameter, Prompts und die Benennung der Tools. | | Multi-Agenten-System arbeitet nicht konsistent | - Verfeinern Sie die Prompts für jeden Agenten, um sicherzustellen, dass sie spezifisch und voneinander unterscheidbar sind.<br>- Erstellen Sie ein hierarchisches System mit einem "Routing-" oder Steuerungsagenten, der entscheidet, welcher Agent der richtige ist. | ## Kostenmanagement Hier sind einige Strategien, um die Kosten für die Bereitstellung von KI-Agenten in der Produktion zu verwalten: - **Antworten zwischenspeichern** - Häufige Anfragen und Aufgaben zu identifizieren und die Antworten bereitzustellen, bevor sie durch Ihr agentisches System laufen, ist eine gute Möglichkeit, das Volumen ähnlicher Anfragen zu reduzieren. Sie können sogar einen Ablauf implementieren, um zu bestimmen, wie ähnlich eine Anfrage den zwischengespeicherten Anfragen ist, indem Sie einfachere KI-Modelle verwenden. - **Kleinere Modelle verwenden** - Kleine Sprachmodelle (SLMs) können bei bestimmten agentischen Anwendungsfällen gut abschneiden und die Kosten erheblich senken. Wie bereits erwähnt, ist der Aufbau eines Bewertungssystems, um Leistung und Kosten zwischen kleineren und größeren Modellen zu vergleichen, der beste Weg, um zu verstehen, wie gut ein SLM für Ihren Anwendungsfall geeignet ist. - **Router-Modell verwenden** - Eine ähnliche Strategie besteht darin, eine Vielfalt von Modellen und Größen zu nutzen. Sie können ein LLM/SLM oder eine serverlose Funktion verwenden, um Anfragen basierend auf deren Komplexität an die am besten geeigneten Modelle weiterzuleiten. Dies hilft, Kosten zu senken und gleichzeitig sicherzustellen, dass die Leistung bei den richtigen Aufgaben erhalten bleibt. ## Herzlichen Glückwunsch Dies ist derzeit die letzte Lektion von "KI-Agenten für Anfänger". Wir planen, basierend auf Feedback und Veränderungen in dieser stetig wachsenden Branche, weitere Lektionen hinzuzufügen. Schauen Sie also bald wieder vorbei. Wenn Sie Ihr Lernen und Arbeiten mit KI-Agenten fortsetzen möchten, treten Sie dem [Azure AI Community Discord](https://discord.gg/kzRShWzttr) bei. Dort veranstalten wir Workshops, Community-Roundtables und "Ask Me Anything"-Sitzungen. Wir haben außerdem eine Learn-Sammlung mit weiteren Materialien, die Ihnen helfen können, KI-Agenten in der Produktion zu entwickeln. ``` **Haftungsausschluss**: Dieses Dokument wurde mithilfe von KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, weisen wir darauf hin, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die aus der Nutzung dieser Übersetzung entstehen.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/de/10-ai-agents-production/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/10-ai-agents-production/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 6229 }
# Configuración del Curso ## Introducción Esta lección cubrirá cómo ejecutar los ejemplos de código de este curso. ## Requisitos - Una cuenta de GitHub - Python 3.12+ ## Clonar o Hacer un Fork de este Repositorio Para comenzar, por favor clona o haz un fork del repositorio de GitHub. Esto creará tu propia versión del material del curso para que puedas ejecutar, probar y ajustar el código a tu gusto. Esto se puede hacer haciendo clic en el enlace para [hacer fork del repositorio](https://github.com/microsoft/ai-agents-for-beginners/fork). Ahora deberías tener tu propia versión del curso como se muestra a continuación: ![Repositorio con Fork](../../../translated_images/forked-repo.eea246a73044cc984a1e462349e36e7336204f00785e3187b7399905feeada07.es.png) ## Recuperar tu Token de Acceso Personal (PAT) de GitHub Actualmente, este curso utiliza el Marketplace de Modelos de GitHub para ofrecer acceso gratuito a Modelos de Lenguaje de Gran Escala (LLMs) que se usarán para crear Agentes de IA. Para acceder a este servicio, necesitarás crear un Token de Acceso Personal de GitHub. Esto se puede hacer yendo a la configuración de [Tokens de Acceso Personal](https://github.com/settings/personal-access-tokens) en tu cuenta de GitHub. Selecciona la opción `Fine-grained tokens` en el lado izquierdo de tu pantalla. Luego selecciona `Generate new token`. ![Generar Token](../../../translated_images/generate-token.361ec40abe59b84ac68d63c23e2b6854d6fad82bd4e41feb98fc0e6f030e8ef7.es.png) Copia tu nuevo token que acabas de crear. Ahora deberás agregarlo a tu archivo `.env` incluido en este curso. ## Agregar esto a tus Variables de Entorno Para crear tu archivo `.env`, ejecuta el siguiente comando en tu terminal: ```bash cp .env.example .env ``` Esto copiará el archivo de ejemplo y creará un `.env` en tu directorio. Abre ese archivo y pega el token que creaste en el campo `GITHUB_TOKEN=` del archivo .env. ## Instalar los Paquetes Requeridos Para asegurarte de que tienes todos los paquetes de Python necesarios para ejecutar el código, ejecuta el siguiente comando en tu terminal. Recomendamos crear un entorno virtual de Python para evitar conflictos y problemas. ```bash pip install -r requirements.txt ``` Esto debería instalar los paquetes de Python requeridos. ¡Ahora estás listo para ejecutar el código de este curso! ¡Feliz aprendizaje sobre el mundo de los Agentes de IA! Si tienes algún problema con esta configuración, únete a nuestro [Discord de la Comunidad de Azure AI](https://discord.gg/kzRShWzttr) o [crea un issue](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst). **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por garantizar la precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de ningún malentendido o interpretación errónea que surja del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/00-course-setup/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/00-course-setup/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 3312 }
# Introducción a los Agentes de IA y Casos de Uso de Agentes ¡Bienvenido al curso "Agentes de IA para Principiantes"! Este curso te proporciona conocimientos fundamentales y ejemplos prácticos para construir con Agentes de IA. Únete a la [Comunidad de Discord de Azure AI](https://discord.gg/kzRShWzttr) para conocer a otros estudiantes, constructores de Agentes de IA y hacer cualquier pregunta que tengas sobre este curso. Para comenzar este curso, primero entenderemos mejor qué son los Agentes de IA y cómo podemos utilizarlos en las aplicaciones y flujos de trabajo que construimos. ## Introducción Esta lección cubre: - ¿Qué son los Agentes de IA y cuáles son los diferentes tipos de agentes? - ¿Cuáles son los casos de uso ideales para los Agentes de IA y cómo pueden ayudarnos? - ¿Cuáles son algunos de los bloques de construcción básicos al diseñar Soluciones Agénticas? ## Objetivos de Aprendizaje Al completar esta lección, deberías ser capaz de: - Comprender los conceptos de los Agentes de IA y cómo se diferencian de otras soluciones de IA. - Aplicar los Agentes de IA de manera más eficiente. - Diseñar soluciones agénticas de manera productiva tanto para usuarios como para clientes. ## Definiendo Agentes de IA y Tipos de Agentes de IA ### ¿Qué son los Agentes de IA? Los Agentes de IA son **sistemas** que permiten que los **Modelos de Lenguaje Extensos (LLMs)** **realicen acciones** al ampliar sus capacidades mediante el acceso a **herramientas** y **conocimiento**. Desglosaremos esta definición en partes más pequeñas: - **Sistema** - Es importante pensar en los agentes no solo como un componente único, sino como un sistema compuesto por múltiples componentes. A nivel básico, los componentes de un Agente de IA son: - **Entorno** - El espacio definido donde opera el Agente de IA. Por ejemplo, si tuviéramos un Agente de IA para reservas de viajes, el entorno podría ser el sistema de reservas que el agente utiliza para completar tareas. - **Sensores** - Los entornos tienen información y proporcionan retroalimentación. Los Agentes de IA usan sensores para recopilar e interpretar esta información sobre el estado actual del entorno. En el ejemplo del Agente de Reservas de Viajes, el sistema de reservas podría proporcionar información como la disponibilidad de hoteles o precios de vuelos. - **Actuadores** - Una vez que el Agente de IA recibe el estado actual del entorno, para la tarea en curso, el agente determina qué acción realizar para cambiar el entorno. Para el agente de reservas, podría ser reservar una habitación disponible para el usuario. ![¿Qué son los Agentes de IA?](../../../translated_images/what-are-ai-agents.125520f55950b252a429b04a9f41e0152d4dafa1f1bd9081f4f574631acb759e.es.png?WT.mc_id=academic-105485-koreyst) **Modelos de Lenguaje Extensos** - El concepto de agentes existía antes de la creación de los LLMs. La ventaja de construir Agentes de IA con LLMs es su capacidad para interpretar el lenguaje humano y los datos. Esta capacidad permite a los LLMs interpretar la información del entorno y definir un plan para cambiarlo. **Realizar Acciones** - Fuera de los sistemas de Agentes de IA, los LLMs están limitados a situaciones donde la acción es generar contenido o información basada en el mensaje del usuario. Dentro de los sistemas de Agentes de IA, los LLMs pueden realizar tareas interpretando la solicitud del usuario y utilizando las herramientas disponibles en su entorno. **Acceso a Herramientas** - Las herramientas a las que el LLM tiene acceso están definidas por 1) el entorno en el que opera y 2) el desarrollador del Agente de IA. En nuestro ejemplo del agente de viajes, las herramientas del agente están limitadas por las operaciones disponibles en el sistema de reservas, y/o el desarrollador puede limitar el acceso del agente a herramientas específicas como vuelos. **Conocimiento** - Más allá de la información proporcionada por el entorno, los Agentes de IA también pueden recuperar conocimiento de otros sistemas, servicios, herramientas e incluso otros agentes. En el ejemplo del agente de viajes, este conocimiento podría incluir información sobre las preferencias de viaje del usuario almacenada en una base de datos de clientes. ### Los diferentes tipos de agentes Ahora que tenemos una definición general de los Agentes de IA, veamos algunos tipos específicos de agentes y cómo se aplicarían a un agente de reservas de viajes. | **Tipo de Agente** | **Descripción** | **Ejemplo** | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Agentes de Reflexión Simple** | Realizan acciones inmediatas basadas en reglas predefinidas. | El agente de viajes interpreta el contexto de un correo electrónico y reenvía quejas de viaje al servicio al cliente. | | **Agentes Basados en Modelos** | Realizan acciones basadas en un modelo del mundo y los cambios en ese modelo. | El agente de viajes prioriza rutas con cambios significativos en precios basándose en el acceso a datos históricos de precios. | | **Agentes Basados en Objetivos** | Crean planes para alcanzar objetivos específicos interpretando el objetivo y determinando las acciones necesarias para lograrlo. | El agente de viajes reserva un trayecto determinando los arreglos de viaje necesarios (coche, transporte público, vuelos) desde la ubicación actual hasta el destino. | | **Agentes Basados en Utilidad** | Consideran preferencias y evalúan compensaciones numéricamente para determinar cómo alcanzar objetivos. | El agente de viajes maximiza la utilidad sopesando comodidad frente a costo al reservar viajes. | | **Agentes de Aprendizaje** | Mejoran con el tiempo al responder a retroalimentación y ajustar sus acciones en consecuencia. | El agente de viajes mejora utilizando retroalimentación de encuestas post-viaje para hacer ajustes en futuras reservas. | | **Agentes Jerárquicos** | Incluyen múltiples agentes en un sistema escalonado, donde agentes de nivel superior dividen tareas en subtareas para que los agentes de nivel inferior las completen. | El agente de viajes cancela un viaje dividiendo la tarea en subtareas (por ejemplo, cancelar reservas específicas) y permitiendo que agentes de nivel inferior las completen, informando de vuelta al agente de nivel superior. | | **Sistemas Multi-Agentes (MAS)** | Los agentes completan tareas de forma independiente, ya sea cooperativa o competitivamente. | Cooperativo: Múltiples agentes reservan servicios específicos de viaje como hoteles, vuelos y entretenimiento. Competitivo: Múltiples agentes gestionan y compiten por un calendario compartido de reservas hoteleras para alojar clientes. | ## Cuándo Usar Agentes de IA En la sección anterior, utilizamos el caso de uso del Agente de Viajes para explicar cómo los diferentes tipos de agentes pueden ser utilizados en diversos escenarios de reservas de viaje. Continuaremos usando esta aplicación a lo largo del curso. Veamos los tipos de casos de uso para los que los Agentes de IA son más adecuados: ![¿Cuándo usar Agentes de IA?](../../../translated_images/when-to-use-ai-agents.912b9a02e9e0e2af45a3e24faa4e912e334ec23f21f0cf5cb040b7e899b09cd0.es.png?WT.mc_id=academic-105485-koreyst) - **Problemas Abiertos** - Permitir que el LLM determine los pasos necesarios para completar una tarea porque no siempre se puede codificar de manera rígida en un flujo de trabajo. - **Procesos de Múltiples Pasos** - Tareas que requieren un nivel de complejidad en el que el Agente de IA necesita usar herramientas o información en múltiples interacciones en lugar de una sola recuperación. - **Mejora con el Tiempo** - Tareas en las que el agente puede mejorar con el tiempo al recibir retroalimentación de su entorno o de los usuarios para proporcionar una mejor utilidad. Cubrimos más consideraciones sobre el uso de Agentes de IA en la lección Construyendo Agentes de IA Confiables. ## Fundamentos de las Soluciones Agénticas ### Desarrollo de Agentes El primer paso para diseñar un sistema de Agente de IA es definir las herramientas, acciones y comportamientos. En este curso, nos enfocamos en usar el **Servicio de Agentes de Azure AI** para definir nuestros agentes. Este ofrece características como: - Selección de Modelos Abiertos como OpenAI, Mistral y Llama - Uso de Datos Licenciados a través de proveedores como Tripadvisor - Uso de herramientas estandarizadas de OpenAPI 3.0 ### Patrones Agénticos La comunicación con los LLMs se realiza a través de prompts. Dada la naturaleza semi-autónoma de los Agentes de IA, no siempre es posible o necesario volver a hacer un prompt manualmente después de un cambio en el entorno. Usamos **Patrones Agénticos** que nos permiten hacer prompts al LLM en múltiples pasos de una manera más escalable. Este curso está dividido en algunos de los patrones agénticos populares actuales. ### Frameworks Agénticos Los Frameworks Agénticos permiten a los desarrolladores implementar patrones agénticos mediante código. Estos frameworks ofrecen plantillas, plugins y herramientas para mejorar la colaboración entre Agentes de IA. Estos beneficios proporcionan capacidades para una mejor observabilidad y solución de problemas en sistemas de Agentes de IA. En este curso, exploraremos el framework AutoGen basado en investigación y el framework listo para producción Agent de Semantic Kernel. **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automatizada basados en inteligencia artificial. Si bien nos esforzamos por garantizar la precisión, tenga en cuenta que las traducciones automáticas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas derivadas del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/01-intro-to-ai-agents/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/01-intro-to-ai-agents/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 11452 }
# Explorar Frameworks de Agentes de IA Los frameworks de agentes de IA son plataformas de software diseñadas para simplificar la creación, implementación y gestión de agentes de inteligencia artificial. Estos frameworks proporcionan a los desarrolladores componentes preconstruidos, abstracciones y herramientas que facilitan el desarrollo de sistemas de IA complejos. Estos frameworks ayudan a los desarrolladores a centrarse en los aspectos únicos de sus aplicaciones al proporcionar enfoques estandarizados para los desafíos comunes en el desarrollo de agentes de IA. Mejoran la escalabilidad, accesibilidad y eficiencia en la construcción de sistemas de IA. ## Introducción Esta lección cubrirá: - ¿Qué son los frameworks de agentes de IA y qué permiten hacer a los desarrolladores? - ¿Cómo pueden los equipos usarlos para prototipar rápidamente, iterar y mejorar las capacidades de sus agentes? - ¿Cuáles son las diferencias entre los frameworks y herramientas creados por Microsoft ([Autogen](https://aka.ms/ai-agents/autogen) / [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) / [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service))? - ¿Puedo integrar directamente mis herramientas existentes del ecosistema Azure o necesito soluciones independientes? - ¿Qué es el servicio Azure AI Agents y cómo me ayuda? ## Objetivos de aprendizaje Los objetivos de esta lección son ayudarte a comprender: - El papel de los frameworks de agentes de IA en el desarrollo de inteligencia artificial. - Cómo aprovechar los frameworks de agentes de IA para construir agentes inteligentes. - Las capacidades clave que habilitan los frameworks de agentes de IA. - Las diferencias entre Autogen, Semantic Kernel y Azure AI Agent Service. ## ¿Qué son los frameworks de agentes de IA y qué permiten hacer a los desarrolladores? Los frameworks de IA tradicionales pueden ayudarte a integrar IA en tus aplicaciones y mejorar estas aplicaciones de las siguientes maneras: - **Personalización**: La IA puede analizar el comportamiento y las preferencias de los usuarios para proporcionar recomendaciones, contenido y experiencias personalizadas. Ejemplo: Servicios de streaming como Netflix usan IA para sugerir películas y series basándose en el historial de visualización, mejorando el compromiso y la satisfacción del usuario. - **Automatización y eficiencia**: La IA puede automatizar tareas repetitivas, optimizar flujos de trabajo y mejorar la eficiencia operativa. Ejemplo: Las aplicaciones de servicio al cliente utilizan chatbots impulsados por IA para manejar consultas comunes, reduciendo los tiempos de respuesta y liberando a los agentes humanos para problemas más complejos. - **Mejora de la experiencia del usuario**: La IA puede mejorar la experiencia del usuario proporcionando funciones inteligentes como reconocimiento de voz, procesamiento de lenguaje natural y texto predictivo. Ejemplo: Asistentes virtuales como Siri y Google Assistant utilizan IA para entender y responder a comandos de voz, facilitando la interacción de los usuarios con sus dispositivos. ### Todo esto suena genial, ¿verdad? Entonces, ¿por qué necesitamos frameworks de agentes de IA? Los frameworks de agentes de IA representan algo más que simples frameworks de IA. Están diseñados para permitir la creación de agentes inteligentes que pueden interactuar con usuarios, otros agentes y el entorno para alcanzar objetivos específicos. Estos agentes pueden mostrar comportamientos autónomos, tomar decisiones y adaptarse a condiciones cambiantes. Veamos algunas capacidades clave habilitadas por los frameworks de agentes de IA: - **Colaboración y coordinación entre agentes**: Permiten la creación de múltiples agentes de IA que pueden trabajar juntos, comunicarse y coordinarse para resolver tareas complejas. - **Automatización y gestión de tareas**: Proporcionan mecanismos para automatizar flujos de trabajo de múltiples pasos, delegación de tareas y gestión dinámica de tareas entre agentes. - **Comprensión y adaptación contextual**: Equipan a los agentes con la capacidad de entender el contexto, adaptarse a entornos cambiantes y tomar decisiones basadas en información en tiempo real. En resumen, los agentes te permiten hacer más, llevar la automatización al siguiente nivel y crear sistemas más inteligentes que pueden adaptarse y aprender de su entorno. ## ¿Cómo prototipar rápidamente, iterar y mejorar las capacidades de los agentes? Este es un campo que avanza rápidamente, pero hay algunos elementos comunes en la mayoría de los frameworks de agentes de IA que pueden ayudarte a prototipar e iterar rápidamente, como los componentes modulares, herramientas colaborativas y aprendizaje en tiempo real. Vamos a profundizar en estos: - **Usar componentes modulares**: Los frameworks de IA ofrecen componentes preconstruidos como prompts, parsers y gestión de memoria. - **Aprovechar herramientas colaborativas**: Diseñar agentes con roles y tareas específicas, permitiéndoles probar y refinar flujos de trabajo colaborativos. - **Aprender en tiempo real**: Implementar bucles de retroalimentación donde los agentes aprenden de las interacciones y ajustan su comportamiento dinámicamente. ### Usar componentes modulares Frameworks como LangChain y Microsoft Semantic Kernel ofrecen componentes preconstruidos como prompts, parsers y gestión de memoria. **Cómo los equipos pueden usarlos**: Los equipos pueden ensamblar rápidamente estos componentes para crear un prototipo funcional sin empezar desde cero, permitiendo una experimentación e iteración rápidas. **Cómo funciona en la práctica**: Puedes usar un parser preconstruido para extraer información de la entrada del usuario, un módulo de memoria para almacenar y recuperar datos, y un generador de prompts para interactuar con los usuarios, todo sin necesidad de construir estos componentes desde cero. **Ejemplo de código**: Veamos un ejemplo de cómo puedes usar un parser preconstruido para extraer información de la entrada del usuario: ```python from langchain import Parser parser = Parser() user_input = "Book a flight from New York to London on July 15th" parsed_data = parser.parse(user_input) print(parsed_data) # Output: {'origin': 'New York', 'destination': 'London', 'date': 'July 15th'} ``` Este ejemplo muestra cómo puedes aprovechar un parser preconstruido para extraer información clave de la entrada del usuario, como el origen, destino y fecha de una solicitud de reserva de vuelo. Este enfoque modular te permite centrarte en la lógica de alto nivel. ### Aprovechar herramientas colaborativas Frameworks como CrewAI y Microsoft Autogen facilitan la creación de múltiples agentes que pueden trabajar juntos. **Cómo los equipos pueden usarlos**: Los equipos pueden diseñar agentes con roles y tareas específicas, permitiéndoles probar y refinar flujos de trabajo colaborativos y mejorar la eficiencia general del sistema. **Cómo funciona en la práctica**: Puedes crear un equipo de agentes donde cada agente tenga una función especializada, como recuperación de datos, análisis o toma de decisiones. Estos agentes pueden comunicarse y compartir información para alcanzar un objetivo común, como responder a una consulta del usuario o completar una tarea. **Ejemplo de código (Autogen)**: ```python # creating agents, then create a round robin schedule where they can work together, in this case in order # Data Retrieval Agent # Data Analysis Agent # Decision Making Agent agent_retrieve = AssistantAgent( name="dataretrieval", model_client=model_client, tools=[retrieve_tool], system_message="Use tools to solve tasks." ) agent_analyze = AssistantAgent( name="dataanalysis", model_client=model_client, tools=[analyze_tool], system_message="Use tools to solve tasks." ) # conversation ends when user says "APPROVE" termination = TextMentionTermination("APPROVE") user_proxy = UserProxyAgent("user_proxy", input_func=input) team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination) stream = team.run_stream(task="Analyze data", max_turns=10) # Use asyncio.run(...) when running in a script. await Console(stream) ``` Este código muestra cómo puedes crear una tarea que involucra a múltiples agentes trabajando juntos para analizar datos. Cada agente realiza una función específica, y la tarea se ejecuta coordinando a los agentes para lograr el resultado deseado. Al crear agentes dedicados con roles especializados, puedes mejorar la eficiencia y el rendimiento de las tareas. ### Aprender en tiempo real Los frameworks avanzados proporcionan capacidades para la comprensión contextual y adaptación en tiempo real. **Cómo los equipos pueden usarlos**: Los equipos pueden implementar bucles de retroalimentación donde los agentes aprenden de las interacciones y ajustan su comportamiento dinámicamente, lo que lleva a una mejora continua y refinamiento de capacidades. **Cómo funciona en la práctica**: Los agentes pueden analizar comentarios de usuarios, datos del entorno y resultados de tareas para actualizar su base de conocimiento, ajustar algoritmos de toma de decisiones y mejorar su rendimiento con el tiempo. Este proceso de aprendizaje iterativo permite a los agentes adaptarse a condiciones cambiantes y preferencias de los usuarios, mejorando la efectividad general del sistema. ## ¿Cuáles son las diferencias entre Autogen, Semantic Kernel y Azure AI Agent Service? Existen muchas formas de comparar estos frameworks, pero analicemos algunas diferencias clave en términos de su diseño, capacidades y casos de uso objetivo: ### Autogen Autogen es un framework de código abierto desarrollado por el Laboratorio de Fronteras de IA de Microsoft Research. Se centra en aplicaciones *agénticas* distribuidas y basadas en eventos, habilitando múltiples LLMs y SLMs, herramientas y patrones avanzados de diseño multi-agente. ... *(El resto del contenido traducido continúa aquí según el formato y estilo original).* basado en los objetivos del proyecto. Ideal para la comprensión del lenguaje natural y la generación de contenido. - **Azure AI Agent Service**: Modelos flexibles, mecanismos de seguridad empresarial, métodos de almacenamiento de datos. Ideal para el despliegue seguro, escalable y flexible de agentes de IA en aplicaciones empresariales. ## ¿Puedo integrar directamente mis herramientas existentes del ecosistema de Azure, o necesito soluciones independientes? La respuesta es sí, puedes integrar tus herramientas existentes del ecosistema de Azure directamente con Azure AI Agent Service, especialmente porque ha sido diseñado para trabajar de manera fluida con otros servicios de Azure. Podrías, por ejemplo, integrar Bing, Azure AI Search y Azure Functions. También hay una integración profunda con Azure AI Foundry. Para Autogen y Semantic Kernel, también puedes integrarlos con servicios de Azure, pero puede requerir que llames a los servicios de Azure desde tu código. Otra forma de integrar es usar los SDKs de Azure para interactuar con los servicios de Azure desde tus agentes. Además, como se mencionó, puedes usar Azure AI Agent Service como un orquestador para tus agentes construidos en Autogen o Semantic Kernel, lo que facilitaría el acceso al ecosistema de Azure. ## Referencias - [1] - [Azure Agent Service](https://techcommunity.microsoft.com/blog/azure-ai-services-blog/introducing-azure-ai-agent-service/4298357) - [2] - [Semantic Kernel and Autogen](https://devblogs.microsoft.com/semantic-kernel/microsofts-agentic-ai-frameworks-autogen-and-semantic-kernel/) - [3] - [Semantic Kernel Agent Framework](https://learn.microsoft.com/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp) - [4] - [Azure AI Agent service](https://learn.microsoft.com/azure/ai-services/agents/overview) - [5] - [Using Azure AI Agent Service with AutoGen / Semantic Kernel to build a multi-agent's solution](https://techcommunity.microsoft.com/blog/educatordeveloperblog/using-azure-ai-agent-service-with-autogen--semantic-kernel-to-build-a-multi-agen/4363121) **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en IA. Si bien nos esforzamos por lograr precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que surjan del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/02-explore-agentic-frameworks/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/02-explore-agentic-frameworks/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 12836 }
# Principios de Diseño Agéntico para IA ## Introducción Existen muchas formas de abordar la construcción de Sistemas de IA Agénticos. Dado que la ambigüedad es una característica y no un defecto en el diseño de IA Generativa, a veces es difícil para los ingenieros saber por dónde empezar. Hemos creado un conjunto de Principios de Diseño centrados en el usuario para ayudar a los desarrolladores a construir sistemas agénticos enfocados en los clientes y resolver sus necesidades empresariales. Estos principios de diseño no son una arquitectura prescriptiva, sino más bien un punto de partida para los equipos que están definiendo y construyendo experiencias agénticas. En general, los agentes deben: - Ampliar y escalar las capacidades humanas (generación de ideas, resolución de problemas, automatización, etc.) - Rellenar vacíos de conocimiento (ponerse al día en dominios de conocimiento, traducción, etc.) - Facilitar y apoyar la colaboración en las formas en que preferimos trabajar con otros - Ayudarnos a ser mejores versiones de nosotros mismos (por ejemplo, entrenador de vida/gestor de tareas, ayudándonos a aprender habilidades de regulación emocional y mindfulness, construir resiliencia, etc.) ## En Esta Lección Veremos - Qué son los Principios de Diseño Agéntico - Qué pautas seguir al implementar estos principios de diseño - Ejemplos de cómo usar estos principios de diseño ## Objetivos de Aprendizaje Al completar esta lección, serás capaz de: 1. Explicar qué son los Principios de Diseño Agéntico 2. Explicar las pautas para usar los Principios de Diseño Agéntico 3. Comprender cómo construir un agente utilizando los Principios de Diseño Agéntico ## Los Principios de Diseño Agéntico ![Principios de Diseño Agéntico](../../../translated_images/agentic-design-principles.9f32a64bb6e2aa5a1bdffb70111aa724058bc248b1a3dd3c6661344015604cff.es.png?WT.mc_id=academic-105485-koreyst) ### Agente (Espacio) Este es el entorno en el que opera el agente. Estos principios informan cómo diseñamos agentes para interactuar en mundos físicos y digitales. - **Conectar, no reemplazar** – ayuda a conectar a las personas con otras personas, eventos y conocimientos accionables para facilitar la colaboración y la conexión. - Los agentes ayudan a conectar eventos, conocimientos y personas. - Los agentes acercan a las personas. No están diseñados para reemplazar o minimizar a las personas. - **Fácilmente accesible pero ocasionalmente invisible** – el agente opera mayormente en segundo plano y solo interviene cuando es relevante y apropiado. - El agente es fácilmente descubrible y accesible para usuarios autorizados en cualquier dispositivo o plataforma. - El agente admite entradas y salidas multimodales (sonido, voz, texto, etc.). - El agente puede cambiar sin problemas entre primer plano y segundo plano; entre ser proactivo y reactivo, dependiendo de las necesidades del usuario. - El agente puede operar de forma invisible, pero su proceso en segundo plano y su colaboración con otros agentes son transparentes y controlables para el usuario. ### Agente (Tiempo) Esto se refiere a cómo opera el agente a lo largo del tiempo. Estos principios informan cómo diseñamos agentes que interactúan a través del pasado, presente y futuro. - **Pasado**: Reflexionar sobre la historia que incluye tanto el estado como el contexto. - El agente proporciona resultados más relevantes basados en un análisis más rico de datos históricos más allá del evento, personas o estados. - El agente crea conexiones a partir de eventos pasados y reflexiona activamente sobre la memoria para interactuar con situaciones actuales. - **Presente**: Más que notificar, motivar. - El agente adopta un enfoque integral para interactuar con las personas. Cuando ocurre un evento, el agente va más allá de una notificación estática u otra formalidad estática. Puede simplificar flujos o generar pistas dinámicamente para dirigir la atención del usuario en el momento adecuado. - El agente entrega información basada en el contexto ambiental, cambios sociales y culturales, y adaptada a la intención del usuario. - La interacción con el agente puede ser gradual, evolucionando/creciendo en complejidad para empoderar a los usuarios a largo plazo. - **Futuro**: Adaptarse y evolucionar. - El agente se adapta a diversos dispositivos, plataformas y modalidades. - El agente se adapta al comportamiento del usuario, a sus necesidades de accesibilidad y es totalmente personalizable. - El agente se moldea y evoluciona a través de una interacción continua con el usuario. ### Agente (Núcleo) Estos son los elementos clave en el núcleo del diseño de un agente. - **Aceptar la incertidumbre pero establecer confianza**. - Se espera cierto nivel de incertidumbre en el agente. La incertidumbre es un elemento clave del diseño agéntico. - La confianza y la transparencia son capas fundamentales del diseño de agentes. - Los humanos tienen control sobre cuándo el agente está encendido/apagado, y el estado del agente es claramente visible en todo momento. ## Pautas Para Implementar Estos Principios Cuando utilices los principios de diseño mencionados anteriormente, sigue estas pautas: 1. **Transparencia**: Informa al usuario que se está utilizando IA, cómo funciona (incluidas acciones pasadas) y cómo dar retroalimentación y modificar el sistema. 2. **Control**: Permite que el usuario personalice, especifique preferencias y personalice el sistema y sus atributos (incluida la capacidad de olvidar). 3. **Consistencia**: Busca experiencias consistentes y multimodales en dispositivos y puntos de interacción. Usa elementos de UI/UX familiares cuando sea posible (por ejemplo, ícono de micrófono para interacción por voz) y reduce la carga cognitiva del usuario tanto como sea posible (por ejemplo, respuestas concisas, ayudas visuales y contenido de "Aprender Más"). ## Cómo Diseñar un Agente de Viajes Usando Estos Principios y Pautas Imagina que estás diseñando un Agente de Viajes, así es como podrías pensar en usar los Principios de Diseño y las Pautas: 1. **Transparencia** – Informa al usuario que el Agente de Viajes es un agente habilitado por IA. Proporciona algunas instrucciones básicas sobre cómo empezar (por ejemplo, un mensaje de "Hola", ejemplos de preguntas). Documenta esto claramente en la página del producto. Muestra la lista de preguntas que el usuario ha hecho en el pasado. Deja claro cómo dar retroalimentación (pulgares arriba y abajo, botón "Enviar Comentarios", etc.). Articula claramente si el agente tiene restricciones de uso o de temas. 2. **Control** – Asegúrate de que sea claro cómo el usuario puede modificar el agente después de haber sido creado con cosas como el System Prompt. Permite al usuario elegir cuán detallado es el agente, su estilo de escritura y cualquier limitación sobre qué temas no debe abordar. Permite al usuario ver y eliminar cualquier archivo o dato asociado, preguntas y conversaciones pasadas. 3. **Consistencia** – Asegúrate de que los íconos para Compartir Pregunta, añadir un archivo o foto y etiquetar a alguien o algo sean estándar y reconocibles. Usa el ícono de clip para indicar la carga/compartición de archivos con el agente, y un ícono de imagen para indicar la carga de gráficos. ## Recursos Adicionales - [Practices for Governing Agentic AI Systems | OpenAI](https://openai.com) - [The HAX Toolkit Project - Microsoft Research](https://microsoft.com) - [Responsible AI Toolbox](https://responsibleaitoolbox.ai) **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por lograr precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse como la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/03-agentic-design-patterns/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/03-agentic-design-patterns/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 8203 }
# Patrón de Diseño de Uso de Herramientas ## Introducción En esta lección, buscamos responder las siguientes preguntas: - ¿Qué es el patrón de diseño de uso de herramientas? - ¿Cuáles son los casos de uso en los que se puede aplicar? - ¿Cuáles son los elementos/bloques necesarios para implementar este patrón de diseño? - ¿Qué consideraciones especiales existen al usar el patrón de diseño de uso de herramientas para construir agentes de IA confiables? ## Objetivos de Aprendizaje Al completar esta lección, serás capaz de: - Definir el patrón de diseño de uso de herramientas y su propósito. - Identificar casos de uso donde este patrón de diseño es aplicable. - Comprender los elementos clave necesarios para implementar el patrón de diseño. - Reconocer consideraciones para garantizar la confiabilidad en agentes de IA que utilicen este patrón de diseño. ## ¿Qué es el patrón de diseño de uso de herramientas? El **Patrón de Diseño de Uso de Herramientas** se centra en dotar a los Modelos de Lenguaje Extensos (LLMs) de la capacidad de interactuar con herramientas externas para alcanzar objetivos específicos. Las herramientas son código que puede ser ejecutado por un agente para realizar acciones. Una herramienta puede ser una función simple como una calculadora, o una llamada a una API de un servicio de terceros, como la consulta de precios de acciones o un pronóstico del clima. En el contexto de los agentes de IA, las herramientas están diseñadas para ser ejecutadas por agentes en respuesta a **llamadas a funciones generadas por el modelo**. ## ¿Cuáles son los casos de uso en los que se puede aplicar? Los agentes de IA pueden aprovechar las herramientas para completar tareas complejas, recuperar información o tomar decisiones. El patrón de diseño de uso de herramientas se utiliza con frecuencia en escenarios que requieren interacción dinámica con sistemas externos, como bases de datos, servicios web o intérpretes de código. Esta capacidad es útil para una variedad de casos de uso, entre ellos: - **Recuperación Dinámica de Información:** Los agentes pueden consultar APIs externas o bases de datos para obtener datos actualizados (por ejemplo, realizar consultas a una base de datos SQLite para análisis de datos, obtener precios de acciones o información meteorológica). - **Ejecución e Interpretación de Código:** Los agentes pueden ejecutar código o scripts para resolver problemas matemáticos, generar informes o realizar simulaciones. - **Automatización de Flujos de Trabajo:** Automatización de tareas repetitivas o flujos de trabajo de varios pasos mediante la integración de herramientas como planificadores de tareas, servicios de correo electrónico o canalizaciones de datos. - **Atención al Cliente:** Los agentes pueden interactuar con sistemas CRM, plataformas de tickets o bases de conocimiento para resolver consultas de usuarios. - **Generación y Edición de Contenido:** Los agentes pueden utilizar herramientas como correctores gramaticales, resúmenes de texto o evaluadores de seguridad de contenido para asistir en tareas de creación de contenido. ## ¿Cuáles son los elementos/bloques necesarios para implementar el patrón de diseño de uso de herramientas? ### Llamadas a Funciones/Herramientas La llamada a funciones es la principal forma en que permitimos que los LLMs interactúen con herramientas. A menudo verás que los términos "Función" y "Herramienta" se usan de manera intercambiable porque las "funciones" (bloques de código reutilizable) son las "herramientas" que los agentes utilizan para llevar a cabo tareas. Para que se invoque el código de una función, un LLM debe comparar la solicitud del usuario con la descripción de la función. Para ello, se envía al LLM un esquema que contiene las descripciones de todas las funciones disponibles. El LLM selecciona la función más adecuada para la tarea y devuelve su nombre y argumentos. La función seleccionada se invoca, su respuesta se envía de vuelta al LLM, que utiliza la información para responder a la solicitud del usuario. Para que los desarrolladores implementen la llamada a funciones para agentes, necesitarán: 1. Un modelo LLM que soporte llamadas a funciones. 2. Un esquema que contenga las descripciones de las funciones. 3. El código de cada función descrita. Usaremos el ejemplo de obtener la hora actual en una ciudad para ilustrar: - **Inicializar un LLM que soporte llamadas a funciones:** No todos los modelos soportan llamadas a funciones, por lo que es importante verificar que el LLM que estás utilizando lo haga. [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling) soporta llamadas a funciones. Podemos comenzar iniciando el cliente de Azure OpenAI. ```python # Initialize the Azure OpenAI client client = AzureOpenAI( azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), api_version="2024-05-01-preview" ) ``` - **Crear un Esquema de Función:** A continuación, definiremos un esquema JSON que contiene el nombre de la función, una descripción de lo que hace la función, y los nombres y descripciones de los parámetros de la función. Luego tomaremos este esquema y lo pasaremos al cliente creado anteriormente, junto con la solicitud del usuario para encontrar la hora en San Francisco. Es importante notar que lo que se devuelve es una **llamada a herramienta**, **no** la respuesta final a la pregunta. Como mencionamos antes, el LLM devuelve el nombre de la función que seleccionó para la tarea y los argumentos que se le pasarán. ```python # Function description for the model to read tools = [ { "type": "function", "function": { "name": "get_current_time", "description": "Get the current time in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name, e.g. San Francisco", }, }, "required": ["location"], }, } } ] ``` ```python # Initial user message messages = [{"role": "user", "content": "What's the current time in San Francisco"}] # First API call: Ask the model to use the function response = client.chat.completions.create( model=deployment_name, messages=messages, tools=tools, tool_choice="auto", ) # Process the model's response response_message = response.choices[0].message messages.append(response_message) print("Model's response:") print(response_message) ``` ```bash Model's response: ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')]) ``` - **El código de la función necesario para llevar a cabo la tarea:** Ahora que el LLM ha elegido qué función necesita ejecutarse, el código que realiza la tarea debe implementarse y ejecutarse. Podemos implementar el código para obtener la hora actual en Python. También necesitaremos escribir el código para extraer el nombre y los argumentos del `response_message` para obtener el resultado final. ```python def get_current_time(location): """Get the current time for a given location""" print(f"get_current_time called with location: {location}") location_lower = location.lower() for key, timezone in TIMEZONE_DATA.items(): if key in location_lower: print(f"Timezone found for {key}") current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p") return json.dumps({ "location": location, "current_time": current_time }) print(f"No timezone data found for {location_lower}") return json.dumps({"location": location, "current_time": "unknown"}) ``` ```python # Handle function calls if response_message.tool_calls: for tool_call in response_message.tool_calls: if tool_call.function.name == "get_current_time": function_args = json.loads(tool_call.function.arguments) time_response = get_current_time( location=function_args.get("location") ) messages.append({ "tool_call_id": tool_call.id, "role": "tool", "name": "get_current_time", "content": time_response, }) else: print("No tool calls were made by the model.") # Second API call: Get the final response from the model final_response = client.chat.completions.create( model=deployment_name, messages=messages, ) return final_response.choices[0].message.content ``` ```bash get_current_time called with location: San Francisco Timezone found for san francisco The current time in San Francisco is 09:24 AM. ``` La llamada a funciones es el núcleo de la mayoría, si no de todos, los diseños de uso de herramientas por agentes. Sin embargo, implementarla desde cero puede ser un desafío. Como aprendimos en [Lección 2](../../../02-explore-agentic-frameworks), los marcos agenticos nos proporcionan bloques de construcción predefinidos para implementar el uso de herramientas. ### Ejemplos de Uso de Herramientas con Marcos Agenticos - ### **[Semantic Kernel](https://learn.microsoft.com/azure/ai-services/agents/overview)** Semantic Kernel es un marco de IA de código abierto para desarrolladores de .NET, Python y Java que trabajan con LLMs. Simplifica el proceso de usar llamadas a funciones describiendo automáticamente tus funciones y sus parámetros al modelo mediante un proceso llamado [serialización](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions). También maneja la comunicación entre el modelo y tu código. Otra ventaja de usar un marco agentico como Semantic Kernel es que te permite acceder a herramientas predefinidas como [File Search](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step4_assistant_tool_file_search.py) e [Interpreter de Código](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py). El siguiente diagrama ilustra el proceso de llamadas a funciones con Semantic Kernel: ![function calling](../../../translated_images/functioncalling-diagram.b5493ea5154ad8e3e4940d2e36a49101eec1398948e5d1039942203b4f5a4209.es.png) En Semantic Kernel, las funciones/herramientas se llaman [Plugins](https://learn.microsoft.com/semantic-kernel/concepts/plugins/?pivots=programming-language-python). Podemos convertir la función `get_current_time` function we saw earlier into a plugin by turning it into a class with the function in it. We can also import the `kernel_function` utilizando un decorador, que toma la descripción de la función. Cuando luego creas un kernel con el `GetCurrentTimePlugin`, el kernel serializará automáticamente la función y sus parámetros, creando el esquema para enviarlo al LLM en el proceso. ```python from semantic_kernel.functions import kernel_function class GetCurrentTimePlugin: async def __init__(self, location): self.location = location @kernel_function( description="Get the current time for a given location" ) def get_current_time(location: str = ""): ... ``` ```python from semantic_kernel import Kernel # Create the kernel kernel = Kernel() # Create the plugin get_current_time_plugin = GetCurrentTimePlugin(location) # Add the plugin to the kernel kernel.add_plugin(get_current_time_plugin) ``` - ### **[Azure AI Agent Service](https://learn.microsoft.com/azure/ai-services/agents/overview)** Azure AI Agent Service es un marco agentico más reciente diseñado para permitir a los desarrolladores construir, implementar y escalar agentes de IA de alta calidad y extensibles de manera segura, sin necesidad de gestionar los recursos subyacentes de cómputo y almacenamiento. Es particularmente útil para aplicaciones empresariales, ya que es un servicio totalmente gestionado con seguridad de nivel empresarial. Comparado con el desarrollo directo con la API de LLM, Azure AI Agent Service ofrece algunas ventajas, como: - Llamadas a herramientas automáticas: no es necesario analizar una llamada a herramienta, invocar la herramienta y manejar la respuesta; todo esto ahora se realiza del lado del servidor. - Gestión segura de datos: en lugar de gestionar tu propio estado de conversación, puedes confiar en los hilos para almacenar toda la información que necesitas. - Herramientas predefinidas: Herramientas que puedes usar para interactuar con tus fuentes de datos, como Bing, Azure AI Search y Azure Functions. Las herramientas disponibles en Azure AI Agent Service se dividen en dos categorías: 1. Herramientas de Conocimiento: - [Integración con Bing Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview) - [File Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/file-search?tabs=python&pivots=overview) - [Azure AI Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search) 2. Herramientas de Acción: - [Llamadas a Funciones](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/function-calling?tabs=python&pivots=overview) - [Intérprete de Código](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/code-interpreter?tabs=python&pivots=overview) - [Herramientas Definidas por OpenAI](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/openapi-spec?tabs=python&pivots=overview) - [Azure Functions](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-functions?pivots=overview) El servicio de agentes permite utilizar estas herramientas juntas como un `toolset`. It also utilizes `threads` which keep track of the history of messages from a particular conversation. Imagine you are a sales agent at a company called Contoso. You want to develop a conversational agent that can answer questions about your sales data. The image below illustrates how you could use Azure AI Agent Service to analyze your sales data: ![Agentic Service In Action](../../../translated_images/agent-service-in-action.8c2d8aa8e9d91feeb29549b3fde529f8332b243875154d03907616a69198afbc.tw.jpg?WT.mc_id=academic-105485-koreyst) To use any of these tools with the service we can create a client and define a tool or toolset. To implement this practically we can use the Python code below. The LLM will be able to look at the toolset and decide whether to use the user created function, `fetch_sales_data_using_sqlite_query`, o el intérprete de código predefinido dependiendo de la solicitud del usuario. ```python import os from azure.ai.projects import AIProjectClient from azure.identity import DefaultAzureCredential from fecth_sales_data_functions import fetch_sales_data_using_sqlite_query # fetch_sales_data_using_sqlite_query function which can be found in a fecth_sales_data_functions.py file. from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool project_client = AIProjectClient.from_connection_string( credential=DefaultAzureCredential(), conn_str=os.environ["PROJECT_CONNECTION_STRING"], ) # Initialize function calling agent with the fetch_sales_data_using_sqlite_query function and adding it to the toolset fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query) toolset = ToolSet() toolset.add(fetch_data_function) # Initialize Code Interpreter tool and adding it to the toolset. code_interpreter = code_interpreter = CodeInterpreterTool() toolset = ToolSet() toolset.add(code_interpreter) agent = project_client.agents.create_agent( model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent", toolset=toolset ) ``` ## ¿Cuáles son las consideraciones especiales para usar el patrón de diseño de uso de herramientas para construir agentes de IA confiables? Una preocupación común con el SQL generado dinámicamente por LLMs es la seguridad, particularmente el riesgo de inyección SQL o acciones maliciosas, como borrar o alterar la base de datos. Aunque estas preocupaciones son válidas, pueden mitigarse de manera efectiva configurando adecuadamente los permisos de acceso a la base de datos. Para la mayoría de las bases de datos, esto implica configurarlas como de solo lectura. Para servicios de bases de datos como PostgreSQL o Azure SQL, la aplicación debe asignarse a un rol de solo lectura (SELECT). Ejecutar la aplicación en un entorno seguro mejora aún más la protección. En escenarios empresariales, los datos suelen extraerse y transformarse desde sistemas operativos hacia una base de datos de solo lectura o un almacén de datos con un esquema amigable para el usuario. Este enfoque asegura que los datos sean seguros, estén optimizados para el rendimiento y la accesibilidad, y que la aplicación tenga acceso restringido de solo lectura. ## Recursos Adicionales - [Azure AI Agents Service Workshop](https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/) - [Contoso Creative Writer Multi-Agent Workshop](https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop) - [Semantic Kernel Function Calling Tutorial](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions) - [Semantic Kernel Code Interpreter](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py) - [Autogen Tools](https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html) **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por lograr precisión, tenga en cuenta que las traducciones automáticas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse como la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que surjan del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/04-tool-use/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/04-tool-use/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 19857 }
# Agentic RAG Esta lección ofrece una visión completa de Agentic Retrieval-Augmented Generation (Agentic RAG), un paradigma emergente de IA en el que los modelos de lenguaje grandes (LLMs) planifican de forma autónoma sus próximos pasos mientras extraen información de fuentes externas. A diferencia de los patrones estáticos de recuperación y lectura, Agentic RAG implica llamadas iterativas al LLM, intercaladas con llamadas a herramientas o funciones y salidas estructuradas. El sistema evalúa los resultados, refina consultas, invoca herramientas adicionales si es necesario y continúa este ciclo hasta alcanzar una solución satisfactoria. ## Introducción Esta lección cubrirá: - **Entender Agentic RAG:** Aprende sobre este paradigma emergente en IA donde los modelos de lenguaje grandes (LLMs) planifican de forma autónoma sus próximos pasos mientras obtienen información de fuentes de datos externas. - **Comprender el estilo iterativo Maker-Checker:** Entiende el ciclo de llamadas iterativas al LLM, intercaladas con llamadas a herramientas o funciones y salidas estructuradas, diseñado para mejorar la precisión y manejar consultas malformadas. - **Explorar aplicaciones prácticas:** Identifica escenarios donde Agentic RAG sobresale, como entornos donde la precisión es clave, interacciones complejas con bases de datos y flujos de trabajo extensos. ## Objetivos de aprendizaje Al completar esta lección, sabrás cómo/entenderás: - **Comprender Agentic RAG:** Aprende sobre este paradigma emergente en IA donde los modelos de lenguaje grandes (LLMs) planifican de forma autónoma sus próximos pasos mientras obtienen información de fuentes de datos externas. - **Estilo iterativo Maker-Checker:** Comprende el concepto de un ciclo de llamadas iterativas al LLM, intercaladas con llamadas a herramientas o funciones y salidas estructuradas, diseñado para mejorar la precisión y manejar consultas malformadas. - **Controlar el proceso de razonamiento:** Entiende la capacidad del sistema para hacerse cargo de su propio proceso de razonamiento, tomando decisiones sobre cómo abordar problemas sin depender de caminos predefinidos. - **Flujo de trabajo:** Aprende cómo un modelo agente decide de forma independiente recuperar informes de tendencias de mercado, identificar datos de competidores, correlacionar métricas internas de ventas, sintetizar hallazgos y evaluar estrategias. - **Bucles iterativos, integración de herramientas y memoria:** Descubre cómo el sistema se basa en un patrón de interacción en bucle, manteniendo estado y memoria a lo largo de los pasos para evitar repeticiones y tomar decisiones informadas. - **Manejo de modos de fallo y autocorrección:** Explora los mecanismos robustos de autocorrección del sistema, incluyendo iteración y reconsulta, uso de herramientas de diagnóstico y recurrir a supervisión humana cuando sea necesario. - **Límites de la agencia:** Comprende las limitaciones de Agentic RAG, centrándote en la autonomía específica del dominio, la dependencia de infraestructura y el respeto a las directrices. - **Casos de uso prácticos y valor:** Identifica escenarios donde Agentic RAG brilla, como entornos donde la precisión es esencial, interacciones complejas con bases de datos y flujos de trabajo extensos. - **Gobernanza, transparencia y confianza:** Aprende sobre la importancia de la gobernanza y la transparencia, incluyendo razonamiento explicable, control de sesgos y supervisión humana. ## ¿Qué es Agentic RAG? Agentic Retrieval-Augmented Generation (Agentic RAG) es un paradigma emergente en IA donde los modelos de lenguaje grandes (LLMs) planifican de forma autónoma sus próximos pasos mientras extraen información de fuentes externas. A diferencia de los patrones estáticos de recuperación y lectura, Agentic RAG implica llamadas iterativas al LLM, intercaladas con llamadas a herramientas o funciones y salidas estructuradas. El sistema evalúa los resultados, refina consultas, invoca herramientas adicionales si es necesario y continúa este ciclo hasta lograr una solución satisfactoria. Este estilo iterativo “maker-checker” mejora la precisión, maneja consultas malformadas y garantiza resultados de alta calidad. El sistema asume activamente el control de su proceso de razonamiento, reescribiendo consultas fallidas, eligiendo diferentes métodos de recuperación e integrando múltiples herramientas, como búsquedas vectoriales en Azure AI Search, bases de datos SQL o APIs personalizadas, antes de finalizar su respuesta. La cualidad distintiva de un sistema agente es su capacidad para controlar su proceso de razonamiento. Las implementaciones tradicionales de RAG dependen de caminos predefinidos, pero un sistema agente determina de forma autónoma la secuencia de pasos en función de la calidad de la información que encuentra. ## Definiendo Agentic Retrieval-Augmented Generation (Agentic RAG) Agentic Retrieval-Augmented Generation (Agentic RAG) es un paradigma emergente en el desarrollo de IA donde los LLMs no solo obtienen información de fuentes de datos externas, sino que también planifican de forma autónoma sus próximos pasos. A diferencia de los patrones estáticos de recuperación y lectura o las secuencias de prompts cuidadosamente diseñadas, Agentic RAG implica un ciclo de llamadas iterativas al LLM, intercaladas con llamadas a herramientas o funciones y salidas estructuradas. En cada paso, el sistema evalúa los resultados obtenidos, decide si refinar sus consultas, invoca herramientas adicionales si es necesario y continúa este ciclo hasta lograr una solución satisfactoria. Este estilo iterativo “maker-checker” está diseñado para mejorar la precisión, manejar consultas malformadas a bases de datos estructuradas (por ejemplo, NL2SQL) y garantizar resultados equilibrados y de alta calidad. En lugar de depender únicamente de cadenas de prompts cuidadosamente diseñadas, el sistema asume activamente el control de su proceso de razonamiento. Puede reescribir consultas que fallan, elegir diferentes métodos de recuperación e integrar múltiples herramientas, como búsquedas vectoriales en Azure AI Search, bases de datos SQL o APIs personalizadas, antes de finalizar su respuesta. Esto elimina la necesidad de marcos de orquestación excesivamente complejos. En cambio, un bucle relativamente simple de “llamada al LLM → uso de herramienta → llamada al LLM → …” puede generar salidas sofisticadas y bien fundamentadas. ![Ciclo central de Agentic RAG](../../../translated_images/agentic-rag-core-loop.2224925a913fb3439f518bda61a40096ddf6aa432a11c9b5bba8d0d625e47b79.es.png) ## Controlar el proceso de razonamiento La cualidad distintiva que hace que un sistema sea “agente” es su capacidad para controlar su propio proceso de razonamiento. Las implementaciones tradicionales de RAG a menudo dependen de que los humanos definan previamente un camino para el modelo: una cadena de razonamiento que describe qué recuperar y cuándo. Pero cuando un sistema es verdaderamente agente, decide internamente cómo abordar el problema. No solo ejecuta un guion; determina de forma autónoma la secuencia de pasos en función de la calidad de la información que encuentra. Por ejemplo, si se le pide que cree una estrategia de lanzamiento de producto, no se basa únicamente en un prompt que detalle todo el flujo de trabajo de investigación y toma de decisiones. En cambio, el modelo agente decide de forma independiente: 1. Recuperar informes de tendencias actuales del mercado usando Bing Web Grounding. 2. Identificar datos relevantes de competidores usando Azure AI Search. 3. Correlacionar métricas internas de ventas históricas usando Azure SQL Database. 4. Sintetizar los hallazgos en una estrategia cohesiva orquestada mediante Azure OpenAI Service. 5. Evaluar la estrategia en busca de brechas o inconsistencias, iniciando otra ronda de recuperación si es necesario. Todos estos pasos—refinar consultas, elegir fuentes, iterar hasta estar “satisfecho” con la respuesta—son decididos por el modelo, no predefinidos por un humano. ## Bucles iterativos, integración de herramientas y memoria ![Arquitectura de integración de herramientas](../../../translated_images/tool-integration.7b05a923e3278bf1fd2972faa228fb2ac725f166ed084362b031a24bffd26287.es.png) Un sistema agente se basa en un patrón de interacción en bucle: - **Llamada inicial:** El objetivo del usuario (es decir, el prompt del usuario) se presenta al LLM. - **Invocación de herramientas:** Si el modelo identifica información faltante o instrucciones ambiguas, selecciona una herramienta o método de recuperación—como una consulta a una base de datos vectorial (por ejemplo, Azure AI Search Hybrid Search sobre datos privados) o una llamada estructurada a SQL—para obtener más contexto. - **Evaluación y refinamiento:** Tras revisar los datos obtenidos, el modelo decide si la información es suficiente. Si no, refina la consulta, prueba una herramienta diferente o ajusta su enfoque. - **Repetir hasta estar satisfecho:** Este ciclo continúa hasta que el modelo determina que tiene suficiente claridad y evidencia para entregar una respuesta final bien fundamentada. - **Memoria y estado:** Dado que el sistema mantiene estado y memoria a lo largo de los pasos, puede recordar intentos previos y sus resultados, evitando bucles repetitivos y tomando decisiones más informadas a medida que avanza. Con el tiempo, esto crea un sentido de comprensión evolutiva, permitiendo al modelo navegar tareas complejas y de múltiples pasos sin requerir que un humano intervenga constantemente o redefina el prompt. ## Manejo de modos de fallo y autocorrección La autonomía de Agentic RAG también incluye mecanismos robustos de autocorrección. Cuando el sistema se encuentra con obstáculos—como recuperar documentos irrelevantes o enfrentar consultas malformadas—puede: - **Iterar y reconsultar:** En lugar de devolver respuestas de bajo valor, el modelo intenta nuevas estrategias de búsqueda, reescribe consultas a bases de datos o explora conjuntos de datos alternativos. - **Usar herramientas de diagnóstico:** El sistema puede invocar funciones adicionales diseñadas para ayudarle a depurar sus pasos de razonamiento o confirmar la corrección de los datos obtenidos. Herramientas como Azure AI Tracing serán importantes para habilitar una observabilidad y monitoreo robustos. - **Recurrir a supervisión humana:** Para escenarios críticos o que fallan repetidamente, el modelo puede señalar incertidumbre y solicitar orientación humana. Una vez que el humano proporciona retroalimentación correctiva, el modelo puede incorporar esa lección en adelante. Este enfoque iterativo y dinámico permite al modelo mejorar continuamente, asegurando que no sea solo un sistema de un intento, sino uno que aprende de sus errores durante una sesión determinada. ![Mecanismo de autocorrección](../../../translated_images/self-correction.3d42c31baf4a476bb89313cec58efb196b0e97959c04d7439cc23d27ef1242ac.es.png) ## Límites de la agencia A pesar de su autonomía dentro de una tarea, Agentic RAG no es análogo a la Inteligencia General Artificial. Sus capacidades “agentes” están confinadas a las herramientas, fuentes de datos y políticas proporcionadas por los desarrolladores humanos. No puede inventar sus propias herramientas ni operar fuera de los límites del dominio establecidos. Más bien, sobresale en la orquestación dinámica de los recursos disponibles. Las diferencias clave con formas más avanzadas de IA incluyen: 1. **Autonomía específica del dominio:** Los sistemas Agentic RAG están enfocados en lograr objetivos definidos por el usuario dentro de un dominio conocido, empleando estrategias como la reescritura de consultas o la selección de herramientas para mejorar los resultados. 2. **Dependencia de infraestructura:** Las capacidades del sistema dependen de las herramientas y datos integrados por los desarrolladores. No puede superar estos límites sin intervención humana. 3. **Respeto a las directrices:** Las pautas éticas, reglas de cumplimiento y políticas empresariales siguen siendo muy importantes. La libertad del agente siempre está limitada por medidas de seguridad y mecanismos de supervisión (¿esperemos?). ## Casos de uso prácticos y valor Agentic RAG sobresale en escenarios que requieren refinamiento iterativo y precisión: 1. **Entornos donde la precisión es clave:** En verificaciones de cumplimiento, análisis regulatorio o investigaciones legales, el modelo agente puede verificar repetidamente hechos, consultar múltiples fuentes y reescribir consultas hasta producir una respuesta completamente revisada. 2. **Interacciones complejas con bases de datos:** Al trabajar con datos estructurados donde las consultas a menudo pueden fallar o necesitar ajustes, el sistema puede refinar autónomamente sus consultas usando Azure SQL o Microsoft Fabric OneLake, asegurando que la recuperación final se alinee con la intención del usuario. 3. **Flujos de trabajo extensos:** Las sesiones más largas pueden evolucionar a medida que surgen nuevas informaciones. Agentic RAG puede incorporar continuamente nuevos datos, ajustando estrategias a medida que aprende más sobre el problema. ## Gobernanza, transparencia y confianza A medida que estos sistemas se vuelven más autónomos en su razonamiento, la gobernanza y la transparencia son cruciales: - **Razonamiento explicable:** El modelo puede proporcionar un registro de auditoría de las consultas que realizó, las fuentes que consultó y los pasos de razonamiento que siguió para llegar a su conclusión. Herramientas como Azure AI Content Safety y Azure AI Tracing / GenAIOps pueden ayudar a mantener la transparencia y mitigar riesgos. - **Control de sesgos y recuperación equilibrada:** Los desarrolladores pueden ajustar estrategias de recuperación para garantizar que se consideren fuentes de datos equilibradas y representativas, y auditar regularmente las salidas para detectar sesgos o patrones desbalanceados usando modelos personalizados para organizaciones avanzadas de ciencia de datos con Azure Machine Learning. - **Supervisión humana y cumplimiento:** Para tareas sensibles, la revisión humana sigue siendo esencial. Agentic RAG no reemplaza el juicio humano en decisiones críticas, sino que lo complementa entregando opciones más exhaustivamente revisadas. Tener herramientas que proporcionen un registro claro de acciones es esencial. Sin ellas, depurar un proceso de múltiples pasos puede ser muy difícil. A continuación, un ejemplo de ejecución de un agente de Literal AI (la empresa detrás de Chainlit): ![Ejemplo de ejecución de agente](../../../translated_images/AgentRunExample.27e2df23ad898772d1b3e7a3e3cd4615378e10dfda87ae8f06b4748bf8eea97d.es.png) ![Ejemplo de ejecución de agente 2](../../../translated_images/AgentRunExample2.c0e8c78b1f2540a641515e60035abcc6a9c5e3688bae143eb6c559dd37cdee9f.es.png) ## Conclusión Agentic RAG representa una evolución natural en cómo los sistemas de IA manejan tareas complejas e intensivas en datos. Al adoptar un patrón de interacción en bucle, seleccionar herramientas de forma autónoma y refinar consultas hasta lograr un resultado de alta calidad, el sistema va más allá de simplemente seguir prompts estáticos, convirtiéndose en un tomador de decisiones más adaptable y consciente del contexto. Aunque sigue estando limitado por infraestructuras definidas por humanos y pautas éticas, estas capacidades agentes permiten interacciones de IA más ricas, dinámicas y, en última instancia, más útiles tanto para empresas como para usuarios finales. ## Recursos adicionales - Implementar Retrieval Augmented Generation (RAG) con Azure OpenAI Service: Aprende cómo usar tus propios datos con Azure OpenAI Service. [Este módulo de Microsoft Learn proporciona una guía completa sobre cómo implementar RAG](https://learn.microsoft.com/training/modules/use-own-data-azure-openai) - Evaluación de aplicaciones de IA generativa con Azure AI Foundry: Este artículo cubre la evaluación y comparación de modelos en conjuntos de datos públicos, incluyendo [aplicaciones de IA agente y arquitecturas RAG](https://learn.microsoft.com/azure/ai-studio/concepts/evaluation-approach-gen-ai) - [What is Agentic RAG | Weaviate](https://weaviate.io/blog/what-is-agentic-rag) - [Agentic RAG: A Complete Guide to Agent-Based Retrieval Augmented Generation – News from generation RAG](https://ragaboutit.com/agentic-rag-a-complete-guide-to-agent-based-retrieval-augmented-generation/) - [Agentic RAG: turbocharge your RAG with query reformulation and self-query! Hugging Face Open-Source AI Cookbook](https://huggingface.co/learn/cookbook/agent_rag) - [Adding Agentic Layers to RAG](https://youtu.be/aQ4yQXeB1Ss?si=2HUqBzHoeB5tR04U) - [The Future of Knowledge Assistants: Jerry Liu](https://www.youtube.com/watch?v=zeAyuLc_f3Q&t=244s) - [How to Build Agentic RAG Systems](https://www.youtube.com/watch?v=AOSjiXP1jmQ) - [Using Azure AI Foundry Agent Service to scale your AI agents](https://ignite.microsoft.com/sessions/BRK102?source=sessions) ### Artículos académicos - [2303.17651 Self-Refine: Iterative Refinement with Self-Feedback](https://arxiv.org/abs/2303.17651) - [2303.11366 Reflexion: Language Agents with Verbal Reinforcement Learning](https://arxiv.org/abs/2303.11366) - [2305.11738 CRITIC: Large Language Models Can Self-Correct with Tool-Interactive Critiquing](https://arxiv.org/abs/2305.11738) **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por garantizar la precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse como la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/05-agentic-rag/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/05-agentic-rag/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 18134 }
# Construyendo Agentes de IA Confiables ## Introducción En esta lección se cubrirá: - Cómo construir y desplegar Agentes de IA seguros y efectivos. - Consideraciones importantes de seguridad al desarrollar Agentes de IA. - Cómo mantener la privacidad de datos y usuarios al desarrollar Agentes de IA. ## Objetivos de Aprendizaje Al completar esta lección, sabrás cómo: - Identificar y mitigar riesgos al crear Agentes de IA. - Implementar medidas de seguridad para garantizar que los datos y el acceso estén correctamente gestionados. - Crear Agentes de IA que mantengan la privacidad de los datos y ofrezcan una experiencia de usuario de calidad. ## Seguridad Primero, exploremos cómo construir aplicaciones de agentes seguras. La seguridad significa que el agente de IA actúa según lo diseñado. Como creadores de aplicaciones de agentes, contamos con métodos y herramientas para maximizar la seguridad: ### Construcción de un Sistema de Meta-Prompts Si alguna vez has creado una aplicación de IA utilizando Modelos de Lenguaje Extenso (LLMs, por sus siglas en inglés), sabes la importancia de diseñar un prompt o mensaje del sistema robusto. Estos prompts establecen las reglas, instrucciones y directrices meta sobre cómo el LLM interactuará con el usuario y los datos. Para los Agentes de IA, el prompt del sistema es aún más importante, ya que estos agentes necesitarán instrucciones altamente específicas para completar las tareas que hemos diseñado para ellos. Para crear prompts del sistema escalables, podemos utilizar un sistema de meta-prompts para construir uno o más agentes en nuestra aplicación: ![Construcción de un Sistema de Meta-Prompts](../../../translated_images/building-a-metaprompting-system.aa7d6de2100b0ef48c3e1926dab6903026b22fc9d27fc4327162fbbb9caf960f.es.png) #### Paso 1: Crear un Meta-Prompt o Prompt Plantilla El meta-prompt será utilizado por un LLM para generar los prompts del sistema para los agentes que creemos. Lo diseñamos como una plantilla para poder crear múltiples agentes de manera eficiente si es necesario. Aquí tienes un ejemplo de un meta-prompt que podríamos proporcionar al LLM: ```plaintext You are an expert at creating AI agent assitants. You will be provided a company name, role, responsibilites and other information that you will use to provide a system prompt for. To create the system prompt, be descriptive as possible and provide a structure that a system using an LLM can better understand the role and responsibilites of the AI assistant. ``` #### Paso 2: Crear un Prompt Básico El siguiente paso es crear un prompt básico para describir al Agente de IA. Debes incluir el rol del agente, las tareas que realizará y cualquier otra responsabilidad que tenga. Aquí tienes un ejemplo: ```plaintext You are a travel agent for Contoso Travel with that is great at booking flights for customers. To help customers you can perform the following tasks: lookup available flights, book flights, ask for preferences in seating and times for flights, cancel any previously booked flights and alert customers on any delays or cancellations of flights. ``` #### Paso 3: Proporcionar el Prompt Básico al LLM Ahora podemos optimizar este prompt proporcionando el meta-prompt como el prompt del sistema junto con nuestro prompt básico. Esto producirá un prompt mejor diseñado para guiar a nuestros Agentes de IA: ```markdown **Company Name:** Contoso Travel **Role:** Travel Agent Assistant **Objective:** You are an AI-powered travel agent assistant for Contoso Travel, specializing in booking flights and providing exceptional customer service. Your main goal is to assist customers in finding, booking, and managing their flights, all while ensuring that their preferences and needs are met efficiently. **Key Responsibilities:** 1. **Flight Lookup:** - Assist customers in searching for available flights based on their specified destination, dates, and any other relevant preferences. - Provide a list of options, including flight times, airlines, layovers, and pricing. 2. **Flight Booking:** - Facilitate the booking of flights for customers, ensuring that all details are correctly entered into the system. - Confirm bookings and provide customers with their itinerary, including confirmation numbers and any other pertinent information. 3. **Customer Preference Inquiry:** - Actively ask customers for their preferences regarding seating (e.g., aisle, window, extra legroom) and preferred times for flights (e.g., morning, afternoon, evening). - Record these preferences for future reference and tailor suggestions accordingly. 4. **Flight Cancellation:** - Assist customers in canceling previously booked flights if needed, following company policies and procedures. - Notify customers of any necessary refunds or additional steps that may be required for cancellations. 5. **Flight Monitoring:** - Monitor the status of booked flights and alert customers in real-time about any delays, cancellations, or changes to their flight schedule. - Provide updates through preferred communication channels (e.g., email, SMS) as needed. **Tone and Style:** - Maintain a friendly, professional, and approachable demeanor in all interactions with customers. - Ensure that all communication is clear, informative, and tailored to the customer's specific needs and inquiries. **User Interaction Instructions:** - Respond to customer queries promptly and accurately. - Use a conversational style while ensuring professionalism. - Prioritize customer satisfaction by being attentive, empathetic, and proactive in all assistance provided. **Additional Notes:** - Stay updated on any changes to airline policies, travel restrictions, and other relevant information that could impact flight bookings and customer experience. - Use clear and concise language to explain options and processes, avoiding jargon where possible for better customer understanding. This AI assistant is designed to streamline the flight booking process for customers of Contoso Travel, ensuring that all their travel needs are met efficiently and effectively. ``` #### Paso 4: Iterar y Mejorar El valor de este sistema de meta-prompts radica en la capacidad de escalar la creación de prompts para múltiples agentes de manera más sencilla, así como en la mejora continua de los prompts. Es raro que un prompt funcione perfectamente desde el primer intento para todo el caso de uso. Poder realizar pequeños ajustes y mejoras cambiando el prompt básico y ejecutándolo a través del sistema te permitirá comparar y evaluar los resultados. ## Comprendiendo las Amenazas Para construir agentes de IA confiables, es importante entender y mitigar los riesgos y amenazas a los que están expuestos. Veamos algunas de las diferentes amenazas a los Agentes de IA y cómo puedes planificar y prepararte mejor para enfrentarlas. ![Comprendiendo las Amenazas](../../../translated_images/understanding-threats.f8fbe6fe11e025b3085fc91e82d975937ad1d672260a2aeed40458aa41798d0e.es.png) ### Tareas e Instrucciones **Descripción:** Los atacantes intentan cambiar las instrucciones o metas del Agente de IA a través de prompts o manipulando entradas. **Mitigación:** Ejecuta verificaciones de validación y filtros de entrada para detectar prompts potencialmente peligrosos antes de que sean procesados por el Agente de IA. Dado que estos ataques suelen requerir interacciones frecuentes con el Agente, limitar el número de turnos en una conversación es otra manera de prevenir este tipo de ataques. ### Acceso a Sistemas Críticos **Descripción:** Si un Agente de IA tiene acceso a sistemas y servicios que almacenan datos sensibles, los atacantes pueden comprometer la comunicación entre el agente y estos servicios. Estos pueden ser ataques directos o intentos indirectos de obtener información sobre estos sistemas a través del agente. **Mitigación:** Los Agentes de IA deben tener acceso a los sistemas únicamente cuando sea necesario para prevenir este tipo de ataques. La comunicación entre el agente y los sistemas también debe ser segura. Implementar autenticación y control de acceso es otra forma de proteger esta información. ### Sobrecarga de Recursos y Servicios **Descripción:** Los Agentes de IA pueden acceder a diferentes herramientas y servicios para completar tareas. Los atacantes pueden aprovechar esta capacidad para atacar estos servicios enviando un alto volumen de solicitudes a través del Agente de IA, lo que podría resultar en fallos del sistema o altos costos. **Mitigación:** Implementa políticas para limitar el número de solicitudes que un Agente de IA puede realizar a un servicio. Limitar el número de turnos de conversación y solicitudes al Agente de IA es otra manera de prevenir este tipo de ataques. ### Envenenamiento de la Base de Conocimientos **Descripción:** Este tipo de ataque no se dirige directamente al Agente de IA, sino a la base de conocimientos y otros servicios que el agente utilizará. Esto podría implicar corromper los datos o la información que el agente usará para completar una tarea, lo que llevaría a respuestas sesgadas o no deseadas al usuario. **Mitigación:** Realiza verificaciones regulares de los datos que el Agente de IA utilizará en sus flujos de trabajo. Asegúrate de que el acceso a estos datos sea seguro y que solo personas de confianza puedan realizar cambios para evitar este tipo de ataques. ### Errores en Cascada **Descripción:** Los Agentes de IA acceden a diversas herramientas y servicios para completar tareas. Los errores causados por atacantes pueden provocar fallos en otros sistemas conectados al Agente de IA, haciendo que el ataque se propague y sea más difícil de solucionar. **Mitigación:** Una forma de evitar esto es hacer que el Agente de IA opere en un entorno limitado, como realizar tareas en un contenedor Docker, para prevenir ataques directos al sistema. Crear mecanismos de respaldo y lógica de reintento cuando ciertos sistemas respondan con errores es otra manera de prevenir fallos mayores en el sistema. ## Humano en el Bucle Otra forma efectiva de construir sistemas de Agentes de IA confiables es utilizar un enfoque de Humano en el Bucle. Esto crea un flujo en el que los usuarios pueden proporcionar retroalimentación a los Agentes durante su ejecución. Los usuarios actúan esencialmente como un agente en un sistema multiagente, proporcionando aprobación o terminación del proceso en curso. ![Humano en el Bucle](../../../translated_images/human-in-the-loop.e9edbe8f6d42041b4213421410823250aa750fe8bdba5601d69ed46f3ff6489d.es.png) Aquí tienes un fragmento de código que utiliza AutoGen para mostrar cómo se implementa este concepto: ```python # Create the agents. model_client = OpenAIChatCompletionClient(model="gpt-4o-mini") assistant = AssistantAgent("assistant", model_client=model_client) user_proxy = UserProxyAgent("user_proxy", input_func=input) # Use input() to get user input from console. # Create the termination condition which will end the conversation when the user says "APPROVE". termination = TextMentionTermination("APPROVE") # Create the team. team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination) # Run the conversation and stream to the console. stream = team.run_stream(task="Write a 4-line poem about the ocean.") # Use asyncio.run(...) when running in a script. await Console(stream) ``` **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por garantizar la precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o inexactitudes. El documento original en su idioma nativo debe considerarse como la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de ningún malentendido o interpretación errónea que surja del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/06-building-trustworthy-agents/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/06-building-trustworthy-agents/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 12252 }
# Planificación y Diseño ## Introducción En esta lección cubriremos: * Definir un objetivo general claro y descomponer una tarea compleja en tareas manejables. * Aprovechar salidas estructuradas para obtener respuestas más confiables y legibles por máquinas. * Aplicar un enfoque basado en eventos para manejar tareas dinámicas e inputs inesperados. ## Objetivos de Aprendizaje Al completar esta lección, comprenderás cómo: * Identificar y establecer un objetivo general para un agente de IA, asegurándote de que sepa claramente qué debe lograr. * Descomponer una tarea compleja en subtareas manejables y organizarlas en una secuencia lógica. * Equipar a los agentes con las herramientas adecuadas (por ejemplo, herramientas de búsqueda o análisis de datos), decidir cuándo y cómo usarlas, y manejar situaciones inesperadas que puedan surgir. * Evaluar los resultados de las subtareas, medir el rendimiento e iterar en las acciones para mejorar el resultado final. ## Definir el Objetivo General y Descomponer una Tarea ![Definir Objetivos y Tareas](../../../translated_images/defining-goals-tasks.dcc1181bbdb194704ae0fb3363371562949e8b03fd2fadc256218aaadf84a9f4.es.png) La mayoría de las tareas del mundo real son demasiado complejas para abordarlas en un solo paso. Un agente de IA necesita un objetivo claro y conciso que guíe su planificación y acciones. Por ejemplo, considera el objetivo: "Generar un itinerario de viaje de 3 días." Aunque es sencillo de enunciar, aún necesita refinamiento. Cuanto más claro sea el objetivo, mejor podrán el agente (y cualquier colaborador humano) enfocarse en lograr el resultado correcto, como crear un itinerario completo con opciones de vuelo, recomendaciones de hoteles y sugerencias de actividades. ### Descomposición de Tareas Las tareas grandes o intrincadas se vuelven más manejables cuando se dividen en subtareas más pequeñas y orientadas a objetivos. Para el ejemplo del itinerario de viaje, podrías descomponer el objetivo en: * Reserva de vuelos * Reserva de hoteles * Alquiler de autos * Personalización Cada subtarea puede ser abordada por agentes o procesos especializados. Un agente podría especializarse en buscar las mejores ofertas de vuelos, otro en reservas de hoteles, y así sucesivamente. Un agente coordinador o "descendente" puede luego compilar estos resultados en un itinerario cohesivo para el usuario final. Este enfoque modular también permite mejoras incrementales. Por ejemplo, podrías agregar agentes especializados en Recomendaciones Gastronómicas o Sugerencias de Actividades Locales y refinar el itinerario con el tiempo. ### Salidas Estructuradas Los Modelos de Lenguaje Extenso (LLMs) pueden generar salidas estructuradas (por ejemplo, JSON) que son más fáciles de analizar y procesar para agentes o servicios posteriores. Esto es especialmente útil en un contexto multiagente, donde podemos ejecutar estas tareas después de recibir la salida del plan. Consulta este [blogpost](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/cookbook/structured-output-agent.html) para una visión general rápida. A continuación, se muestra un fragmento de código en Python que demuestra cómo un agente de planificación descompone un objetivo en subtareas y genera un plan estructurado: ### Agente de Planificación con Orquestación Multiagente En este ejemplo, un Agente de Enrutador Semántico recibe una solicitud del usuario (por ejemplo, "Necesito un plan de hotel para mi viaje."). El planificador luego: * Recibe el Plan del Hotel: El planificador toma el mensaje del usuario y, basado en un prompt del sistema (incluyendo detalles de los agentes disponibles), genera un plan de viaje estructurado. * Lista los Agentes y Sus Herramientas: El registro de agentes contiene una lista de agentes (por ejemplo, para vuelos, hoteles, alquiler de autos y actividades) junto con las funciones o herramientas que ofrecen. * Rutea el Plan a los Agentes Correspondientes: Dependiendo del número de subtareas, el planificador envía el mensaje directamente a un agente dedicado (para escenarios de tarea única) o coordina a través de un gestor de chat grupal para la colaboración multiagente. * Resume el Resultado: Finalmente, el planificador resume el plan generado para mayor claridad. A continuación, se muestra el código Python que ilustra estos pasos: ```python from pydantic import BaseModel from enum import Enum from typing import List, Optional, Union class AgentEnum(str, Enum): FlightBooking = "flight_booking" HotelBooking = "hotel_booking" CarRental = "car_rental" ActivitiesBooking = "activities_booking" DestinationInfo = "destination_info" DefaultAgent = "default_agent" GroupChatManager = "group_chat_manager" # Travel SubTask Model class TravelSubTask(BaseModel): task_details: str assigned_agent: AgentEnum # we want to assign the task to the agent class TravelPlan(BaseModel): main_task: str subtasks: List[TravelSubTask] is_greeting: bool import json import os from typing import Optional from autogen_core.models import UserMessage, SystemMessage, AssistantMessage from autogen_ext.models.openai import AzureOpenAIChatCompletionClient # Create the client with type-checked environment variables client = AzureOpenAIChatCompletionClient( azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"), model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"), api_version=os.getenv("AZURE_OPENAI_API_VERSION"), azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), ) from pprint import pprint # Define the user message messages = [ SystemMessage(content="""You are an planner agent. Your job is to decide which agents to run based on the user's request. Below are the available agents specialised in different tasks: - FlightBooking: For booking flights and providing flight information - HotelBooking: For booking hotels and providing hotel information - CarRental: For booking cars and providing car rental information - ActivitiesBooking: For booking activities and providing activity information - DestinationInfo: For providing information about destinations - DefaultAgent: For handling general requests""", source="system"), UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"), ] response = await client.create(messages=messages, extra_create_args={"response_format": TravelPlan}) # Ensure the response content is a valid JSON string before loading it response_content: Optional[str] = response.content if isinstance(response.content, str) else None if response_content is None: raise ValueError("Response content is not a valid JSON string") # Print the response content after loading it as JSON pprint(json.loads(response_content)) ``` A continuación, se muestra la salida del código anterior, que luego puedes usar para enviar al `assigned_agent` y resumir el plan de viaje para el usuario final: ```json { "is_greeting": "False", "main_task": "Plan a family trip from Singapore to Melbourne.", "subtasks": [ { "assigned_agent": "flight_booking", "task_details": "Book round-trip flights from Singapore to Melbourne." }, { "assigned_agent": "hotel_booking", "task_details": "Find family-friendly hotels in Melbourne." }, { "assigned_agent": "car_rental", "task_details": "Arrange a car rental suitable for a family of four in Melbourne." }, { "assigned_agent": "activities_booking", "task_details": "List family-friendly activities in Melbourne." }, { "assigned_agent": "destination_info", "task_details": "Provide information about Melbourne as a travel destination." } ] } ``` Un notebook de ejemplo con el código anterior está disponible [aquí](../../../07-planning-design/code_samples/07-autogen.ipynb). ### Planificación Iterativa Algunas tareas requieren un proceso iterativo o de ida y vuelta, donde el resultado de una subtarea influye en la siguiente. Por ejemplo, si el agente encuentra un formato de datos inesperado al reservar vuelos, podría necesitar adaptar su estrategia antes de continuar con la reserva de hoteles. Además, los comentarios del usuario (por ejemplo, que una persona prefiera un vuelo más temprano) pueden desencadenar una re-planificación parcial. Este enfoque dinámico e iterativo asegura que la solución final se alinee con las restricciones del mundo real y las preferencias cambiantes del usuario. Por ejemplo, código de muestra: ```python from autogen_core.models import UserMessage, SystemMessage, AssistantMessage #.. same as previous code and pass on the user history, current plan messages = [ SystemMessage(content="""You are a planner agent to optimize the Your job is to decide which agents to run based on the user's request. Below are the available agents specialised in different tasks: - FlightBooking: For booking flights and providing flight information - HotelBooking: For booking hotels and providing hotel information - CarRental: For booking cars and providing car rental information - ActivitiesBooking: For booking activities and providing activity information - DestinationInfo: For providing information about destinations - DefaultAgent: For handling general requests""", source="system"), UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melboune", source="user"), AssistantMessage(content=f"Previous travel plan - {TravelPlan}", source="assistant") ] # .. re-plan and send the tasks to respective agents ``` Para una planificación más completa, consulta el blog Magnetic One [Blogpost](https://www.microsoft.com/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks) para resolver tareas complejas. ## Resumen En este artículo hemos visto un ejemplo de cómo crear un planificador que puede seleccionar dinámicamente los agentes disponibles definidos. La salida del planificador descompone las tareas y asigna los agentes para que las ejecuten. Se asume que los agentes tienen acceso a las funciones/herramientas necesarias para realizar la tarea. Además de los agentes, puedes incluir otros patrones como reflexión, resumidores o chat en rondas para personalizar aún más. ## Recursos Adicionales * El uso de modelos de razonamiento o1 ha demostrado ser bastante avanzado para planificar tareas complejas. - TODO: ¿Compartir ejemplo? * Autogen Magnetic One - Un sistema multiagente generalista para resolver tareas complejas que ha logrado resultados impresionantes en múltiples benchmarks desafiantes de agentes. Referencia: [autogen-magentic-one](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-magentic-one). En esta implementación, el orquestador crea un plan específico para la tarea y delega estas tareas a los agentes disponibles. Además de planificar, el orquestador también emplea un mecanismo de seguimiento para monitorear el progreso de la tarea y re-planificar según sea necesario. **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por garantizar la precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse como la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables por malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/07-planning-design/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/07-planning-design/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 12149 }
# Patrones de diseño de múltiples agentes Tan pronto como comiences a trabajar en un proyecto que involucre múltiples agentes, necesitarás considerar el patrón de diseño de múltiples agentes. Sin embargo, puede que no sea inmediatamente evidente cuándo cambiar a un enfoque de múltiples agentes y cuáles son sus ventajas. ## Introducción En esta lección, buscamos responder las siguientes preguntas: - ¿En qué escenarios son aplicables los múltiples agentes? - ¿Cuáles son las ventajas de usar múltiples agentes en lugar de un solo agente realizando múltiples tareas? - ¿Cuáles son los componentes básicos para implementar el patrón de diseño de múltiples agentes? - ¿Cómo podemos tener visibilidad de cómo interactúan entre sí los múltiples agentes? ## Objetivos de aprendizaje Al finalizar esta lección, deberías ser capaz de: - Identificar escenarios donde los múltiples agentes son aplicables. - Reconocer las ventajas de usar múltiples agentes en lugar de un solo agente. - Comprender los componentes básicos para implementar el patrón de diseño de múltiples agentes. ### ¿Cuál es la idea principal? *Los múltiples agentes son un patrón de diseño que permite que varios agentes trabajen juntos para lograr un objetivo común*. Este patrón se utiliza ampliamente en diversos campos, incluidos la robótica, los sistemas autónomos y la computación distribuida. ## Escenarios donde los múltiples agentes son aplicables Entonces, ¿en qué escenarios es útil usar múltiples agentes? La respuesta es que hay muchos casos en los que emplear múltiples agentes resulta beneficioso, especialmente en las siguientes situaciones: - **Altas cargas de trabajo**: Las cargas de trabajo grandes pueden dividirse en tareas más pequeñas y asignarse a diferentes agentes, permitiendo procesamiento en paralelo y una finalización más rápida. Un ejemplo de esto es en el caso de una tarea de procesamiento de datos a gran escala. - **Tareas complejas**: Las tareas complejas, al igual que las grandes cargas de trabajo, pueden descomponerse en subtareas más pequeñas y asignarse a diferentes agentes, cada uno especializado en un aspecto específico de la tarea. Un buen ejemplo de esto es en el caso de vehículos autónomos, donde diferentes agentes gestionan la navegación, la detección de obstáculos y la comunicación con otros vehículos. - **Diversidad de especialización**: Diferentes agentes pueden tener especializaciones diversas, permitiéndoles manejar distintos aspectos de una tarea de manera más efectiva que un único agente. Por ejemplo, en el caso del sector salud, los agentes pueden gestionar diagnósticos, planes de tratamiento y monitoreo de pacientes. ## Ventajas de usar múltiples agentes frente a un solo agente Un sistema con un solo agente puede funcionar bien para tareas simples, pero para tareas más complejas, usar múltiples agentes puede ofrecer varias ventajas: - **Especialización**: Cada agente puede especializarse en una tarea específica. La falta de especialización en un solo agente puede significar que este termine realizando tareas para las que no está mejor preparado. Por ejemplo, podría enfrentarse a tareas complejas que lo confundan o que realice de manera subóptima. - **Escalabilidad**: Es más sencillo escalar sistemas añadiendo más agentes en lugar de sobrecargar a un único agente. - **Tolerancia a fallos**: Si un agente falla, los demás pueden seguir funcionando, garantizando la fiabilidad del sistema. Tomemos un ejemplo: reservar un viaje para un usuario. Un sistema con un solo agente tendría que manejar todos los aspectos del proceso de reserva de viaje, desde encontrar vuelos hasta reservar hoteles y autos de alquiler. Para lograr esto, el agente único necesitaría herramientas para gestionar todas estas tareas, lo que podría llevar a un sistema complejo y monolítico, difícil de mantener y escalar. Un sistema con múltiples agentes, en cambio, podría tener diferentes agentes especializados en encontrar vuelos, reservar hoteles y autos de alquiler. Esto haría que el sistema fuera más modular, fácil de mantener y escalable. Compáralo con una agencia de viajes administrada como un pequeño negocio familiar frente a una agencia de viajes operada como una franquicia. El negocio familiar tendría un solo agente manejando todos los aspectos del proceso de reserva de viaje, mientras que la franquicia tendría diferentes agentes gestionando distintos aspectos del proceso. ## Componentes básicos para implementar el patrón de diseño de múltiples agentes Antes de implementar el patrón de diseño de múltiples agentes, necesitas entender los componentes básicos que conforman este patrón. Hagamos esto más concreto volviendo al ejemplo de reservar un viaje para un usuario. En este caso, los componentes básicos incluirían: - **Comunicación entre agentes**: Los agentes encargados de encontrar vuelos, reservar hoteles y autos de alquiler necesitan comunicarse y compartir información sobre las preferencias y restricciones del usuario. Necesitarás decidir los protocolos y métodos para esta comunicación. Por ejemplo, el agente que encuentra vuelos debe comunicarse con el agente que reserva hoteles para asegurarse de que el hotel esté reservado para las mismas fechas que el vuelo. Esto significa que los agentes deben compartir información sobre las fechas de viaje del usuario, por lo que necesitas decidir *qué información comparten los agentes y cómo la comparten*. - **Mecanismos de coordinación**: Los agentes deben coordinar sus acciones para asegurarse de que se cumplan las preferencias y restricciones del usuario. Por ejemplo, una preferencia del usuario podría ser que quiere un hotel cerca del aeropuerto, mientras que una restricción podría ser que los autos de alquiler solo están disponibles en el aeropuerto. Esto significa que el agente que reserva hoteles necesita coordinarse con el agente que reserva autos de alquiler para cumplir con las preferencias y restricciones del usuario. Necesitarás decidir *cómo los agentes coordinan sus acciones*. - **Arquitectura de los agentes**: Los agentes necesitan una estructura interna para tomar decisiones y aprender de sus interacciones con el usuario. Por ejemplo, el agente que encuentra vuelos necesita una estructura interna para decidir qué vuelos recomendar al usuario. Esto significa que necesitas decidir *cómo los agentes toman decisiones y aprenden de sus interacciones con el usuario*. Un ejemplo de cómo un agente puede aprender y mejorar es que el agente que encuentra vuelos podría usar un modelo de aprendizaje automático para recomendar vuelos al usuario basándose en sus preferencias pasadas. - **Visibilidad de las interacciones entre agentes**: Es necesario tener visibilidad de cómo interactúan entre sí los múltiples agentes. Esto implica contar con herramientas y técnicas para rastrear las actividades e interacciones de los agentes. Podrías usar herramientas de registro y monitoreo, herramientas de visualización y métricas de rendimiento. - **Patrones de múltiples agentes**: Existen diferentes patrones para implementar sistemas de múltiples agentes, como arquitecturas centralizadas, descentralizadas e híbridas. Necesitarás decidir cuál se adapta mejor a tu caso de uso. - **Intervención humana**: En la mayoría de los casos, habrá un humano involucrado en el proceso, y necesitarás instruir a los agentes sobre cuándo pedir la intervención humana. Por ejemplo, un usuario podría pedir un hotel o un vuelo específico que los agentes no hayan recomendado, o podría solicitar confirmación antes de realizar una reserva. ## Visibilidad de las interacciones entre agentes Es importante tener visibilidad de cómo interactúan entre sí los múltiples agentes. Esta visibilidad es esencial para depurar, optimizar y garantizar la efectividad general del sistema. Para lograrlo, necesitas herramientas y técnicas para rastrear las actividades e interacciones de los agentes. Esto podría incluir herramientas de registro y monitoreo, herramientas de visualización y métricas de rendimiento. Por ejemplo, en el caso de reservar un viaje para un usuario, podrías tener un panel de control que muestre el estado de cada agente, las preferencias y restricciones del usuario, y las interacciones entre los agentes. Este panel podría mostrar las fechas de viaje del usuario, los vuelos recomendados por el agente de vuelos, los hoteles recomendados por el agente de hoteles y los autos de alquiler recomendados por el agente de autos de alquiler. Esto te daría una visión clara de cómo interactúan entre sí los agentes y si se están cumpliendo las preferencias y restricciones del usuario. Veamos cada uno de estos aspectos con más detalle: - **Herramientas de registro y monitoreo**: Es importante registrar cada acción tomada por un agente. Una entrada en el registro podría incluir información sobre el agente que realizó la acción, la acción realizada, el momento en que se realizó y el resultado de la acción. Esta información puede usarse para depurar, optimizar y más. - **Herramientas de visualización**: Las herramientas de visualización pueden ayudarte a entender las interacciones entre los agentes de manera más intuitiva. Por ejemplo, podrías tener un gráfico que muestre el flujo de información entre los agentes. Esto podría ayudarte a identificar cuellos de botella, ineficiencias y otros problemas en el sistema. - **Métricas de rendimiento**: Las métricas de rendimiento pueden ayudarte a rastrear la efectividad del sistema de múltiples agentes. Por ejemplo, podrías rastrear el tiempo necesario para completar una tarea, el número de tareas completadas por unidad de tiempo y la precisión de las recomendaciones realizadas por los agentes. Esta información puede ayudarte a identificar áreas de mejora y optimizar el sistema. ## Patrones de múltiples agentes Veamos algunos patrones concretos que podemos usar para crear aplicaciones de múltiples agentes. Aquí hay algunos patrones interesantes que vale la pena considerar: ### Chat grupal Este patrón es útil cuando quieres crear una aplicación de chat grupal donde múltiples agentes puedan comunicarse entre sí. Los casos de uso típicos de este patrón incluyen colaboración en equipo, soporte al cliente y redes sociales. En este patrón, cada agente representa a un usuario en el chat grupal, y los mensajes se intercambian entre los agentes utilizando un protocolo de mensajería. Los agentes pueden enviar mensajes al chat grupal, recibir mensajes del chat grupal y responder a mensajes de otros agentes. Este patrón puede implementarse utilizando una arquitectura centralizada, donde todos los mensajes se enrutan a través de un servidor central, o una arquitectura descentralizada, donde los mensajes se intercambian directamente. ![Chat grupal](../../../translated_images/multi-agent-group-chat.82d537c5c8dc833abbd252033e60874bc9d00df7193888b3377f8426449a0b20.es.png) ### Transferencia de tareas (Hand-off) Este patrón es útil cuando deseas crear una aplicación donde múltiples agentes puedan transferir tareas entre sí. Los casos de uso típicos de este patrón incluyen soporte al cliente, gestión de tareas y automatización de flujos de trabajo. En este patrón, cada agente representa una tarea o un paso en un flujo de trabajo, y los agentes pueden transferir tareas a otros agentes basándose en reglas predefinidas. ![Transferencia de tareas](../../../translated_images/multi-agent-hand-off.ed4f0a5a58614a8a3e962fc476187e630a3ba309d066e460f017b503d0b84cfc.es.png) ### Filtrado colaborativo Este patrón es útil cuando deseas crear una aplicación donde múltiples agentes puedan colaborar para hacer recomendaciones a los usuarios. ¿Por qué querrías que múltiples agentes colaboren? Porque cada agente puede tener diferentes especializaciones y contribuir al proceso de recomendación de maneras distintas. Tomemos un ejemplo donde un usuario quiere una recomendación sobre la mejor acción para comprar en el mercado de valores: - **Experto en la industria**: Un agente podría ser experto en una industria específica. - **Análisis técnico**: Otro agente podría ser experto en análisis técnico. - **Análisis fundamental**: Y otro agente podría ser experto en análisis fundamental. Colaborando, estos agentes pueden proporcionar una recomendación más completa al usuario. ![Recomendación](../../../translated_images/multi-agent-filtering.719217d169391ddb118bbb726b19d4d89ee139f960f8749ccb2400efb4d0ce79.es.png) ## Escenario: Proceso de reembolso Consideremos un escenario donde un cliente está intentando obtener un reembolso por un producto. Puede haber varios agentes involucrados en este proceso, pero dividámoslos entre agentes específicos para este proceso y agentes generales que pueden usarse en otros procesos. **Agentes específicos para el proceso de reembolso**: A continuación, algunos agentes que podrían estar involucrados en el proceso de reembolso: - **Agente del cliente**: Representa al cliente y es responsable de iniciar el proceso de reembolso. - **Agente del vendedor**: Representa al vendedor y es responsable de procesar el reembolso. - **Agente de pagos**: Representa el proceso de pago y es responsable de reembolsar el pago del cliente. - **Agente de resolución**: Representa el proceso de resolución y es responsable de resolver cualquier problema que surja durante el proceso de reembolso. - **Agente de cumplimiento**: Representa el proceso de cumplimiento y es responsable de garantizar que el proceso de reembolso cumpla con las normativas y políticas. **Agentes generales**: Estos agentes pueden usarse en otras partes de tu negocio: - **Agente de envío**: Representa el proceso de envío y es responsable de devolver el producto al vendedor. Este agente puede usarse tanto para el proceso de reembolso como para el envío general de un producto tras una compra, por ejemplo. - **Agente de retroalimentación**: Representa el proceso de retroalimentación y es responsable de recopilar comentarios del cliente. La retroalimentación podría obtenerse en cualquier momento, no solo durante el proceso de reembolso. - **Agente de escalamiento**: Representa el proceso de escalamiento y es responsable de escalar problemas a un nivel superior de soporte. Este tipo de agente puede usarse en cualquier proceso donde necesites escalar un problema. - **Agente de notificaciones**: Representa el proceso de notificaciones y es responsable de enviar notificaciones al cliente en varias etapas del proceso de reembolso. - **Agente de análisis**: Representa el proceso de análisis y es responsable de analizar datos relacionados con el proceso de reembolso. - **Agente de auditoría**: Representa el proceso de auditoría y es responsable de auditar el proceso de reembolso para garantizar que se lleve a cabo correctamente. - **Agente de reportes**: Representa el proceso de reportes y es responsable de generar informes sobre el proceso de reembolso. - **Agente de conocimiento**: Representa el proceso de gestión del conocimiento y es responsable de mantener una base de datos de información relacionada con el proceso de reembolso. Este agente podría ser útil tanto para reembolsos como para otras partes de tu negocio. - **Agente de seguridad**: Representa el proceso de seguridad y es responsable de garantizar la seguridad del proceso de reembolso. - **Agente de calidad**: Representa el proceso de calidad y es responsable de garantizar la calidad del proceso de reembolso. Hay bastantes agentes enumerados anteriormente, tanto específicos para el proceso de reembolso como generales que pueden usarse en otras partes de tu negocio. Esperamos que esto te dé una idea de cómo decidir qué agentes usar en tu sistema de múltiples agentes. ## Tarea ¿Cuál sería una buena tarea para esta lección? Diseña un sistema de múltiples agentes para un proceso de soporte al cliente. Identifica los agentes involucrados en el proceso, sus roles y responsabilidades, y cómo interactúan entre sí. Considera tanto agentes específicos para el proceso de soporte al cliente como agentes generales que puedan usarse en otras partes de tu negocio. > Reflexiona antes de leer la solución a continuación, puede que necesites más agentes de los que crees. > TIP: Piensa en las diferentes etapas del proceso de soporte al cliente y también considera los agentes necesarios para cualquier sistema. ## Solución [Solución](./solution/solution.md) ## Verificaciones de conocimiento Pregunta: ¿Cuándo deberías considerar usar múltiples agentes? - [] A1: Cuando tienes una carga de trabajo pequeña y una tarea sencilla. - [] A2: Cuando tienes una carga de trabajo grande. - [] A3: Cuando tienes una tarea sencilla. [Solución del cuestionario](./solution/solution-quiz.md) ## Resumen En esta lección, hemos explorado el patrón de diseño de múltiples agentes, incluidos los escenarios donde son aplicables, las ventajas de usar múltiples agentes en lugar de un solo agente, los componentes básicos para implementar el patrón de diseño de múltiples agentes y cómo tener visibilidad de cómo interactúan entre sí los múltiples agentes. ## Recursos adicionales - [Autogen design patterns](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/design-patterns/intro.html) - [Agentic design patterns](https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/) **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por garantizar la precisión, tenga en cuenta que las traducciones automáticas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse como la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/08-multi-agent/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/08-multi-agent/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 18187 }
# Metacognición en Agentes de IA ## Introducción ¡Bienvenido a la lección sobre metacognición en agentes de IA! Este capítulo está diseñado para principiantes curiosos sobre cómo los agentes de IA pueden reflexionar sobre sus propios procesos de pensamiento. Al final de esta lección, comprenderás conceptos clave y estarás equipado con ejemplos prácticos para aplicar la metacognición en el diseño de agentes de IA. ## Objetivos de Aprendizaje Después de completar esta lección, serás capaz de: 1. Comprender las implicaciones de los bucles de razonamiento en las definiciones de agentes. 2. Utilizar técnicas de planificación y evaluación para ayudar a agentes a autocorregirse. 3. Crear tus propios agentes capaces de manipular código para cumplir tareas. ## Introducción a la Metacognición La metacognición se refiere a los procesos cognitivos de orden superior que implican pensar sobre el propio pensamiento. Para los agentes de IA, esto significa ser capaces de evaluar y ajustar sus acciones basándose en la autoconciencia y experiencias pasadas. ### ¿Qué es la Metacognición? La metacognición, o "pensar sobre el pensamiento", es un proceso cognitivo de orden superior que implica la autoconciencia y la autorregulación de los propios procesos cognitivos. En el ámbito de la IA, la metacognición permite a los agentes evaluar y adaptar sus estrategias y acciones, lo que lleva a una mejora en la resolución de problemas y la toma de decisiones. Al comprender la metacognición, puedes diseñar agentes de IA que no solo sean más inteligentes, sino también más adaptables y eficientes. ### Importancia de la Metacognición en Agentes de IA La metacognición desempeña un papel crucial en el diseño de agentes de IA por varias razones: ![Importancia de la Metacognición](../../../translated_images/importance-of-metacognition.e351a5983bb745d60a1a60185391a39a6751d033c8c1948ceb6ad04eff7dbeac.es.png) - **Autorreflexión**: Los agentes pueden evaluar su propio rendimiento e identificar áreas de mejora. - **Adaptabilidad**: Los agentes pueden modificar sus estrategias basándose en experiencias pasadas y entornos cambiantes. - **Corrección de errores**: Los agentes pueden detectar y corregir errores de forma autónoma, lo que lleva a resultados más precisos. - **Gestión de recursos**: Los agentes pueden optimizar el uso de recursos, como el tiempo y la potencia computacional, planificando y evaluando sus acciones. ## Componentes de un Agente de IA Antes de profundizar en los procesos metacognitivos, es esencial entender los componentes básicos de un agente de IA. Un agente de IA típicamente consiste en: - **Personalidad**: La personalidad y características del agente, que definen cómo interactúa con los usuarios. - **Herramientas**: Las capacidades y funciones que el agente puede realizar. - **Habilidades**: El conocimiento y la experiencia que posee el agente. Estos componentes trabajan juntos para crear una "unidad de experiencia" que puede realizar tareas específicas. **Ejemplo**: Considera un agente de viajes que no solo planifica tus vacaciones, sino que también ajusta su camino basándose en datos en tiempo real y experiencias previas de clientes. ### Ejemplo: Metacognición en un Servicio de Agente de Viajes Imagina que estás diseñando un servicio de agente de viajes impulsado por IA. Este agente, "Agente de Viajes", ayuda a los usuarios a planificar sus vacaciones. Para incorporar la metacognición, el Agente de Viajes necesita evaluar y ajustar sus acciones basándose en la autoconciencia y experiencias pasadas. Aquí está cómo la metacognición podría desempeñar un papel: #### Tarea Actual La tarea actual es ayudar a un usuario a planificar un viaje a París. #### Pasos para Completar la Tarea 1. **Recopilar Preferencias del Usuario**: Preguntar al usuario sobre sus fechas de viaje, presupuesto, intereses (por ejemplo, museos, gastronomía, compras) y cualquier requisito específico. 2. **Recuperar Información**: Buscar opciones de vuelos, alojamientos, atracciones y restaurantes que coincidan con las preferencias del usuario. 3. **Generar Recomendaciones**: Proporcionar un itinerario personalizado con detalles de vuelos, reservas de hotel y actividades sugeridas. 4. **Ajustar Basándose en la Retroalimentación**: Pedir al usuario comentarios sobre las recomendaciones y realizar los ajustes necesarios. #### Recursos Requeridos - Acceso a bases de datos de reservas de vuelos y hoteles. - Información sobre atracciones y restaurantes en París. - Datos de retroalimentación de usuarios de interacciones previas. #### Experiencia y Autorreflexión El Agente de Viajes utiliza la metacognición para evaluar su rendimiento y aprender de experiencias pasadas. Por ejemplo: 1. **Análisis de Retroalimentación del Usuario**: El Agente de Viajes revisa los comentarios de los usuarios para determinar qué recomendaciones fueron bien recibidas y cuáles no. Ajusta sus sugerencias futuras en consecuencia. 2. **Adaptabilidad**: Si un usuario mencionó previamente que no le gustan los lugares concurridos, el Agente de Viajes evitará recomendar puntos turísticos populares durante las horas pico en el futuro. 3. **Corrección de Errores**: Si el Agente de Viajes cometió un error en una reserva pasada, como sugerir un hotel que estaba completamente reservado, aprende a verificar la disponibilidad más rigurosamente antes de hacer recomendaciones. #### Ejemplo Práctico para Desarrolladores Aquí hay un ejemplo simplificado de cómo podría verse el código del Agente de Viajes al incorporar metacognición: ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): # Search for flights, hotels, and attractions based on preferences flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) # Analyze feedback and adjust future recommendations self.user_preferences = adjust_preferences(self.user_preferences, feedback) # Example usage travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} travel_agent.adjust_based_on_feedback(feedback) ``` #### Por Qué Importa la Metacognición - **Autorreflexión**: Los agentes pueden analizar su rendimiento e identificar áreas de mejora. - **Adaptabilidad**: Los agentes pueden modificar estrategias basándose en comentarios y condiciones cambiantes. - **Corrección de Errores**: Los agentes pueden detectar y corregir errores de forma autónoma. - **Gestión de Recursos**: Los agentes pueden optimizar el uso de recursos, como el tiempo y la potencia computacional. Al incorporar la metacognición, el Agente de Viajes puede proporcionar recomendaciones de viaje más personalizadas y precisas, mejorando la experiencia general del usuario. --- ## 2. Planificación en Agentes La planificación es un componente crítico del comportamiento de los agentes de IA. Implica delinear los pasos necesarios para lograr un objetivo, considerando el estado actual, los recursos y posibles obstáculos. ### Elementos de la Planificación - **Tarea Actual**: Definir claramente la tarea. - **Pasos para Completar la Tarea**: Dividir la tarea en pasos manejables. - **Recursos Requeridos**: Identificar los recursos necesarios. - **Experiencia**: Utilizar experiencias pasadas para informar la planificación. **Ejemplo**: Aquí están los pasos que el Agente de Viajes necesita tomar para ayudar a un usuario a planificar su viaje de manera efectiva: ### Pasos para el Agente de Viajes 1. **Recopilar Preferencias del Usuario** - Preguntar al usuario detalles sobre sus fechas de viaje, presupuesto, intereses y cualquier requisito específico. - Ejemplos: "¿Cuándo planeas viajar?" "¿Cuál es tu rango de presupuesto?" "¿Qué actividades disfrutas en vacaciones?" 2. **Recuperar Información** - Buscar opciones de viaje relevantes basadas en las preferencias del usuario. - **Vuelos**: Buscar vuelos disponibles dentro del presupuesto y las fechas preferidas del usuario. - **Alojamientos**: Encontrar hoteles o propiedades en alquiler que coincidan con las preferencias del usuario en cuanto a ubicación, precio y comodidades. - **Atracciones y Restaurantes**: Identificar atracciones populares, actividades y opciones gastronómicas que se alineen con los intereses del usuario. 3. **Generar Recomendaciones** - Compilar la información recuperada en un itinerario personalizado. - Proporcionar detalles como opciones de vuelos, reservas de hotel y actividades sugeridas, asegurándose de personalizar las recomendaciones según las preferencias del usuario. 4. **Presentar el Itinerario al Usuario** - Compartir el itinerario propuesto con el usuario para su revisión. - Ejemplo: "Aquí tienes un itinerario sugerido para tu viaje a París. Incluye detalles de vuelos, reservas de hotel y una lista de actividades y restaurantes recomendados. ¡Hazme saber qué opinas!" 5. **Recopilar Retroalimentación** - Pedir al usuario comentarios sobre el itinerario propuesto. - Ejemplos: "¿Te gustan las opciones de vuelos?" "¿Es el hotel adecuado para tus necesidades?" "¿Hay alguna actividad que te gustaría añadir o eliminar?" 6. **Ajustar Basándose en la Retroalimentación** - Modificar el itinerario según los comentarios del usuario. - Realizar los cambios necesarios en las recomendaciones de vuelos, alojamiento y actividades para que coincidan mejor con las preferencias del usuario. 7. **Confirmación Final** - Presentar el itinerario actualizado al usuario para su confirmación final. - Ejemplo: "He realizado los ajustes basándome en tus comentarios. Aquí tienes el itinerario actualizado. ¿Todo se ve bien para ti?" 8. **Reservar y Confirmar Reservas** - Una vez que el usuario apruebe el itinerario, proceder con la reserva de vuelos, alojamientos y cualquier actividad pre-planificada. - Enviar detalles de confirmación al usuario. 9. **Proveer Soporte Continuo** - Permanecer disponible para ayudar al usuario con cualquier cambio o solicitud adicional antes y durante su viaje. - Ejemplo: "Si necesitas más ayuda durante tu viaje, no dudes en contactarme en cualquier momento." ### Interacción de Ejemplo ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) self.user_preferences = adjust_preferences(self.user_preferences, feedback) # Example usage within a booing request travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} travel_agent.adjust_based_on_feedback(feedback) ``` ## 3. Sistema Correctivo RAG Primero, comencemos entendiendo la diferencia entre la Herramienta RAG y la Carga de Contexto Preventiva: ![RAG vs Context Loading](../../../translated_images/rag-vs-context.9bb2b76d17aeba1489ad2a43ddbc9cd20e7ada4e4871cc99c63a498aa0ff70f7.es.png) ### Generación Aumentada por Recuperación (RAG) RAG combina un sistema de recuperación con un modelo generativo. Cuando se realiza una consulta, el sistema de recuperación obtiene documentos o datos relevantes de una fuente externa, y esta información recuperada se utiliza para aumentar la entrada al modelo generativo. Esto ayuda al modelo a generar respuestas más precisas y contextualmente relevantes. En un sistema RAG, el agente recupera información relevante de una base de conocimiento y la utiliza para generar respuestas o acciones apropiadas. ### Enfoque Correctivo RAG El enfoque Correctivo RAG se centra en usar técnicas RAG para corregir errores y mejorar la precisión de los agentes de IA. Esto implica: 1. **Técnica de Prompts**: Usar prompts específicos para guiar al agente en la recuperación de información relevante. 2. **Herramienta**: Implementar algoritmos y mecanismos que permitan al agente evaluar la relevancia de la información recuperada y generar respuestas precisas. 3. **Evaluación**: Evaluar continuamente el rendimiento del agente y realizar ajustes para mejorar su precisión y eficiencia. #### Ejemplo: Correctivo RAG en un Agente de Búsqueda Considera un agente de búsqueda que recupera información de la web para responder a consultas de usuarios. El enfoque Correctivo RAG podría implicar: 1. **Técnica de Prompts**: Formular consultas de búsqueda basándose en la entrada del usuario. 2. **Herramienta**: Usar procesamiento de lenguaje natural y algoritmos de aprendizaje automático para clasificar y filtrar los resultados de búsqueda. 3. **Evaluación**: Analizar los comentarios de los usuarios para identificar y corregir inexactitudes en la información recuperada. ### Correctivo RAG en el Agente de Viajes Correctivo RAG (Generación Aumentada por Recuperación) mejora la capacidad de una IA para recuperar y generar información mientras corrige cualquier inexactitud. Veamos cómo el Agente de Viajes puede usar el enfoque Correctivo RAG para proporcionar recomendaciones de viaje más precisas y relevantes. Esto implica: - **Técnica de Prompts**: Usar prompts específicos para guiar al agente en la recuperación de información relevante. - **Herramienta**: Implementar algoritmos y mecanismos que permitan al agente evaluar la relevancia de la información recuperada y generar respuestas precisas. - **Evaluación**: Evaluar continuamente el rendimiento del agente y realizar ajustes para mejorar su precisión y eficiencia. #### Pasos para Implementar Correctivo RAG en el Agente de Viajes 1. **Interacción Inicial con el Usuario** - El Agente de Viajes recopila las preferencias iniciales del usuario, como destino, fechas de viaje, presupuesto e intereses. - Ejemplo: ```python preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } ``` 2. **Recuperación de Información** - El Agente de Viajes recupera información sobre vuelos, alojamientos, atracciones y restaurantes basándose en las preferencias del usuario. - Ejemplo: ```python flights = search_flights(preferences) hotels = search_hotels(preferences) attractions = search_attractions(preferences) ``` 3. **Generación de Recomendaciones Iniciales** - El Agente de Viajes utiliza la información recuperada para generar un itinerario personalizado. - Ejemplo: ```python itinerary = create_itinerary(flights, hotels, attractions) print("Suggested Itinerary:", itinerary) ``` 4. **Recopilación de Retroalimentación del Usuario** - El Agente de Viajes solicita comentarios del usuario sobre las recomendaciones iniciales. - Ejemplo: ```python feedback = { "liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"] } ``` 5. **Proceso Correctivo RAG** - **Técnica de Prompts**: ``` ```markdown El Agente de Viajes formula nuevas consultas de búsqueda basadas en los comentarios de los usuarios. - Ejemplo: ```python if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] ``` - **Herramienta**: El Agente de Viajes utiliza algoritmos para clasificar y filtrar nuevos resultados de búsqueda, enfatizando la relevancia basada en los comentarios de los usuarios. - Ejemplo: ```python new_attractions = search_attractions(preferences) new_itinerary = create_itinerary(flights, hotels, new_attractions) print("Updated Itinerary:", new_itinerary) ``` - **Evaluación**: El Agente de Viajes evalúa continuamente la relevancia y precisión de sus recomendaciones analizando los comentarios de los usuarios y realizando los ajustes necesarios. - Ejemplo: ```python def adjust_preferences(preferences, feedback): if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] return preferences preferences = adjust_preferences(preferences, feedback) ``` #### Ejemplo Práctico Aquí hay un ejemplo simplificado de código Python que incorpora el enfoque Corrective RAG en el Agente de Viajes: ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) self.user_preferences = adjust_preferences(self.user_preferences, feedback) new_itinerary = self.generate_recommendations() return new_itinerary # Example usage travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} new_itinerary = travel_agent.adjust_based_on_feedback(feedback) print("Updated Itinerary:", new_itinerary) ``` ### Carga de Contexto Previa La Carga de Contexto Previa implica cargar información relevante o de fondo en el modelo antes de procesar una consulta. Esto significa que el modelo tiene acceso a esta información desde el inicio, lo que puede ayudarle a generar respuestas más informadas sin necesidad de recuperar datos adicionales durante el proceso. Aquí hay un ejemplo simplificado de cómo podría verse una carga de contexto previa para una aplicación de agente de viajes en Python: ```python class TravelAgent: def __init__(self): # Pre-load popular destinations and their information self.context = { "Paris": {"country": "France", "currency": "Euro", "language": "French", "attractions": ["Eiffel Tower", "Louvre Museum"]}, "Tokyo": {"country": "Japan", "currency": "Yen", "language": "Japanese", "attractions": ["Tokyo Tower", "Shibuya Crossing"]}, "New York": {"country": "USA", "currency": "Dollar", "language": "English", "attractions": ["Statue of Liberty", "Times Square"]}, "Sydney": {"country": "Australia", "currency": "Dollar", "language": "English", "attractions": ["Sydney Opera House", "Bondi Beach"]} } def get_destination_info(self, destination): # Fetch destination information from pre-loaded context info = self.context.get(destination) if info: return f"{destination}:\nCountry: {info['country']}\nCurrency: {info['currency']}\nLanguage: {info['language']}\nAttractions: {', '.join(info['attractions'])}" else: return f"Sorry, we don't have information on {destination}." # Example usage travel_agent = TravelAgent() print(travel_agent.get_destination_info("Paris")) print(travel_agent.get_destination_info("Tokyo")) ``` #### Explicación 1. **Inicialización (`__init__` method)**: The `TravelAgent` class pre-loads a dictionary containing information about popular destinations such as Paris, Tokyo, New York, and Sydney. This dictionary includes details like the country, currency, language, and major attractions for each destination. 2. **Retrieving Information (`get_destination_info` method)**: When a user queries about a specific destination, the `get_destination_info`)**: El método obtiene la información relevante del diccionario de contexto precargado. Al precargar el contexto, la aplicación del agente de viajes puede responder rápidamente a las consultas de los usuarios sin tener que recuperar esta información de una fuente externa en tiempo real. Esto hace que la aplicación sea más eficiente y receptiva. ### Iniciar el Plan con un Objetivo Antes de Iterar Iniciar un plan con un objetivo implica comenzar con un resultado claro u objetivo en mente. Al definir este objetivo desde el principio, el modelo puede usarlo como principio guía durante todo el proceso iterativo. Esto ayuda a garantizar que cada iteración se acerque al resultado deseado, haciendo que el proceso sea más eficiente y enfocado. Aquí hay un ejemplo de cómo podrías iniciar un plan de viaje con un objetivo antes de iterar para un agente de viajes en Python: ### Escenario Un agente de viajes quiere planificar unas vacaciones personalizadas para un cliente. El objetivo es crear un itinerario de viaje que maximice la satisfacción del cliente en función de sus preferencias y presupuesto. ### Pasos 1. Definir las preferencias y el presupuesto del cliente. 2. Iniciar el plan inicial basado en estas preferencias. 3. Iterar para refinar el plan, optimizando la satisfacción del cliente. #### Código en Python ```python class TravelAgent: def __init__(self, destinations): self.destinations = destinations def bootstrap_plan(self, preferences, budget): plan = [] total_cost = 0 for destination in self.destinations: if total_cost + destination['cost'] <= budget and self.match_preferences(destination, preferences): plan.append(destination) total_cost += destination['cost'] return plan def match_preferences(self, destination, preferences): for key, value in preferences.items(): if destination.get(key) != value: return False return True def iterate_plan(self, plan, preferences, budget): for i in range(len(plan)): for destination in self.destinations: if destination not in plan and self.match_preferences(destination, preferences) and self.calculate_cost(plan, destination) <= budget: plan[i] = destination break return plan def calculate_cost(self, plan, new_destination): return sum(destination['cost'] for destination in plan) + new_destination['cost'] # Example usage destinations = [ {"name": "Paris", "cost": 1000, "activity": "sightseeing"}, {"name": "Tokyo", "cost": 1200, "activity": "shopping"}, {"name": "New York", "cost": 900, "activity": "sightseeing"}, {"name": "Sydney", "cost": 1100, "activity": "beach"}, ] preferences = {"activity": "sightseeing"} budget = 2000 travel_agent = TravelAgent(destinations) initial_plan = travel_agent.bootstrap_plan(preferences, budget) print("Initial Plan:", initial_plan) refined_plan = travel_agent.iterate_plan(initial_plan, preferences, budget) print("Refined Plan:", refined_plan) ``` #### Explicación del Código 1. **Inicialización (`__init__` method)**: The `TravelAgent` class is initialized with a list of potential destinations, each having attributes like name, cost, and activity type. 2. **Bootstrapping the Plan (`bootstrap_plan` method)**: This method creates an initial travel plan based on the client's preferences and budget. It iterates through the list of destinations and adds them to the plan if they match the client's preferences and fit within the budget. 3. **Matching Preferences (`match_preferences` method)**: This method checks if a destination matches the client's preferences. 4. **Iterating the Plan (`iterate_plan` method)**: This method refines the initial plan by trying to replace each destination in the plan with a better match, considering the client's preferences and budget constraints. 5. **Calculating Cost (`calculate_cost`)**: Este método calcula el costo total del plan actual, incluyendo un destino nuevo potencial. #### Ejemplo de Uso - **Plan Inicial**: El agente de viajes crea un plan inicial basado en las preferencias del cliente para turismo y un presupuesto de $2000. - **Plan Refinado**: El agente de viajes itera el plan, optimizando las preferencias y el presupuesto del cliente. Al iniciar el plan con un objetivo claro (por ejemplo, maximizar la satisfacción del cliente) e iterar para refinarlo, el agente de viajes puede crear un itinerario de viaje personalizado y optimizado para el cliente. Este enfoque garantiza que el plan de viaje se alinee con las preferencias y el presupuesto del cliente desde el principio y mejore con cada iteración. ### Aprovechar LLM para Reordenar y Puntuar Los Modelos de Lenguaje Extensos (LLMs) pueden utilizarse para reordenar y puntuar evaluando la relevancia y calidad de los documentos recuperados o las respuestas generadas. Así es como funciona: **Recuperación:** El paso inicial de recuperación obtiene un conjunto de documentos o respuestas candidatos basados en la consulta. **Reordenamiento:** El LLM evalúa estos candidatos y los reordena en función de su relevancia y calidad. Este paso asegura que la información más relevante y de alta calidad se presente primero. **Puntuación:** El LLM asigna puntuaciones a cada candidato, reflejando su relevancia y calidad. Esto ayuda a seleccionar la mejor respuesta o documento para el usuario. Al aprovechar los LLM para reordenar y puntuar, el sistema puede proporcionar información más precisa y contextualmente relevante, mejorando la experiencia general del usuario. Aquí hay un ejemplo de cómo un agente de viajes podría usar un Modelo de Lenguaje Extenso (LLM) para reordenar y puntuar destinos de viaje basados en las preferencias del usuario en Python: #### Escenario - Viajes basados en Preferencias Un agente de viajes quiere recomendar los mejores destinos de viaje a un cliente basado en sus preferencias. El LLM ayudará a reordenar y puntuar los destinos para garantizar que se presenten las opciones más relevantes. #### Pasos: 1. Recopilar las preferencias del usuario. 2. Recuperar una lista de posibles destinos de viaje. 3. Usar el LLM para reordenar y puntuar los destinos basados en las preferencias del usuario. Aquí está cómo puedes actualizar el ejemplo anterior para usar Azure OpenAI Services: #### Requisitos 1. Necesitas tener una suscripción a Azure. 2. Crear un recurso de Azure OpenAI y obtener tu clave API. #### Código de Ejemplo en Python ```python import requests import json class TravelAgent: def __init__(self, destinations): self.destinations = destinations def get_recommendations(self, preferences, api_key, endpoint): # Generate a prompt for the Azure OpenAI prompt = self.generate_prompt(preferences) # Define headers and payload for the request headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {api_key}' } payload = { "prompt": prompt, "max_tokens": 150, "temperature": 0.7 } # Call the Azure OpenAI API to get the re-ranked and scored destinations response = requests.post(endpoint, headers=headers, json=payload) response_data = response.json() # Extract and return the recommendations recommendations = response_data['choices'][0]['text'].strip().split('\n') return recommendations def generate_prompt(self, preferences): prompt = "Here are the travel destinations ranked and scored based on the following user preferences:\n" for key, value in preferences.items(): prompt += f"{key}: {value}\n" prompt += "\nDestinations:\n" for destination in self.destinations: prompt += f"- {destination['name']}: {destination['description']}\n" return prompt # Example usage destinations = [ {"name": "Paris", "description": "City of lights, known for its art, fashion, and culture."}, {"name": "Tokyo", "description": "Vibrant city, famous for its modernity and traditional temples."}, {"name": "New York", "description": "The city that never sleeps, with iconic landmarks and diverse culture."}, {"name": "Sydney", "description": "Beautiful harbour city, known for its opera house and stunning beaches."}, ] preferences = {"activity": "sightseeing", "culture": "diverse"} api_key = 'your_azure_openai_api_key' endpoint = 'https://your-endpoint.com/openai/deployments/your-deployment-name/completions?api-version=2022-12-01' travel_agent = TravelAgent(destinations) recommendations = travel_agent.get_recommendations(preferences, api_key, endpoint) print("Recommended Destinations:") for rec in recommendations: print(rec) ``` #### Explicación del Código - Preference Booker 1. **Inicialización**: El `TravelAgent` class is initialized with a list of potential travel destinations, each having attributes like name and description. 2. **Getting Recommendations (`get_recommendations` method)**: This method generates a prompt for the Azure OpenAI service based on the user's preferences and makes an HTTP POST request to the Azure OpenAI API to get re-ranked and scored destinations. 3. **Generating Prompt (`generate_prompt` method)**: This method constructs a prompt for the Azure OpenAI, including the user's preferences and the list of destinations. The prompt guides the model to re-rank and score the destinations based on the provided preferences. 4. **API Call**: The `requests` library is used to make an HTTP POST request to the Azure OpenAI API endpoint. The response contains the re-ranked and scored destinations. 5. **Example Usage**: The travel agent collects user preferences (e.g., interest in sightseeing and diverse culture) and uses the Azure OpenAI service to get re-ranked and scored recommendations for travel destinations. Make sure to replace `your_azure_openai_api_key` with your actual Azure OpenAI API key and `https://your-endpoint.com/...` con la URL real del endpoint de tu implementación de Azure OpenAI. Al aprovechar el LLM para reordenar y puntuar, el agente de viajes puede proporcionar recomendaciones de viaje más personalizadas y relevantes a los clientes, mejorando su experiencia general. ### RAG: Técnica de Prompts vs Herramienta La Generación Aumentada por Recuperación (RAG) puede ser tanto una técnica de prompts como una herramienta en el desarrollo de agentes de IA. Comprender la distinción entre ambas puede ayudarte a aprovechar RAG de manera más efectiva en tus proyectos. #### RAG como Técnica de Prompts **¿Qué es?** - Como técnica de prompts, RAG implica formular consultas o prompts específicos para guiar la recuperación de información relevante de un corpus o base de datos grande. Esta información luego se utiliza para generar respuestas o acciones. **Cómo funciona:** 1. **Formular Prompts**: Crear prompts o consultas bien estructurados en función de la tarea o entrada del usuario. 2. **Recuperar Información**: Usar los prompts para buscar datos relevantes de una base de conocimiento o conjunto de datos preexistente. 3. **Generar Respuesta**: Combinar la información recuperada con modelos generativos de IA para producir una respuesta completa y coherente. **Ejemplo en Agente de Viajes**: - Entrada del Usuario: "Quiero visitar museos en París." - Prompt: "Encuentra los principales museos en París." - Información Recuperada: Detalles sobre el Museo del Louvre, Musée d'Orsay, etc. - Respuesta Generada: "Aquí tienes algunos de los principales museos en París: Museo del Louvre, Musée d'Orsay y Centro Pompidou." #### RAG como Herramienta **¿Qué es?** - Como herramienta, RAG es un sistema integrado que automatiza el proceso de recuperación y generación, facilitando a los desarrolladores implementar funcionalidades complejas de IA sin tener que crear prompts manualmente para cada consulta. **Cómo funciona:** 1. **Integración**: Integrar RAG dentro de la arquitectura del agente de IA, permitiéndole manejar automáticamente las tareas de recuperación y generación. 2. **Automatización**: La herramienta gestiona todo el proceso, desde recibir la entrada del usuario hasta generar la respuesta final, sin requerir prompts explícitos para cada paso. 3. **Eficiencia**: Mejora el rendimiento del agente al simplificar el proceso de recuperación y generación, permitiendo respuestas más rápidas y precisas. **Ejemplo en Agente de Viajes**: - Entrada del Usuario: "Quiero visitar museos en París." - Herramienta RAG: Recupera automáticamente información sobre museos y genera una respuesta. - Respuesta Generada: "Aquí tienes algunos de los principales museos en París: Museo del Louvre, Musée d'Orsay y Centro Pompidou." ### Comparación | Aspecto | Técnica de Prompts | Herramienta | |------------------------|-----------------------------------------------------|----------------------------------------------| | **Manual vs Automático**| Formulación manual de prompts para cada consulta. | Proceso automatizado de recuperación y generación. | | **Control** | Ofrece más control sobre el proceso de recuperación.| Simplifica y automatiza la recuperación y generación. | | **Flexibilidad** | Permite prompts personalizados según necesidades específicas. | Más eficiente para implementaciones a gran escala. | | **Complejidad** | Requiere creación y ajuste de prompts. | Más fácil de integrar en la arquitectura de un agente de IA. | ### Ejemplos Prácticos **Ejemplo de Técnica de Prompts:** ```python def search_museums_in_paris(): prompt = "Find top museums in Paris" search_results = search_web(prompt) return search_results museums = search_museums_in_paris() print("Top Museums in Paris:", museums) ``` **Ejemplo de Herramienta:** ```python class Travel_Agent: def __init__(self): self.rag_tool = RAGTool() def get_museums_in_paris(self): user_input = "I want to visit museums in Paris." response = self.rag_tool.retrieve_and_generate(user_input) return response travel_agent = Travel_Agent() museums = travel_agent.get_museums_in_paris() print("Top Museums in Paris:", museums) ``` ``` ```markdown ¿los mejores museos en París?"). - **Intención de Navegación**: El usuario quiere navegar a un sitio web o página específica (por ejemplo, "Sitio web oficial del Museo del Louvre"). - **Intención Transaccional**: El usuario tiene como objetivo realizar una transacción, como reservar un vuelo o hacer una compra (por ejemplo, "Reservar un vuelo a París"). 2. **Conciencia de Contexto**: - Analizar el contexto de la consulta del usuario ayuda a identificar con precisión su intención. Esto incluye considerar interacciones previas, preferencias del usuario y los detalles específicos de la consulta actual. 3. **Procesamiento de Lenguaje Natural (NLP)**: - Se emplean técnicas de NLP para entender e interpretar las consultas en lenguaje natural proporcionadas por los usuarios. Esto incluye tareas como reconocimiento de entidades, análisis de sentimientos y análisis de consultas. 4. **Personalización**: - Personalizar los resultados de búsqueda basándose en el historial del usuario, sus preferencias y comentarios mejora la relevancia de la información recuperada. #### Ejemplo Práctico: Búsqueda con Intención en Agente de Viajes Tomemos como ejemplo el Agente de Viajes para ver cómo se puede implementar la búsqueda con intención. 1. **Recolección de Preferencias del Usuario** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Entendiendo la Intención del Usuario** ```python def identify_intent(query): if "book" in query or "purchase" in query: return "transactional" elif "website" in query or "official" in query: return "navigational" else: return "informational" ``` 3. **Conciencia de Contexto** ```python def analyze_context(query, user_history): # Combine current query with user history to understand context context = { "current_query": query, "user_history": user_history } return context ``` 4. **Buscar y Personalizar Resultados** ```python def search_with_intent(query, preferences, user_history): intent = identify_intent(query) context = analyze_context(query, user_history) if intent == "informational": search_results = search_information(query, preferences) elif intent == "navigational": search_results = search_navigation(query) elif intent == "transactional": search_results = search_transaction(query, preferences) personalized_results = personalize_results(search_results, user_history) return personalized_results def search_information(query, preferences): # Example search logic for informational intent results = search_web(f"best {preferences['interests']} in {preferences['destination']}") return results def search_navigation(query): # Example search logic for navigational intent results = search_web(query) return results def search_transaction(query, preferences): # Example search logic for transactional intent results = search_web(f"book {query} to {preferences['destination']}") return results def personalize_results(results, user_history): # Example personalization logic personalized = [result for result in results if result not in user_history] return personalized[:10] # Return top 10 personalized results ``` 5. **Ejemplo de Uso** ```python travel_agent = Travel_Agent() preferences = { "destination": "Paris", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) user_history = ["Louvre Museum website", "Book flight to Paris"] query = "best museums in Paris" results = search_with_intent(query, preferences, user_history) print("Search Results:", results) ``` --- ## 4. Generación de Código como Herramienta Los agentes generadores de código utilizan modelos de IA para escribir y ejecutar código, resolviendo problemas complejos y automatizando tareas. ### Agentes Generadores de Código Los agentes generadores de código utilizan modelos de IA generativa para escribir y ejecutar código. Estos agentes pueden resolver problemas complejos, automatizar tareas y proporcionar valiosos conocimientos generando y ejecutando código en varios lenguajes de programación. #### Aplicaciones Prácticas 1. **Generación Automática de Código**: Generar fragmentos de código para tareas específicas, como análisis de datos, web scraping o aprendizaje automático. 2. **SQL como RAG**: Utilizar consultas SQL para recuperar y manipular datos de bases de datos. 3. **Resolución de Problemas**: Crear y ejecutar código para resolver problemas específicos, como optimización de algoritmos o análisis de datos. #### Ejemplo: Agente Generador de Código para Análisis de Datos Imagina que estás diseñando un agente generador de código. Así es como podría funcionar: 1. **Tarea**: Analizar un conjunto de datos para identificar tendencias y patrones. 2. **Pasos**: - Cargar el conjunto de datos en una herramienta de análisis de datos. - Generar consultas SQL para filtrar y agregar los datos. - Ejecutar las consultas y recuperar los resultados. - Utilizar los resultados para generar visualizaciones y conocimientos. 3. **Recursos Requeridos**: Acceso al conjunto de datos, herramientas de análisis de datos y capacidades de SQL. 4. **Experiencia**: Utilizar resultados de análisis pasados para mejorar la precisión y relevancia de futuros análisis. ### Ejemplo: Agente Generador de Código para Agente de Viajes En este ejemplo, diseñaremos un agente generador de código, Agente de Viajes, para ayudar a los usuarios a planificar sus viajes generando y ejecutando código. Este agente puede manejar tareas como obtener opciones de viaje, filtrar resultados y compilar un itinerario utilizando IA generativa. #### Descripción General del Agente Generador de Código 1. **Recolección de Preferencias del Usuario**: Recopila información del usuario como destino, fechas de viaje, presupuesto e intereses. 2. **Generación de Código para Obtener Datos**: Genera fragmentos de código para recuperar datos sobre vuelos, hoteles y atracciones. 3. **Ejecución del Código Generado**: Ejecuta el código generado para obtener información en tiempo real. 4. **Generación de Itinerario**: Compila los datos obtenidos en un plan de viaje personalizado. 5. **Ajuste Basado en Comentarios**: Recibe comentarios del usuario y regenera el código si es necesario para refinar los resultados. #### Implementación Paso a Paso 1. **Recolección de Preferencias del Usuario** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Generación de Código para Obtener Datos** ```python def generate_code_to_fetch_data(preferences): # Example: Generate code to search for flights based on user preferences code = f""" def search_flights(): import requests response = requests.get('https://api.example.com/flights', params={preferences}) return response.json() """ return code def generate_code_to_fetch_hotels(preferences): # Example: Generate code to search for hotels code = f""" def search_hotels(): import requests response = requests.get('https://api.example.com/hotels', params={preferences}) return response.json() """ return code ``` 3. **Ejecución del Código Generado** ```python def execute_code(code): # Execute the generated code using exec exec(code) result = locals() return result travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) flight_code = generate_code_to_fetch_data(preferences) hotel_code = generate_code_to_fetch_hotels(preferences) flights = execute_code(flight_code) hotels = execute_code(hotel_code) print("Flight Options:", flights) print("Hotel Options:", hotels) ``` 4. **Generación de Itinerario** ```python def generate_itinerary(flights, hotels, attractions): itinerary = { "flights": flights, "hotels": hotels, "attractions": attractions } return itinerary attractions = search_attractions(preferences) itinerary = generate_itinerary(flights, hotels, attractions) print("Suggested Itinerary:", itinerary) ``` 5. **Ajuste Basado en Comentarios** ```python def adjust_based_on_feedback(feedback, preferences): # Adjust preferences based on user feedback if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] return preferences feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} updated_preferences = adjust_based_on_feedback(feedback, preferences) # Regenerate and execute code with updated preferences updated_flight_code = generate_code_to_fetch_data(updated_preferences) updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences) updated_flights = execute_code(updated_flight_code) updated_hotels = execute_code(updated_hotel_code) updated_itinerary = generate_itinerary(updated_flights, updated_hotels, attractions) print("Updated Itinerary:", updated_itinerary) ``` ### Aprovechando la Conciencia del Entorno y el Razonamiento Basarse en el esquema de la tabla puede mejorar el proceso de generación de consultas aprovechando la conciencia del entorno y el razonamiento. Aquí hay un ejemplo de cómo se puede hacer: 1. **Entender el Esquema**: El sistema entenderá el esquema de la tabla y usará esta información para fundamentar la generación de consultas. 2. **Ajuste Basado en Comentarios**: El sistema ajustará las preferencias del usuario en función de los comentarios y razonará sobre qué campos en el esquema necesitan ser actualizados. 3. **Generación y Ejecución de Consultas**: El sistema generará y ejecutará consultas para obtener datos actualizados de vuelos y hoteles en función de las nuevas preferencias. Aquí hay un ejemplo de código Python actualizado que incorpora estos conceptos: ```python def adjust_based_on_feedback(feedback, preferences, schema): # Adjust preferences based on user feedback if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] # Reasoning based on schema to adjust other related preferences for field in schema: if field in preferences: preferences[field] = adjust_based_on_environment(feedback, field, schema) return preferences def adjust_based_on_environment(feedback, field, schema): # Custom logic to adjust preferences based on schema and feedback if field in feedback["liked"]: return schema[field]["positive_adjustment"] elif field in feedback["disliked"]: return schema[field]["negative_adjustment"] return schema[field]["default"] def generate_code_to_fetch_data(preferences): # Generate code to fetch flight data based on updated preferences return f"fetch_flights(preferences={preferences})" def generate_code_to_fetch_hotels(preferences): # Generate code to fetch hotel data based on updated preferences return f"fetch_hotels(preferences={preferences})" def execute_code(code): # Simulate execution of code and return mock data return {"data": f"Executed: {code}"} def generate_itinerary(flights, hotels, attractions): # Generate itinerary based on flights, hotels, and attractions return {"flights": flights, "hotels": hotels, "attractions": attractions} # Example schema schema = { "favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"}, "avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"} } # Example usage preferences = {"favorites": "sightseeing", "avoid": "crowded places"} feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} updated_preferences = adjust_based_on_feedback(feedback, preferences, schema) # Regenerate and execute code with updated preferences updated_flight_code = generate_code_to_fetch_data(updated_preferences) updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences) updated_flights = execute_code(updated_flight_code) updated_hotels = execute_code(updated_hotel_code) updated_itinerary = generate_itinerary(updated_flights, updated_hotels, feedback["liked"]) print("Updated Itinerary:", updated_itinerary) ``` #### Explicación - Reserva Basada en Comentarios 1. **Conciencia del Esquema**: El método `schema` dictionary defines how preferences should be adjusted based on feedback. It includes fields like `favorites` and `avoid`, with corresponding adjustments. 2. **Adjusting Preferences (`adjust_based_on_feedback` method)**: This method adjusts preferences based on user feedback and the schema. 3. **Environment-Based Adjustments (`adjust_based_on_environment` personaliza los ajustes basados en el esquema y los comentarios. 4. **Generación y Ejecución de Consultas**: El sistema genera código para obtener datos actualizados de vuelos y hoteles en función de las preferencias ajustadas y simula la ejecución de estas consultas. 5. **Generación de Itinerario**: El sistema crea un itinerario actualizado basado en los nuevos datos de vuelos, hoteles y atracciones. Al hacer que el sistema sea consciente del entorno y razone en función del esquema, puede generar consultas más precisas y relevantes, lo que lleva a mejores recomendaciones de viaje y una experiencia de usuario más personalizada. ### Uso de SQL como Técnica de Recuperación-Aumentada por Generación (RAG) SQL (Lenguaje de Consulta Estructurada) es una herramienta poderosa para interactuar con bases de datos. Cuando se utiliza como parte de un enfoque de Recuperación-Aumentada por Generación (RAG), SQL puede recuperar datos relevantes de bases de datos para informar y generar respuestas o acciones en agentes de IA. Exploremos cómo SQL puede usarse como técnica RAG en el contexto del Agente de Viajes. #### Conceptos Clave 1. **Interacción con Bases de Datos**: - SQL se utiliza para consultar bases de datos, recuperar información relevante y manipular datos. - Ejemplo: Obtener detalles de vuelos, información de hoteles y atracciones de una base de datos de viajes. 2. **Integración con RAG**: - Las consultas SQL se generan en función de la entrada y preferencias del usuario. - Los datos recuperados se utilizan para generar recomendaciones o acciones personalizadas. 3. **Generación Dinámica de Consultas**: - El agente de IA genera consultas SQL dinámicas basadas en el contexto y las necesidades del usuario. - Ejemplo: Personalizar consultas SQL para filtrar resultados en función del presupuesto, fechas e intereses. #### Aplicaciones - **Generación Automática de Código**: Generar fragmentos de código para tareas específicas. - **SQL como RAG**: Utilizar consultas SQL para manipular datos. - **Resolución de Problemas**: Crear y ejecutar código para resolver problemas. **Ejemplo**: Un agente de análisis de datos: 1. **Tarea**: Analizar un conjunto de datos para encontrar tendencias. 2. **Pasos**: - Cargar el conjunto de datos. - Generar consultas SQL para filtrar datos. - Ejecutar consultas y recuperar resultados. - Generar visualizaciones y conocimientos. 3. **Recursos**: Acceso al conjunto de datos, capacidades de SQL. 4. **Experiencia**: Usar resultados pasados para mejorar futuros análisis. #### Ejemplo Práctico: Uso de SQL en Agente de Viajes 1. **Recolección de Preferencias del Usuario** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Generación de Consultas SQL** ```python def generate_sql_query(table, preferences): query = f"SELECT * FROM {table} WHERE " conditions = [] for key, value in preferences.items(): conditions.append(f"{key}='{value}'") query += " AND ".join(conditions) return query ``` 3. **Ejecución de Consultas SQL** ```python import sqlite3 def execute_sql_query(query, database="travel.db"): connection = sqlite3.connect(database) cursor = connection.cursor() cursor.execute(query) results = cursor.fetchall() connection.close() return results ``` 4. **Generación de Recomendaciones** ```python def generate_recommendations(preferences): flight_query = generate_sql_query("flights", preferences) hotel_query = generate_sql_query("hotels", preferences) attraction_query = generate_sql_query("attractions", preferences) flights = execute_sql_query(flight_query) hotels = execute_sql_query(hotel_query) attractions = execute_sql_query(attraction_query) itinerary = { "flights": flights, "hotels": hotels, "attractions": attractions } return itinerary travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = generate_recommendations(preferences) print("Suggested Itinerary:", itinerary) ``` #### Ejemplos de Consultas SQL 1. **Consulta de Vuelos** ```sql SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate'; ``` 2. **Consulta de Hoteles** ```sql SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate'; ``` 3. **Consulta de Atracciones** ```sql SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine'; ``` Al aprovechar SQL como parte de la técnica de Recuperación-Aumentada por Generación (RAG), agentes de IA como el Agente de Viajes pueden recuperar y utilizar dinámicamente datos relevantes para proporcionar recomendaciones precisas y personalizadas. ### Conclusión La metacognición es una herramienta poderosa que puede mejorar significativamente las capacidades de los agentes de IA. Al incorporar procesos metacognitivos, puedes diseñar agentes que sean más inteligentes, adaptables y eficientes. Utiliza los recursos adicionales para explorar más a fondo el fascinante mundo de la metacognición en agentes de IA. ``` **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por lograr precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse como la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/09-metacognition/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/09-metacognition/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 56889 }
# Agentes de IA en Producción ## Introducción Esta lección cubrirá: - Cómo planificar de manera efectiva el despliegue de tu Agente de IA en producción. - Errores comunes y problemas que podrías enfrentar al desplegar tu Agente de IA en producción. - Cómo gestionar costos mientras mantienes el rendimiento de tu Agente de IA. ## Objetivos de Aprendizaje Al completar esta lección, sabrás cómo/entenderás: - Técnicas para mejorar el rendimiento, los costos y la efectividad de un sistema de Agentes de IA en producción. - Qué evaluar y cómo evaluar tus Agentes de IA. - Cómo controlar los costos al desplegar Agentes de IA en producción. Es importante desplegar Agentes de IA confiables. Consulta también la lección "Construyendo Agentes de IA Confiables". ## Evaluando Agentes de IA Antes, durante y después de desplegar Agentes de IA, es fundamental tener un sistema adecuado para evaluarlos. Esto asegurará que tu sistema esté alineado con tus objetivos y los de tus usuarios. Para evaluar un Agente de IA, es importante tener la capacidad de evaluar no solo la salida del agente, sino todo el sistema en el que opera tu Agente de IA. Esto incluye, pero no se limita a: - La solicitud inicial al modelo. - La capacidad del agente para identificar la intención del usuario. - La capacidad del agente para identificar la herramienta adecuada para realizar la tarea. - La respuesta de la herramienta a la solicitud del agente. - La capacidad del agente para interpretar la respuesta de la herramienta. - La retroalimentación del usuario a la respuesta del agente. Esto te permitirá identificar áreas de mejora de manera más modular. Luego, puedes monitorear el efecto de los cambios en modelos, indicaciones, herramientas y otros componentes con mayor eficiencia. ## Problemas Comunes y Soluciones Potenciales con Agentes de IA | **Problema** | **Solución Potencial** | | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | El Agente de IA no realiza tareas de forma consistente | - Refina el prompt dado al Agente de IA; sé claro con los objetivos.<br>- Identifica si dividir las tareas en subtareas y manejarlas con múltiples agentes puede ser útil. | | El Agente de IA entra en bucles continuos | - Asegúrate de tener términos y condiciones claros de finalización para que el Agente sepa cuándo detener el proceso.<br>- Para tareas complejas que requieren razonamiento y planificación, usa un modelo más grande especializado en tareas de razonamiento. | | Las llamadas a herramientas del Agente de IA no funcionan bien | - Prueba y valida la salida de la herramienta fuera del sistema del agente.<br>- Refina los parámetros definidos, los prompts y los nombres de las herramientas. | | El sistema multi-agente no funciona de forma consistente | - Refina los prompts dados a cada agente para asegurarte de que sean específicos y distintos entre sí.<br>- Construye un sistema jerárquico usando un agente "enrutador" o controlador para determinar cuál agente es el correcto. | ## Gestión de Costos Aquí tienes algunas estrategias para gestionar los costos de desplegar Agentes de IA en producción: - **Almacenamiento en Caché de Respuestas** - Identificar solicitudes y tareas comunes y proporcionar las respuestas antes de que pasen por tu sistema agentivo es una buena forma de reducir el volumen de solicitudes similares. Incluso puedes implementar un flujo para identificar qué tan similar es una solicitud a tus solicitudes en caché utilizando modelos de IA más básicos. - **Uso de Modelos Más Pequeños** - Los Modelos de Lenguaje Pequeños (SLMs) pueden funcionar bien en ciertos casos de uso agentivos y reducirán significativamente los costos. Como se mencionó antes, construir un sistema de evaluación para determinar y comparar el rendimiento frente a modelos más grandes es la mejor manera de entender qué tan bien funcionará un SLM en tu caso de uso. - **Uso de un Modelo Enrutador** - Una estrategia similar es usar una diversidad de modelos y tamaños. Puedes usar un LLM/SLM o una función sin servidor para enrutar solicitudes según su complejidad a los modelos más adecuados. Esto también ayudará a reducir costos mientras se garantiza el rendimiento en las tareas adecuadas. ## Felicitaciones Esta es actualmente la última lección de "Agentes de IA para Principiantes". Planeamos seguir agregando lecciones basadas en comentarios y cambios en esta industria en constante crecimiento, así que vuelve a visitarnos en un futuro cercano. Si deseas continuar aprendiendo y construyendo con Agentes de IA, únete al [Azure AI Community Discord](https://discord.gg/kzRShWzttr). Allí organizamos talleres, mesas redondas comunitarias y sesiones de "pregúntame cualquier cosa". También contamos con una colección de materiales de aprendizaje adicionales que pueden ayudarte a comenzar a construir Agentes de IA en producción. **Descargo de responsabilidad**: Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por lograr precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/es/10-ai-agents-production/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/10-ai-agents-production/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 6106 }
# Configuration du Cours ## Introduction Cette leçon expliquera comment exécuter les exemples de code de ce cours. ## Prérequis - Un compte GitHub - Python 3.12+ ## Cloner ou Forker ce Dépôt Pour commencer, veuillez cloner ou forker le dépôt GitHub. Cela créera votre propre version du matériel de cours, vous permettant ainsi d'exécuter, de tester et de modifier le code ! Cela peut être fait en cliquant sur le lien pour [forker le dépôt](https://github.com/microsoft/ai-agents-for-beginners/fork). Vous devriez maintenant avoir votre propre version forkée de ce cours, comme ci-dessous : ![Dépôt Forké](../../../translated_images/forked-repo.eea246a73044cc984a1e462349e36e7336204f00785e3187b7399905feeada07.fr.png) ## Récupérer votre Token d'Accès Personnel (PAT) GitHub Ce cours utilise actuellement le Marketplace des modèles GitHub pour offrir un accès gratuit aux Modèles de Langage de Grande Taille (LLMs) qui seront utilisés pour créer des Agents IA. Pour accéder à ce service, vous devrez créer un Token d'Accès Personnel GitHub. Cela peut être fait en allant dans vos [paramètres de Tokens d'Accès Personnel](https://github.com/settings/personal-access-tokens) sur votre compte GitHub. Sélectionnez l'option `Fine-grained tokens` située à gauche de votre écran. Puis sélectionnez `Generate new token`. ![Générer un Token](../../../translated_images/generate-token.361ec40abe59b84ac68d63c23e2b6854d6fad82bd4e41feb98fc0e6f030e8ef7.fr.png) Copiez le nouveau token que vous venez de créer. Vous allez maintenant l'ajouter à votre fichier `.env` inclus dans ce cours. ## Ajouter ceci à vos Variables d'Environnement Pour créer votre fichier `.env`, exécutez la commande suivante dans votre terminal : ```bash cp .env.example .env ``` Cela copiera le fichier exemple et créera un fichier `.env` dans votre répertoire. Ouvrez ce fichier et collez le token que vous avez créé dans le champ `GITHUB_TOKEN=` du fichier .env. ## Installer les Paquets Requis Pour vous assurer d'avoir tous les paquets Python nécessaires à l'exécution du code, exécutez la commande suivante dans votre terminal. Nous vous recommandons de créer un environnement virtuel Python pour éviter tout conflit ou problème. ```bash pip install -r requirements.txt ``` Cela devrait installer les paquets Python requis. Vous êtes maintenant prêt à exécuter le code de ce cours. Bon apprentissage dans le monde des Agents IA ! Si vous rencontrez des problèmes lors de cette configuration, rejoignez notre [Discord de la Communauté Azure AI](https://discord.gg/kzRShWzttr) ou [créez un ticket](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst). ``` **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatisée basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations cruciales, il est recommandé de recourir à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/00-course-setup/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/00-course-setup/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 3385 }
# Introduction aux Agents IA et Cas d'Utilisation des Agents Bienvenue dans le cours "Agents IA pour Débutants" ! Ce cours vous offre des connaissances fondamentales et des exemples pratiques pour construire avec des Agents IA. Rejoignez la [communauté Discord Azure AI](https://discord.gg/kzRShWzttr) pour rencontrer d'autres apprenants, des créateurs d'Agents IA, et poser toutes vos questions sur ce cours. Pour débuter ce cours, nous allons d'abord mieux comprendre ce que sont les Agents IA et comment nous pouvons les utiliser dans les applications et les flux de travail que nous concevons. ## Introduction Cette leçon couvre : - Qu'est-ce qu'un Agent IA et quels sont les différents types d'agents ? - Quels cas d'utilisation sont les mieux adaptés aux Agents IA et comment peuvent-ils nous aider ? - Quels sont certains des éléments de base à prendre en compte lors de la conception de solutions agentiques ? ## Objectifs d'Apprentissage À la fin de cette leçon, vous devriez être capable de : - Comprendre les concepts des Agents IA et en quoi ils diffèrent des autres solutions d'IA. - Utiliser les Agents IA de manière efficace. - Concevoir des solutions agentiques de manière productive pour les utilisateurs et les clients. ## Définir les Agents IA et les Types d'Agents IA ### Qu'est-ce qu'un Agent IA ? Les Agents IA sont des **systèmes** qui permettent aux **Modèles de Langage de Grande Taille (LLMs)** de **réaliser des actions** en étendant leurs capacités grâce à l'accès à des **outils** et à des **connaissances**. Décomposons cette définition en parties plus simples : - **Système** - Il est important de considérer les agents non pas comme un simple composant, mais comme un système composé de plusieurs éléments. À un niveau basique, les composants d'un Agent IA sont : - **Environnement** - L'espace défini où l'Agent IA opère. Par exemple, si nous avions un Agent IA de réservation de voyages, l'environnement pourrait être le système de réservation utilisé par l'agent pour accomplir ses tâches. - **Capteurs** - Les environnements contiennent des informations et fournissent des retours. Les Agents IA utilisent des capteurs pour recueillir et interpréter ces informations sur l'état actuel de l'environnement. Dans l'exemple de l'agent de réservation, le système de réservation peut fournir des informations comme la disponibilité des hôtels ou les prix des vols. - **Actionneurs** - Une fois que l'Agent IA reçoit l'état actuel de l'environnement, il détermine quelle action effectuer pour modifier cet environnement en fonction de la tâche actuelle. Pour l'agent de réservation, cela pourrait être de réserver une chambre disponible pour l'utilisateur. ![Qu'est-ce qu'un Agent IA ?](../../../translated_images/what-are-ai-agents.125520f55950b252a429b04a9f41e0152d4dafa1f1bd9081f4f574631acb759e.fr.png?WT.mc_id=academic-105485-koreyst) **Modèles de Langage de Grande Taille** - Le concept d'agents existait avant la création des LLMs. L'avantage de construire des Agents IA avec des LLMs réside dans leur capacité à interpréter le langage humain et les données. Cette capacité leur permet d'interpréter les informations environnementales et de définir un plan pour modifier l'environnement. **Réaliser des Actions** - En dehors des systèmes d'Agents IA, les LLMs sont limités aux situations où l'action consiste à générer du contenu ou des informations en réponse à une demande de l'utilisateur. Dans les systèmes d'Agents IA, les LLMs peuvent accomplir des tâches en interprétant la demande de l'utilisateur et en utilisant les outils disponibles dans leur environnement. **Accès aux Outils** - Les outils auxquels le LLM a accès sont définis par 1) l'environnement dans lequel il opère et 2) le développeur de l'Agent IA. Dans l'exemple de l'agent de voyage, les outils de l'agent sont limités par les opérations disponibles dans le système de réservation, et/ou le développeur peut limiter l'accès de l'agent aux vols uniquement. **Connaissances** - En dehors des informations fournies par l'environnement, les Agents IA peuvent également récupérer des connaissances provenant d'autres systèmes, services, outils, et même d'autres agents. Dans l'exemple de l'agent de voyage, ces connaissances pourraient inclure les préférences de voyage de l'utilisateur situées dans une base de données client. ### Les différents types d'agents Maintenant que nous avons une définition générale des Agents IA, examinons quelques types spécifiques d'agents et comment ils pourraient être appliqués à un agent de réservation de voyages. | **Type d'Agent** | **Description** | **Exemple** | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Agents Réflexes Simples** | Réalisent des actions immédiates basées sur des règles prédéfinies. | L'agent de voyage interprète le contexte d'un e-mail et transfère les plaintes liées aux voyages au service client. | | **Agents Réflexes Basés sur un Modèle** | Réalisent des actions basées sur un modèle du monde et les changements de ce modèle. | L'agent de voyage priorise les itinéraires avec des variations importantes de prix grâce à l'accès à des données historiques sur les prix. | | **Agents Basés sur des Objectifs** | Créent des plans pour atteindre des objectifs spécifiques en interprétant l'objectif et en déterminant les actions nécessaires pour y parvenir. | L'agent de voyage organise un trajet en déterminant les arrangements nécessaires (voiture, transports publics, vols) pour aller de l'emplacement actuel à la destination. | | **Agents Basés sur l'Utilité** | Prennent en compte les préférences et évaluent numériquement les compromis pour déterminer comment atteindre leurs objectifs. | L'agent de voyage maximise l'utilité en pesant la commodité contre le coût lors de la réservation de voyages. | | **Agents Apprenants** | S'améliorent au fil du temps en répondant aux retours et en ajustant leurs actions en conséquence. | L'agent de voyage s'améliore en utilisant les retours des clients recueillis via des enquêtes post-voyage pour ajuster les futures réservations. | | **Agents Hiérarchiques** | Comprennent plusieurs agents dans un système hiérarchisé, où des agents de haut niveau divisent les tâches en sous-tâches pour les agents de niveau inférieur. | L'agent de voyage annule un voyage en décomposant la tâche en sous-tâches (par exemple, annuler des réservations spécifiques) et en demandant à des agents de niveau inférieur de les exécuter, tout en rapportant au niveau supérieur. | | **Systèmes Multi-Agents (MAS)** | Les agents réalisent des tâches de manière indépendante, soit de façon coopérative, soit de façon compétitive. | Coopératif : Plusieurs agents réservent des services de voyage spécifiques comme des hôtels, des vols, et des divertissements. Compétitif : Plusieurs agents gèrent et se disputent un calendrier partagé pour réserver des clients dans un hôtel. | ## Quand Utiliser les Agents IA Dans la section précédente, nous avons utilisé l'exemple de l'Agent de Voyage pour expliquer comment les différents types d'agents peuvent être utilisés dans diverses situations de réservation. Nous continuerons d'utiliser cette application tout au long du cours. Examinons maintenant les types de cas d'utilisation pour lesquels les Agents IA sont les mieux adaptés : ![Quand utiliser les Agents IA ?](../../../translated_images/when-to-use-ai-agents.912b9a02e9e0e2af45a3e24faa4e912e334ec23f21f0cf5cb040b7e899b09cd0.fr.png?WT.mc_id=academic-105485-koreyst) - **Problèmes Ouverts** - permettant au LLM de déterminer les étapes nécessaires pour accomplir une tâche, car elles ne peuvent pas toujours être codées en dur dans un flux de travail. - **Processus Multi-Étapes** - tâches nécessitant un certain niveau de complexité, où l'Agent IA doit utiliser des outils ou des informations sur plusieurs itérations plutôt que sur une seule récupération. - **Amélioration au Fil du Temps** - tâches où l'agent peut s'améliorer en recevant des retours de son environnement ou de ses utilisateurs afin de fournir une meilleure utilité. Nous aborderons plus en détail les considérations relatives à l'utilisation des Agents IA dans la leçon sur la Création d'Agents IA de Confiance. ## Bases des Solutions Agentiques ### Développement d'Agents La première étape pour concevoir un système d'Agent IA est de définir les outils, actions et comportements. Dans ce cours, nous nous concentrons sur l'utilisation du **service Azure AI Agent** pour définir nos agents. Il propose des fonctionnalités telles que : - La sélection de modèles ouverts comme OpenAI, Mistral, et Llama - L'utilisation de données sous licence via des fournisseurs comme Tripadvisor - L'utilisation d'outils standardisés OpenAPI 3.0 ### Modèles Agentiques La communication avec les LLMs se fait via des prompts. Étant donné la nature semi-autonome des Agents IA, il n'est pas toujours possible ou nécessaire de reformuler manuellement les prompts après un changement dans l'environnement. Nous utilisons des **Modèles Agentiques** qui permettent de formuler des prompts pour le LLM sur plusieurs étapes de manière plus évolutive. Ce cours est structuré autour de certains des modèles agentiques populaires actuels. ### Cadres Agentiques Les Cadres Agentiques permettent aux développeurs d'implémenter des modèles agentiques via du code. Ces cadres offrent des modèles, des plugins, et des outils pour une meilleure collaboration entre les Agents IA. Ces avantages incluent une meilleure observabilité et une résolution des problèmes plus efficace pour les systèmes d'Agents IA. Dans ce cours, nous explorerons le cadre AutoGen basé sur la recherche ainsi que le cadre prêt pour la production proposé par Semantic Kernel. **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatisée basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de recourir à une traduction professionnelle réalisée par un humain. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/01-intro-to-ai-agents/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/01-intro-to-ai-agents/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 11779 }
# Explorer les Frameworks d'Agents IA Les frameworks d'agents IA sont des plateformes logicielles conçues pour simplifier la création, le déploiement et la gestion d'agents IA. Ces frameworks offrent aux développeurs des composants préconstruits, des abstractions et des outils qui facilitent le développement de systèmes IA complexes. Ces frameworks permettent aux développeurs de se concentrer sur les aspects uniques de leurs applications en proposant des approches standardisées pour relever les défis communs du développement d'agents IA. Ils améliorent la scalabilité, l'accessibilité et l'efficacité dans la construction de systèmes IA. ## Introduction Cette leçon couvrira : - Ce que sont les frameworks d'agents IA et ce qu'ils permettent aux développeurs de réaliser. - Comment les équipes peuvent les utiliser pour prototyper rapidement, itérer et améliorer les capacités de leurs agents. - Les différences entre les frameworks et outils créés par Microsoft ([Autogen](https://aka.ms/ai-agents/autogen) / [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) / [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service)). - Est-il possible d'intégrer directement mes outils existants de l'écosystème Azure, ou ai-je besoin de solutions autonomes ? - Qu'est-ce que le service Azure AI Agents et comment cela m'aide-t-il ? ## Objectifs d'apprentissage Les objectifs de cette leçon sont de vous aider à comprendre : - Le rôle des frameworks d'agents IA dans le développement IA. - Comment tirer parti des frameworks d'agents IA pour construire des agents intelligents. - Les capacités clés offertes par les frameworks d'agents IA. - Les différences entre Autogen, Semantic Kernel et Azure AI Agent Service. ## Que sont les frameworks d'agents IA et que permettent-ils aux développeurs de faire ? Les frameworks IA traditionnels peuvent vous aider à intégrer l'IA dans vos applications et à améliorer ces dernières de plusieurs façons : - **Personnalisation** : L'IA peut analyser le comportement et les préférences des utilisateurs pour fournir des recommandations, contenus et expériences personnalisés. Exemple : Les services de streaming comme Netflix utilisent l'IA pour suggérer des films et des séries en fonction de l'historique de visionnage, améliorant ainsi l'engagement et la satisfaction des utilisateurs. - **Automatisation et efficacité** : L'IA peut automatiser les tâches répétitives, rationaliser les flux de travail et améliorer l'efficacité opérationnelle. Exemple : Les applications de service client utilisent des chatbots alimentés par l'IA pour traiter les demandes courantes, réduisant ainsi les temps de réponse et libérant les agents humains pour des problèmes plus complexes. - **Amélioration de l'expérience utilisateur** : L'IA peut améliorer l'expérience utilisateur globale en proposant des fonctionnalités intelligentes comme la reconnaissance vocale, le traitement du langage naturel et le texte prédictif. Exemple : Les assistants virtuels comme Siri et Google Assistant utilisent l'IA pour comprendre et répondre aux commandes vocales, facilitant l'interaction des utilisateurs avec leurs appareils. ### Tout cela semble génial, n'est-ce pas ? Alors pourquoi avons-nous besoin de frameworks d'agents IA ? Les frameworks d'agents IA représentent quelque chose de plus que les simples frameworks IA. Ils sont conçus pour permettre la création d'agents intelligents capables d'interagir avec les utilisateurs, d'autres agents et leur environnement pour atteindre des objectifs spécifiques. Ces agents peuvent adopter un comportement autonome, prendre des décisions et s'adapter à des conditions changeantes. Examinons quelques capacités clés offertes par les frameworks d'agents IA : - **Collaboration et coordination entre agents** : Permettent la création de multiples agents IA capables de travailler ensemble, communiquer et se coordonner pour résoudre des tâches complexes. - **Automatisation et gestion des tâches** : Fournissent des mécanismes pour automatiser des flux de travail en plusieurs étapes, déléguer des tâches et gérer dynamiquement les tâches entre les agents. - **Compréhension contextuelle et adaptation** : Équipent les agents de la capacité à comprendre le contexte, s'adapter à des environnements changeants et prendre des décisions basées sur des informations en temps réel. En résumé, les agents permettent d'aller plus loin, de pousser l'automatisation à un niveau supérieur et de créer des systèmes plus intelligents capables de s'adapter et d'apprendre de leur environnement. ## Comment prototyper, itérer et améliorer rapidement les capacités d’un agent ? C'est un domaine en constante évolution, mais il existe des éléments communs à la plupart des frameworks d'agents IA qui peuvent vous aider à prototyper et itérer rapidement, notamment les composants modulaires, les outils collaboratifs et l'apprentissage en temps réel. Explorons ces éléments : - **Utiliser des composants modulaires** : Les frameworks IA offrent des composants préconstruits comme des invites, des analyseurs et des gestionnaires de mémoire. - **Exploiter des outils collaboratifs** : Concevoir des agents avec des rôles et tâches spécifiques pour tester et affiner les flux de travail collaboratifs. - **Apprendre en temps réel** : Mettre en œuvre des boucles de rétroaction où les agents apprennent des interactions et ajustent leur comportement de manière dynamique. ### Utiliser des composants modulaires Des frameworks comme LangChain et Microsoft Semantic Kernel offrent des composants préconstruits tels que des invites, des analyseurs et des gestionnaires de mémoire. **Comment les équipes peuvent les utiliser** : Les équipes peuvent assembler rapidement ces composants pour créer un prototype fonctionnel sans partir de zéro, ce qui permet une expérimentation et une itération rapides. **Comment cela fonctionne en pratique** : Vous pouvez utiliser un analyseur préconstruit pour extraire des informations des entrées utilisateur, un module de mémoire pour stocker et récupérer des données, et un générateur d'invites pour interagir avec les utilisateurs, sans avoir à construire ces composants à partir de zéro. **Exemple de code**. Voici un exemple montrant comment utiliser un analyseur préconstruit pour extraire des informations des entrées utilisateur : ```python from langchain import Parser parser = Parser() user_input = "Book a flight from New York to London on July 15th" parsed_data = parser.parse(user_input) print(parsed_data) # Output: {'origin': 'New York', 'destination': 'London', 'date': 'July 15th'} ``` Ce que vous voyez dans cet exemple, c'est comment tirer parti d'un analyseur préconstruit pour extraire des informations clés des entrées utilisateur, comme l'origine, la destination et la date d'une demande de réservation de vol. Cette approche modulaire vous permet de vous concentrer sur la logique de haut niveau. ### Exploiter des outils collaboratifs Des frameworks comme CrewAI et Microsoft Autogen facilitent la création de plusieurs agents capables de travailler ensemble. **Comment les équipes peuvent les utiliser** : Les équipes peuvent concevoir des agents avec des rôles et tâches spécifiques, leur permettant de tester et affiner les flux de travail collaboratifs et d'améliorer l'efficacité globale du système. **Comment cela fonctionne en pratique** : Vous pouvez créer une équipe d'agents où chaque agent a une fonction spécialisée, comme la récupération de données, l'analyse ou la prise de décision. Ces agents peuvent communiquer et partager des informations pour atteindre un objectif commun, comme répondre à une requête utilisateur ou accomplir une tâche. **Exemple de code (Autogen)** : ```python # creating agents, then create a round robin schedule where they can work together, in this case in order # Data Retrieval Agent # Data Analysis Agent # Decision Making Agent agent_retrieve = AssistantAgent( name="dataretrieval", model_client=model_client, tools=[retrieve_tool], system_message="Use tools to solve tasks." ) agent_analyze = AssistantAgent( name="dataanalysis", model_client=model_client, tools=[analyze_tool], system_message="Use tools to solve tasks." ) # conversation ends when user says "APPROVE" termination = TextMentionTermination("APPROVE") user_proxy = UserProxyAgent("user_proxy", input_func=input) team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination) stream = team.run_stream(task="Analyze data", max_turns=10) # Use asyncio.run(...) when running in a script. await Console(stream) ``` Dans le code ci-dessus, vous voyez comment créer une tâche impliquant plusieurs agents travaillant ensemble pour analyser des données. Chaque agent remplit une fonction spécifique, et la tâche est exécutée en coordonnant les agents pour atteindre le résultat souhaité. En créant des agents dédiés avec des rôles spécialisés, vous pouvez améliorer l'efficacité et les performances des tâches. ### Apprendre en temps réel Les frameworks avancés offrent des capacités de compréhension contextuelle et d'adaptation en temps réel. **Comment les équipes peuvent les utiliser** : Les équipes peuvent mettre en œuvre des boucles de rétroaction où les agents apprennent des interactions et ajustent leur comportement de manière dynamique, ce qui conduit à une amélioration continue et à un affinement des capacités. **Comment cela fonctionne en pratique** : Les agents peuvent analyser les retours des utilisateurs, les données environnementales et les résultats des tâches pour mettre à jour leur base de connaissances, ajuster leurs algorithmes de prise de décision et améliorer leurs performances au fil du temps. Ce processus d'apprentissage itératif permet aux agents de s'adapter aux conditions changeantes et aux préférences des utilisateurs, améliorant ainsi l'efficacité globale du système. ## Quelles sont les différences entre les frameworks Autogen, Semantic Kernel et Azure AI Agent Service ? Il existe plusieurs façons de comparer ces frameworks, mais examinons quelques différences clés en termes de conception, de capacités et de cas d'utilisation cibles : --- (La traduction continue ici, mais suit la même logique en respectant les consignes) --- basé sur les objectifs du projet. Idéal pour la compréhension du langage naturel, la génération de contenu. - **Azure AI Agent Service** : Modèles flexibles, mécanismes de sécurité d'entreprise, méthodes de stockage des données. Idéal pour un déploiement sécurisé, évolutif et flexible d'agents IA dans des applications d'entreprise. ## Puis-je intégrer directement mes outils existants de l'écosystème Azure, ou ai-je besoin de solutions autonomes ? La réponse est oui, vous pouvez intégrer directement vos outils existants de l'écosystème Azure avec Azure AI Agent Service, notamment parce qu'il a été conçu pour fonctionner de manière transparente avec d'autres services Azure. Par exemple, vous pourriez intégrer Bing, Azure AI Search et Azure Functions. Il existe également une intégration approfondie avec Azure AI Foundry. Pour Autogen et Semantic Kernel, vous pouvez également intégrer avec les services Azure, mais cela peut nécessiter d'appeler les services Azure depuis votre code. Une autre manière d'intégrer est d'utiliser les SDK Azure pour interagir avec les services Azure depuis vos agents. De plus, comme mentionné, vous pouvez utiliser Azure AI Agent Service comme orchestrateur pour vos agents construits dans Autogen ou Semantic Kernel, ce qui offrirait un accès facile à l'écosystème Azure. ## Références - [1] - [Azure Agent Service](https://techcommunity.microsoft.com/blog/azure-ai-services-blog/introducing-azure-ai-agent-service/4298357) - [2] - [Semantic Kernel and Autogen](https://devblogs.microsoft.com/semantic-kernel/microsofts-agentic-ai-frameworks-autogen-and-semantic-kernel/) - [3] - [Semantic Kernel Agent Framework](https://learn.microsoft.com/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp) - [4] - [Azure AI Agent service](https://learn.microsoft.com/azure/ai-services/agents/overview) - [5] - [Using Azure AI Agent Service with AutoGen / Semantic Kernel to build a multi-agent's solution](https://techcommunity.microsoft.com/blog/educatordeveloperblog/using-azure-ai-agent-service-with-autogen--semantic-kernel-to-build-a-multi-agen/4363121) **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatisée basés sur l'intelligence artificielle. Bien que nous fassions de notre mieux pour garantir l'exactitude, veuillez noter que les traductions automatiques peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de recourir à une traduction professionnelle effectuée par un humain. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/02-explore-agentic-frameworks/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/02-explore-agentic-frameworks/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 13286 }
# Principes de Conception Agentique pour l'IA ## Introduction Il existe de nombreuses façons d'aborder la création de systèmes d'IA agentique. Étant donné que l'ambiguïté est une caractéristique inhérente et non un défaut dans la conception de l'IA générative, il est parfois difficile pour les ingénieurs de savoir par où commencer. Nous avons élaboré un ensemble de principes de conception UX centrés sur l'humain pour permettre aux développeurs de créer des systèmes agentiques centrés sur les utilisateurs, répondant à leurs besoins professionnels. Ces principes de conception ne constituent pas une architecture prescriptive, mais plutôt un point de départ pour les équipes qui définissent et construisent des expériences d'agents. En général, les agents devraient : - Élargir et amplifier les capacités humaines (brainstorming, résolution de problèmes, automatisation, etc.) - Combler les lacunes en matière de connaissances (me mettre à jour sur des domaines de connaissance, traduction, etc.) - Faciliter et soutenir la collaboration en respectant les préférences individuelles pour travailler avec d'autres - Nous rendre meilleurs (par exemple, coach de vie/gestionnaire de tâches, nous aider à apprendre la régulation émotionnelle et des compétences de pleine conscience, renforcer la résilience, etc.) ## Cette Leçon Couvre - Quels sont les Principes de Conception Agentique - Quelles sont les directives à suivre pour mettre en œuvre ces principes de conception - Quels sont des exemples d'utilisation de ces principes de conception ## Objectifs d'Apprentissage Après avoir terminé cette leçon, vous serez en mesure de : 1. Expliquer ce que sont les Principes de Conception Agentique 2. Expliquer les directives pour utiliser les Principes de Conception Agentique 3. Comprendre comment construire un agent en utilisant les Principes de Conception Agentique ## Les Principes de Conception Agentique ![Principes de Conception Agentique](../../../translated_images/agentic-design-principles.9f32a64bb6e2aa5a1bdffb70111aa724058bc248b1a3dd3c6661344015604cff.fr.png?WT.mc_id=academic-105485-koreyst) ### Agent (Espace) C'est l'environnement dans lequel l'agent opère. Ces principes guident la manière dont nous concevons les agents pour interagir dans des mondes physiques et numériques. - **Connecter, pas isoler** – aider à connecter les personnes à d'autres personnes, événements et connaissances exploitables pour favoriser la collaboration et le lien. - Les agents aident à relier événements, connaissances et individus. - Les agents rapprochent les gens. Ils ne sont pas conçus pour remplacer ou minimiser les individus. - **Facilement accessible mais parfois invisible** – l'agent opère principalement en arrière-plan et n'intervient que lorsqu'il est pertinent et approprié. - L'agent est facilement accessible et repérable par les utilisateurs autorisés sur n'importe quel appareil ou plateforme. - L'agent prend en charge des entrées et sorties multimodales (son, voix, texte, etc.). - L'agent peut passer de manière fluide de l'avant-plan à l'arrière-plan ; de proactif à réactif, en fonction de son évaluation des besoins de l'utilisateur. - L'agent peut fonctionner de manière invisible, mais son processus en arrière-plan et sa collaboration avec d'autres agents sont transparents et contrôlables par l'utilisateur. ### Agent (Temps) C'est ainsi que l'agent fonctionne au fil du temps. Ces principes guident la manière dont nous concevons les agents interagissant à travers le passé, le présent et le futur. - **Passé** : Réfléchir à l'historique incluant état et contexte. - L'agent fournit des résultats plus pertinents grâce à l'analyse de données historiques plus riches au-delà de l'événement, des personnes ou des états. - L'agent établit des connexions à partir d'événements passés et réfléchit activement à sa mémoire pour interagir avec les situations actuelles. - **Présent** : Encourager plutôt que notifier. - L'agent adopte une approche globale pour interagir avec les personnes. Lorsqu'un événement se produit, il va au-delà de la notification statique ou d'autres formalités statiques. Il peut simplifier les flux ou générer des indices dynamiques pour attirer l'attention de l'utilisateur au bon moment. - L'agent délivre des informations en fonction du contexte, des changements sociaux et culturels, et adaptées aux intentions de l'utilisateur. - L'interaction avec l'agent peut être progressive, évoluant en complexité pour autonomiser les utilisateurs sur le long terme. - **Futur** : S'adapter et évoluer. - L'agent s'adapte à divers appareils, plateformes et modalités. - L'agent s'adapte au comportement de l'utilisateur, aux besoins d'accessibilité, et est librement personnalisable. - L'agent se façonne et évolue grâce à une interaction continue avec l'utilisateur. ### Agent (Noyau) Ce sont les éléments clés au cœur de la conception d'un agent. - **Accepter l'incertitude mais établir la confiance**. - Un certain niveau d'incertitude de l'agent est attendu. L'incertitude est un élément clé de la conception des agents. - La confiance et la transparence sont des couches fondamentales dans la conception des agents. - Les humains contrôlent quand l'agent est activé/désactivé, et le statut de l'agent est clairement visible à tout moment. ## Les Directives Pour Mettre en Œuvre Ces Principes Lorsque vous utilisez les principes de conception ci-dessus, suivez les directives suivantes : 1. **Transparence** : Informez l'utilisateur que l'IA est impliquée, comment elle fonctionne (y compris ses actions passées), et comment donner des retours et modifier le système. 2. **Contrôle** : Permettez à l'utilisateur de personnaliser, spécifier ses préférences et personnaliser, et d'avoir le contrôle sur le système et ses attributs (y compris la possibilité d'oublier). 3. **Cohérence** : Visez des expériences cohérentes et multimodales sur tous les appareils et points d'accès. Utilisez des éléments d'interface utilisateur/UX familiers lorsque cela est possible (par exemple, une icône de microphone pour l'interaction vocale) et réduisez autant que possible la charge cognitive de l'utilisateur (par exemple, privilégiez des réponses concises, des aides visuelles et du contenu « En savoir plus »). ## Comment Concevoir un Agent de Voyage en Utilisant Ces Principes et Directives Imaginez que vous concevez un Agent de Voyage, voici comment vous pourriez envisager d'utiliser les Principes de Conception et les Directives : 1. **Transparence** – Informez l'utilisateur que l'Agent de Voyage est un agent activé par l'IA. Fournissez des instructions de base pour démarrer (par exemple, un message de « Bonjour », des exemples de requêtes). Documentez cela clairement sur la page produit. Montrez la liste des requêtes posées par l'utilisateur dans le passé. Expliquez clairement comment donner des retours (pouce levé et baissé, bouton « Envoyer un retour », etc.). Indiquez clairement si l'agent a des restrictions d'utilisation ou de sujet. 2. **Contrôle** – Assurez-vous qu'il est clair comment l'utilisateur peut modifier l'agent après sa création, par exemple avec des invites système. Permettez à l'utilisateur de choisir le niveau de détail de l'agent, son style d'écriture, et toute restriction sur ce dont l'agent ne doit pas parler. Autorisez l'utilisateur à consulter et supprimer tout fichier ou donnée associé(e), les requêtes et les conversations passées. 3. **Cohérence** – Assurez-vous que les icônes pour Partager une Requête, ajouter un fichier ou une photo, et taguer quelqu'un ou quelque chose sont standards et reconnaissables. Utilisez l'icône de trombone pour indiquer le téléversement/partage de fichier avec l'agent, et une icône d'image pour indiquer le téléversement de graphiques. ## Ressources Supplémentaires - [Practices for Governing Agentic AI Systems | OpenAI](https://openai.com) - [The HAX Toolkit Project - Microsoft Research](https://microsoft.com) - [Responsible AI Toolbox](https://responsibleaitoolbox.ai) ``` **Avertissement** : Ce document a été traduit à l'aide de services de traduction basés sur l'intelligence artificielle. Bien que nous fassions de notre mieux pour garantir l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de recourir à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées découlant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/03-agentic-design-patterns/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/03-agentic-design-patterns/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 8780 }
# Modèle de Conception d'Utilisation d'Outils ## Introduction Dans cette leçon, nous cherchons à répondre aux questions suivantes : - Qu'est-ce que le modèle de conception d'utilisation d'outils ? - À quels cas d'utilisation peut-il être appliqué ? - Quels sont les éléments nécessaires pour implémenter ce modèle de conception ? - Quelles sont les considérations particulières pour utiliser le modèle de conception d'utilisation d'outils afin de construire des agents d'IA fiables ? ## Objectifs d'Apprentissage Après avoir complété cette leçon, vous serez capable de : - Définir le modèle de conception d'utilisation d'outils et son objectif. - Identifier les cas d'utilisation où ce modèle est applicable. - Comprendre les éléments clés nécessaires pour implémenter ce modèle de conception. - Reconnaître les considérations pour garantir la fiabilité des agents d'IA utilisant ce modèle de conception. ## Qu'est-ce que le modèle de conception d'utilisation d'outils ? Le **modèle de conception d'utilisation d'outils** se concentre sur la capacité des LLMs (modèles de langage à grande échelle) à interagir avec des outils externes pour atteindre des objectifs spécifiques. Les outils sont des morceaux de code pouvant être exécutés par un agent pour effectuer des actions. Un outil peut être une fonction simple comme une calculatrice ou un appel API vers un service tiers, comme une recherche de prix d'actions ou une prévision météo. Dans le contexte des agents d'IA, les outils sont conçus pour être exécutés par des agents en réponse à des **appels de fonction générés par le modèle**. ## À quels cas d'utilisation peut-il être appliqué ? Les agents d'IA peuvent utiliser des outils pour accomplir des tâches complexes, récupérer des informations ou prendre des décisions. Le modèle de conception d'utilisation d'outils est souvent utilisé dans des scénarios nécessitant une interaction dynamique avec des systèmes externes tels que des bases de données, des services web ou des interpréteurs de code. Cette capacité est utile pour de nombreux cas d'utilisation, notamment : - **Récupération d'informations dynamiques :** Les agents peuvent interroger des API ou des bases de données externes pour obtenir des données à jour (par exemple, interroger une base SQLite pour des analyses de données, récupérer des prix d'actions ou des informations météorologiques). - **Exécution et interprétation de code :** Les agents peuvent exécuter du code ou des scripts pour résoudre des problèmes mathématiques, générer des rapports ou réaliser des simulations. - **Automatisation de flux de travail :** Automatiser des flux de travail répétitifs ou en plusieurs étapes en intégrant des outils tels que des planificateurs de tâches, des services d'e-mails ou des pipelines de données. - **Support client :** Les agents peuvent interagir avec des systèmes CRM, des plateformes de gestion des tickets ou des bases de connaissances pour résoudre des demandes des utilisateurs. - **Génération et édition de contenu :** Les agents peuvent utiliser des outils comme des correcteurs grammaticaux, des résumeurs de texte ou des évaluateurs de sécurité de contenu pour aider dans les tâches de création de contenu. ## Quels sont les éléments nécessaires pour implémenter le modèle de conception d'utilisation d'outils ? ### Appels de Fonction/Outil L'appel de fonction est le principal moyen permettant aux LLMs d'interagir avec des outils. Vous verrez souvent les termes 'Fonction' et 'Outil' utilisés de manière interchangeable, car les 'fonctions' (blocs de code réutilisables) sont les 'outils' que les agents utilisent pour accomplir des tâches. Pour qu'une fonction soit invoquée, le LLM doit comparer la demande de l'utilisateur à la description des fonctions. Un schéma contenant les descriptions de toutes les fonctions disponibles est envoyé au LLM. Le LLM sélectionne ensuite la fonction la plus appropriée pour la tâche et retourne son nom ainsi que ses arguments. La fonction sélectionnée est exécutée, sa réponse est renvoyée au LLM, qui utilise ces informations pour répondre à la demande de l'utilisateur. Pour que les développeurs puissent implémenter des appels de fonction pour les agents, ils auront besoin de : 1. Un modèle LLM prenant en charge les appels de fonction 2. Un schéma contenant les descriptions des fonctions 3. Le code de chaque fonction décrite Prenons l'exemple de l'obtention de l'heure actuelle dans une ville pour illustrer : - **Initialiser un LLM prenant en charge les appels de fonction :** Tous les modèles ne prennent pas en charge les appels de fonction, il est donc important de vérifier que le modèle utilisé le permet. [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling) prend en charge les appels de fonction. Nous pouvons commencer par initialiser le client Azure OpenAI. ```python # Initialize the Azure OpenAI client client = AzureOpenAI( azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), api_version="2024-05-01-preview" ) ``` - **Créer un schéma de fonction :** Ensuite, nous définissons un schéma JSON contenant le nom de la fonction, une description de ce que fait la fonction, ainsi que les noms et descriptions des paramètres de la fonction. Nous transmettons ensuite ce schéma au client créé ci-dessus, avec la demande de l'utilisateur pour trouver l'heure à San Francisco. Il est important de noter qu'un **appel d'outil** est ce qui est retourné, **et non** la réponse finale à la question. Comme mentionné précédemment, le LLM retourne le nom de la fonction qu'il a sélectionnée pour la tâche, ainsi que les arguments qui lui seront passés. ```python # Function description for the model to read tools = [ { "type": "function", "function": { "name": "get_current_time", "description": "Get the current time in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name, e.g. San Francisco", }, }, "required": ["location"], }, } } ] ``` ```python # Initial user message messages = [{"role": "user", "content": "What's the current time in San Francisco"}] # First API call: Ask the model to use the function response = client.chat.completions.create( model=deployment_name, messages=messages, tools=tools, tool_choice="auto", ) # Process the model's response response_message = response.choices[0].message messages.append(response_message) print("Model's response:") print(response_message) ``` ```bash Model's response: ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')]) ``` - **Le code de la fonction nécessaire pour accomplir la tâche :** Maintenant que le LLM a choisi la fonction à exécuter, le code réalisant la tâche doit être implémenté et exécuté. Nous pouvons implémenter le code pour obtenir l'heure actuelle en Python. Nous devrons également écrire le code pour extraire le nom et les arguments de `response_message` afin d'obtenir le résultat final. ```python def get_current_time(location): """Get the current time for a given location""" print(f"get_current_time called with location: {location}") location_lower = location.lower() for key, timezone in TIMEZONE_DATA.items(): if key in location_lower: print(f"Timezone found for {key}") current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p") return json.dumps({ "location": location, "current_time": current_time }) print(f"No timezone data found for {location_lower}") return json.dumps({"location": location, "current_time": "unknown"}) ``` ```python # Handle function calls if response_message.tool_calls: for tool_call in response_message.tool_calls: if tool_call.function.name == "get_current_time": function_args = json.loads(tool_call.function.arguments) time_response = get_current_time( location=function_args.get("location") ) messages.append({ "tool_call_id": tool_call.id, "role": "tool", "name": "get_current_time", "content": time_response, }) else: print("No tool calls were made by the model.") # Second API call: Get the final response from the model final_response = client.chat.completions.create( model=deployment_name, messages=messages, ) return final_response.choices[0].message.content ``` ```bash get_current_time called with location: San Francisco Timezone found for san francisco The current time in San Francisco is 09:24 AM. ``` L'appel de fonction est au cœur de la plupart, sinon de toutes les conceptions d'utilisation d'outils par les agents, bien que l'implémenter à partir de zéro puisse parfois être complexe. Comme nous l'avons appris dans la [Leçon 2](../../../02-explore-agentic-frameworks), les frameworks agentiques nous fournissent des blocs de construction préconstruits pour implémenter l'utilisation d'outils. ### Exemples d'Utilisation d'Outils avec des Frameworks Agentiques - ### **[Semantic Kernel](https://learn.microsoft.com/azure/ai-services/agents/overview)** Semantic Kernel est un framework open-source pour les développeurs .NET, Python et Java travaillant avec des LLMs. Il simplifie le processus d'utilisation des appels de fonction en décrivant automatiquement vos fonctions et leurs paramètres au modèle via un processus appelé [sérialisation](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions). Il gère également la communication entre le modèle et votre code. Un autre avantage d'utiliser un framework agentique comme Semantic Kernel est qu'il permet d'accéder à des outils préconstruits tels que [File Search](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step4_assistant_tool_file_search.py) et [Code Interpreter](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py). Le diagramme suivant illustre le processus d'appel de fonction avec Semantic Kernel : ![function calling](../../../translated_images/functioncalling-diagram.b5493ea5154ad8e3e4940d2e36a49101eec1398948e5d1039942203b4f5a4209.fr.png) Dans Semantic Kernel, les fonctions/outils sont appelés [Plugins](https://learn.microsoft.com/semantic-kernel/concepts/plugins/?pivots=programming-language-python). Nous pouvons convertir la fonction `get_current_time` function we saw earlier into a plugin by turning it into a class with the function in it. We can also import the `kernel_function` en utilisant un décorateur qui prend la description de la fonction. Lorsque vous créez un kernel avec le plugin GetCurrentTimePlugin, celui-ci sérialisera automatiquement la fonction et ses paramètres, créant ainsi le schéma à envoyer au LLM. ```python from semantic_kernel.functions import kernel_function class GetCurrentTimePlugin: async def __init__(self, location): self.location = location @kernel_function( description="Get the current time for a given location" ) def get_current_time(location: str = ""): ... ``` ```python from semantic_kernel import Kernel # Create the kernel kernel = Kernel() # Create the plugin get_current_time_plugin = GetCurrentTimePlugin(location) # Add the plugin to the kernel kernel.add_plugin(get_current_time_plugin) ``` - ### **[Azure AI Agent Service](https://learn.microsoft.com/azure/ai-services/agents/overview)** Azure AI Agent Service est un framework agentique plus récent conçu pour permettre aux développeurs de créer, déployer et faire évoluer des agents d'IA de haute qualité et extensibles, sans avoir à gérer les ressources informatiques et de stockage sous-jacentes. Il est particulièrement utile pour les applications d'entreprise, car il s'agit d'un service entièrement géré avec une sécurité de niveau entreprise. Comparé au développement avec l'API LLM directement, Azure AI Agent Service offre certains avantages, notamment : - Appels d'outils automatiques – pas besoin de parser un appel d'outil, d'invoquer l'outil et de gérer la réponse ; tout cela est désormais géré côté serveur. - Gestion sécurisée des données – au lieu de gérer votre propre état de conversation, vous pouvez utiliser des threads pour stocker toutes les informations nécessaires. - Outils prêts à l'emploi – Outils permettant d'interagir avec vos sources de données, comme Bing, Azure AI Search et Azure Functions. Les outils disponibles dans Azure AI Agent Service peuvent être divisés en deux catégories : 1. Outils de Connaissance : - [Grounding avec Bing Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview) - [File Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/file-search?tabs=python&pivots=overview) - [Azure AI Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search) 2. Outils d'Action : - [Appels de Fonction](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/function-calling?tabs=python&pivots=overview) - [Code Interpreter](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/code-interpreter?tabs=python&pivots=overview) - [Outils définis par OpenAI](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/openapi-spec?tabs=python&pivots=overview) - [Azure Functions](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-functions?pivots=overview) Le service Agent permet d'utiliser ces outils ensemble comme un `toolset`. It also utilizes `threads` which keep track of the history of messages from a particular conversation. Imagine you are a sales agent at a company called Contoso. You want to develop a conversational agent that can answer questions about your sales data. The image below illustrates how you could use Azure AI Agent Service to analyze your sales data: ![Agentic Service In Action](../../../translated_images/agent-service-in-action.8c2d8aa8e9d91feeb29549b3fde529f8332b243875154d03907616a69198afbc.fr.jpg?WT.mc_id=academic-105485-koreyst) To use any of these tools with the service we can create a client and define a tool or toolset. To implement this practically we can use the Python code below. The LLM will be able to look at the toolset and decide whether to use the user created function, `fetch_sales_data_using_sqlite_query`, ou le Code Interpreter préconstruit selon la demande de l'utilisateur. ```python import os from azure.ai.projects import AIProjectClient from azure.identity import DefaultAzureCredential from fecth_sales_data_functions import fetch_sales_data_using_sqlite_query # fetch_sales_data_using_sqlite_query function which can be found in a fecth_sales_data_functions.py file. from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool project_client = AIProjectClient.from_connection_string( credential=DefaultAzureCredential(), conn_str=os.environ["PROJECT_CONNECTION_STRING"], ) # Initialize function calling agent with the fetch_sales_data_using_sqlite_query function and adding it to the toolset fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query) toolset = ToolSet() toolset.add(fetch_data_function) # Initialize Code Interpreter tool and adding it to the toolset. code_interpreter = code_interpreter = CodeInterpreterTool() toolset = ToolSet() toolset.add(code_interpreter) agent = project_client.agents.create_agent( model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent", toolset=toolset ) ``` ## Quelles sont les considérations particulières pour utiliser le modèle de conception d'utilisation d'outils pour construire des agents d'IA fiables ? Une préoccupation fréquente avec le SQL généré dynamiquement par les LLMs est la sécurité, en particulier le risque d'injection SQL ou d'actions malveillantes, telles que la suppression ou la manipulation de la base de données. Bien que ces préoccupations soient valides, elles peuvent être efficacement atténuées en configurant correctement les permissions d'accès à la base de données. Pour la plupart des bases de données, cela implique de configurer la base comme en lecture seule. Pour des services de bases de données comme PostgreSQL ou Azure SQL, l'application doit se voir attribuer un rôle en lecture seule (SELECT). Exécuter l'application dans un environnement sécurisé renforce encore la protection. Dans les scénarios d'entreprise, les données sont généralement extraites et transformées à partir de systèmes opérationnels dans une base de données en lecture seule ou un entrepôt de données avec un schéma convivial. Cette approche garantit que les données sont sécurisées, optimisées pour la performance et l'accessibilité, et que l'application dispose d'un accès restreint en lecture seule. ## Ressources Supplémentaires - [Atelier sur Azure AI Agents Service](https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/) - [Atelier Contoso Creative Writer Multi-Agent](https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop) - [Tutoriel sur l'Appel de Fonction dans Semantic Kernel](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions) - [Code Interpreter dans Semantic Kernel](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py) - [Autogen Tools](https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html) ``` **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatisés basés sur l'IA. Bien que nous fassions de notre mieux pour garantir l'exactitude, veuillez noter que les traductions automatiques peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de recourir à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/04-tool-use/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/04-tool-use/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 20182 }
# Agentic RAG Cette leçon offre une vue d'ensemble complète de l'Agentic Retrieval-Augmented Generation (Agentic RAG), un paradigme émergent de l'IA où les grands modèles de langage (LLMs) planifient de manière autonome leurs prochaines étapes tout en récupérant des informations à partir de sources externes. Contrairement aux modèles statiques de type "récupérer puis lire", l'Agentic RAG implique des appels itératifs au LLM, entrecoupés d'appels à des outils ou fonctions et de sorties structurées. Le système évalue les résultats, affine les requêtes, invoque des outils supplémentaires si nécessaire, et poursuit ce cycle jusqu'à ce qu'une solution satisfaisante soit atteinte. ## Introduction Cette leçon couvrira : - **Comprendre l'Agentic RAG :** Découvrez ce paradigme émergent en IA où les grands modèles de langage (LLMs) planifient de manière autonome leurs prochaines étapes tout en récupérant des informations à partir de sources de données externes. - **Approche itérative Maker-Checker :** Apprenez à comprendre la boucle d'appels itératifs au LLM, entrecoupés d'appels à des outils ou fonctions et de sorties structurées, conçue pour améliorer la précision et gérer les requêtes mal formées. - **Explorer des applications pratiques :** Identifiez les scénarios où l'Agentic RAG excelle, comme dans les environnements où la précision est primordiale, les interactions complexes avec des bases de données, et les flux de travail prolongés. ## Objectifs d'apprentissage Après avoir complété cette leçon, vous serez capable de : - **Comprendre l'Agentic RAG :** Découvrir ce paradigme émergent en IA où les grands modèles de langage (LLMs) planifient de manière autonome leurs prochaines étapes tout en récupérant des informations à partir de sources de données externes. - **Approche itérative Maker-Checker :** Saisir le concept d'une boucle d'appels itératifs au LLM, entrecoupés d'appels à des outils ou fonctions et de sorties structurées, conçue pour améliorer la précision et gérer les requêtes mal formées. - **Maîtriser le processus de raisonnement :** Comprendre la capacité du système à prendre en charge son propre processus de raisonnement, en décidant comment aborder les problèmes sans dépendre de chemins pré-définis. - **Flux de travail :** Comprendre comment un modèle agentique décide de manière autonome de récupérer des rapports sur les tendances du marché, d'identifier des données sur les concurrents, de corréler des métriques de ventes internes, de synthétiser les résultats et d'évaluer la stratégie. - **Boucles itératives, intégration d'outils et mémoire :** Apprenez comment le système s'appuie sur un modèle d'interaction en boucle, en maintenant un état et une mémoire à travers les étapes pour éviter les boucles répétitives et prendre des décisions éclairées. - **Gérer les échecs et l'auto-correction :** Explorez les mécanismes robustes d'auto-correction du système, incluant des itérations, des réinterrogations, l'utilisation d'outils de diagnostic et le recours à une supervision humaine. - **Limites de l'autonomie :** Comprendre les limitations de l'Agentic RAG, en se concentrant sur l'autonomie spécifique au domaine, la dépendance à l'infrastructure et le respect des garde-fous. - **Cas d'usage pratiques et valeur ajoutée :** Identifiez les scénarios où l'Agentic RAG excelle, comme dans les environnements où la précision est primordiale, les interactions complexes avec des bases de données, et les flux de travail prolongés. - **Gouvernance, transparence et confiance :** Apprenez l'importance de la gouvernance et de la transparence, y compris le raisonnement explicable, le contrôle des biais et la supervision humaine. ## Qu'est-ce que l'Agentic RAG ? L'Agentic Retrieval-Augmented Generation (Agentic RAG) est un paradigme émergent en IA où les grands modèles de langage (LLMs) planifient de manière autonome leurs prochaines étapes tout en récupérant des informations à partir de sources externes. Contrairement aux modèles statiques de type "récupérer puis lire", l'Agentic RAG implique des appels itératifs au LLM, entrecoupés d'appels à des outils ou fonctions et de sorties structurées. Le système évalue les résultats, affine les requêtes, invoque des outils supplémentaires si nécessaire, et poursuit ce cycle jusqu'à ce qu'une solution satisfaisante soit atteinte. Ce style itératif "maker-checker" améliore la précision, gère les requêtes mal formées et garantit des résultats de haute qualité. Le système prend activement en charge son processus de raisonnement, réécrit les requêtes échouées, choisit différentes méthodes de récupération et intègre plusieurs outils—tels que la recherche vectorielle dans Azure AI Search, les bases de données SQL ou des API personnalisées—avant de finaliser sa réponse. La qualité distinctive d'un système agentique est sa capacité à posséder son processus de raisonnement. Les implémentations traditionnelles de RAG s'appuient sur des chemins pré-définis, mais un système agentique détermine de manière autonome la séquence des étapes en fonction de la qualité des informations qu'il trouve. ## Définir l'Agentic Retrieval-Augmented Generation (Agentic RAG) L'Agentic Retrieval-Augmented Generation (Agentic RAG) est un paradigme émergent dans le développement de l'IA où les LLMs non seulement récupèrent des informations à partir de sources de données externes, mais planifient également leurs prochaines étapes de manière autonome. Contrairement aux modèles statiques de type "récupérer puis lire" ou aux séquences de prompts soigneusement scriptées, l'Agentic RAG repose sur une boucle d'appels itératifs au LLM, entrecoupés d'appels à des outils ou fonctions et de sorties structurées. À chaque étape, le système évalue les résultats obtenus, décide s'il doit affiner ses requêtes, invoque des outils supplémentaires si nécessaire, et poursuit ce cycle jusqu'à ce qu'une solution satisfaisante soit atteinte. Ce style itératif "maker-checker" est conçu pour améliorer la précision, gérer les requêtes mal formées vers des bases de données structurées (par exemple, NL2SQL) et garantir des résultats équilibrés et de haute qualité. Plutôt que de se reposer uniquement sur des chaînes de prompts soigneusement conçues, le système prend activement en charge son processus de raisonnement. Il peut réécrire des requêtes échouées, choisir différentes méthodes de récupération et intégrer plusieurs outils—tels que la recherche vectorielle dans Azure AI Search, les bases de données SQL ou des API personnalisées—avant de finaliser sa réponse. Cela élimine le besoin de cadres d'orchestration excessivement complexes. À la place, une boucle relativement simple de "Appel LLM → Utilisation d'outil → Appel LLM → …" peut produire des résultats sophistiqués et bien fondés. ![Agentic RAG Core Loop](../../../translated_images/agentic-rag-core-loop.2224925a913fb3439f518bda61a40096ddf6aa432a11c9b5bba8d0d625e47b79.fr.png?WT.mc_id=academic-105485-koreyst) ## Maîtriser le processus de raisonnement La qualité distinctive qui rend un système "agentique" est sa capacité à maîtriser son processus de raisonnement. Les implémentations traditionnelles de RAG dépendent souvent des humains pour pré-définir un chemin pour le modèle : une chaîne de réflexion qui décrit quoi récupérer et quand. Mais lorsqu'un système est véritablement agentique, il décide en interne de la manière d'aborder le problème. Il ne fait pas qu'exécuter un script ; il détermine de manière autonome la séquence des étapes en fonction de la qualité des informations qu'il trouve. Par exemple, s'il est demandé de créer une stratégie de lancement de produit, il ne se repose pas uniquement sur un prompt qui décrit tout le flux de travail de recherche et de prise de décision. À la place, le modèle agentique décide indépendamment de : 1. Récupérer les rapports de tendances actuelles du marché à l'aide de Bing Web Grounding. 2. Identifier les données pertinentes sur les concurrents en utilisant Azure AI Search. 3. Corréler les métriques historiques de ventes internes en utilisant Azure SQL Database. 4. Synthétiser les résultats en une stratégie cohérente orchestrée via Azure OpenAI Service. 5. Évaluer la stratégie pour détecter des lacunes ou incohérences, initiant une nouvelle ronde de récupération si nécessaire. Toutes ces étapes—affiner les requêtes, choisir les sources, itérer jusqu'à être "satisfait" de la réponse—sont décidées par le modèle, et non pré-scriptées par un humain. ``` *Note : La traduction est partielle en raison de la longueur du contenu. Si vous souhaitez continuer, veuillez me le faire savoir !* **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatique basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de recourir à une traduction professionnelle humaine. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/05-agentic-rag/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/05-agentic-rag/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 9314 }
# Construire des Agents IA Fiables ## Introduction Cette leçon couvrira : - Comment construire et déployer des Agents IA sûrs et efficaces. - Les considérations importantes en matière de sécurité lors du développement d'Agents IA. - Comment préserver la confidentialité des données et des utilisateurs lors du développement d'Agents IA. ## Objectifs d'Apprentissage Après avoir terminé cette leçon, vous saurez comment : - Identifier et atténuer les risques lors de la création d'Agents IA. - Mettre en œuvre des mesures de sécurité pour garantir que les données et les accès soient correctement gérés. - Créer des Agents IA qui respectent la confidentialité des données et offrent une expérience utilisateur de qualité. ## Sécurité Commençons par examiner la création d'applications agentiques sûres. La sécurité signifie que l'agent IA fonctionne comme prévu. En tant que concepteurs d'applications agentiques, nous disposons de méthodes et d'outils pour maximiser la sécurité : ### Construire un Système de Méta-Prompting Si vous avez déjà conçu une application IA utilisant des modèles de langage de grande taille (LLMs), vous savez à quel point il est crucial de concevoir un prompt ou message système robuste. Ces prompts établissent les règles, instructions et lignes directrices pour la manière dont le LLM interagit avec l'utilisateur et les données. Pour les Agents IA, le prompt système est encore plus important, car ces agents auront besoin d'instructions très spécifiques pour accomplir les tâches que nous leur avons assignées. Pour créer des prompts systèmes évolutifs, nous pouvons utiliser un système de méta-prompting pour concevoir un ou plusieurs agents dans notre application : ![Construire un Système de Méta-Prompting](../../../translated_images/building-a-metaprompting-system.aa7d6de2100b0ef48c3e1926dab6903026b22fc9d27fc4327162fbbb9caf960f.fr.png) #### Étape 1 : Créer un Méta-Prompt ou Prompt Modèle Le méta-prompt sera utilisé par un LLM pour générer les prompts systèmes des agents que nous créons. Nous le concevons comme un modèle afin de pouvoir créer efficacement plusieurs agents si nécessaire. Voici un exemple de méta-prompt que nous donnerions au LLM : ```plaintext You are an expert at creating AI agent assitants. You will be provided a company name, role, responsibilites and other information that you will use to provide a system prompt for. To create the system prompt, be descriptive as possible and provide a structure that a system using an LLM can better understand the role and responsibilites of the AI assistant. ``` #### Étape 2 : Créer un Prompt de Base L'étape suivante consiste à créer un prompt de base pour décrire l'Agent IA. Vous devez inclure le rôle de l'agent, les tâches qu'il accomplira, ainsi que toute autre responsabilité qui lui incombe. Voici un exemple : ```plaintext You are a travel agent for Contoso Travel with that is great at booking flights for customers. To help customers you can perform the following tasks: lookup available flights, book flights, ask for preferences in seating and times for flights, cancel any previously booked flights and alert customers on any delays or cancellations of flights. ``` #### Étape 3 : Fournir le Prompt de Base au LLM Nous pouvons maintenant optimiser ce prompt en utilisant le méta-prompt comme prompt système et notre prompt de base. Cela produira un prompt mieux conçu pour guider nos Agents IA : ```markdown **Company Name:** Contoso Travel **Role:** Travel Agent Assistant **Objective:** You are an AI-powered travel agent assistant for Contoso Travel, specializing in booking flights and providing exceptional customer service. Your main goal is to assist customers in finding, booking, and managing their flights, all while ensuring that their preferences and needs are met efficiently. **Key Responsibilities:** 1. **Flight Lookup:** - Assist customers in searching for available flights based on their specified destination, dates, and any other relevant preferences. - Provide a list of options, including flight times, airlines, layovers, and pricing. 2. **Flight Booking:** - Facilitate the booking of flights for customers, ensuring that all details are correctly entered into the system. - Confirm bookings and provide customers with their itinerary, including confirmation numbers and any other pertinent information. 3. **Customer Preference Inquiry:** - Actively ask customers for their preferences regarding seating (e.g., aisle, window, extra legroom) and preferred times for flights (e.g., morning, afternoon, evening). - Record these preferences for future reference and tailor suggestions accordingly. 4. **Flight Cancellation:** - Assist customers in canceling previously booked flights if needed, following company policies and procedures. - Notify customers of any necessary refunds or additional steps that may be required for cancellations. 5. **Flight Monitoring:** - Monitor the status of booked flights and alert customers in real-time about any delays, cancellations, or changes to their flight schedule. - Provide updates through preferred communication channels (e.g., email, SMS) as needed. **Tone and Style:** - Maintain a friendly, professional, and approachable demeanor in all interactions with customers. - Ensure that all communication is clear, informative, and tailored to the customer's specific needs and inquiries. **User Interaction Instructions:** - Respond to customer queries promptly and accurately. - Use a conversational style while ensuring professionalism. - Prioritize customer satisfaction by being attentive, empathetic, and proactive in all assistance provided. **Additional Notes:** - Stay updated on any changes to airline policies, travel restrictions, and other relevant information that could impact flight bookings and customer experience. - Use clear and concise language to explain options and processes, avoiding jargon where possible for better customer understanding. This AI assistant is designed to streamline the flight booking process for customers of Contoso Travel, ensuring that all their travel needs are met efficiently and effectively. ``` #### Étape 4 : Itérer et Améliorer L'avantage de ce système de méta-prompting est de faciliter la création de prompts pour plusieurs agents ainsi que d'améliorer vos prompts au fil du temps. Il est rare qu'un prompt fonctionne parfaitement dès la première tentative pour répondre à tous vos besoins. Pouvoir effectuer de petits ajustements et améliorations en modifiant le prompt de base et en le passant par le système vous permettra de comparer et d'évaluer les résultats. ## Comprendre les Menaces Pour concevoir des agents IA fiables, il est essentiel de comprendre et d'atténuer les risques et menaces auxquels votre agent IA peut être confronté. Examinons certaines des différentes menaces pour les agents IA et comment vous pouvez mieux les anticiper et vous y préparer. ![Comprendre les Menaces](../../../translated_images/understanding-threats.f8fbe6fe11e025b3085fc91e82d975937ad1d672260a2aeed40458aa41798d0e.fr.png) ### Tâches et Instructions **Description :** Les attaquants tentent de modifier les instructions ou les objectifs de l'agent IA en manipulant les prompts ou les entrées. **Atténuation :** Effectuez des vérifications de validation et appliquez des filtres d'entrée pour détecter les prompts potentiellement dangereux avant qu'ils ne soient traités par l'Agent IA. Comme ces attaques nécessitent généralement des interactions fréquentes avec l'Agent, limiter le nombre de tours dans une conversation est une autre manière de prévenir ces attaques. ### Accès aux Systèmes Critiques **Description :** Si un agent IA a accès à des systèmes et services contenant des données sensibles, des attaquants peuvent compromettre la communication entre l'agent et ces services. Cela peut inclure des attaques directes ou des tentatives indirectes pour obtenir des informations sur ces systèmes via l'agent. **Atténuation :** Les agents IA ne devraient avoir accès aux systèmes que sur une base strictement nécessaire pour éviter ce type d'attaques. La communication entre l'agent et les systèmes doit également être sécurisée. La mise en œuvre de mécanismes d'authentification et de contrôle d'accès est une autre méthode pour protéger ces informations. ### Surcharge des Ressources et Services **Description :** Les agents IA peuvent accéder à divers outils et services pour accomplir leurs tâches. Les attaquants peuvent exploiter cette capacité pour envoyer un grand volume de requêtes via l'Agent IA, ce qui peut entraîner des pannes de système ou des coûts élevés. **Atténuation :** Mettez en place des politiques limitant le nombre de requêtes qu'un agent IA peut envoyer à un service. Limiter le nombre de tours de conversation et de requêtes adressées à votre agent IA est une autre méthode pour prévenir ce type d'attaques. ### Empoisonnement de la Base de Connaissances **Description :** Ce type d'attaque ne cible pas directement l'agent IA mais vise la base de connaissances et d'autres services utilisés par l'agent IA. Cela peut inclure la corruption des données ou informations que l'agent IA utilise pour accomplir ses tâches, entraînant des réponses biaisées ou non souhaitées pour l'utilisateur. **Atténuation :** Effectuez des vérifications régulières des données utilisées par l'agent IA dans ses flux de travail. Assurez-vous que l'accès à ces données est sécurisé et que seules des personnes de confiance peuvent les modifier pour éviter ce type d'attaque. ### Erreurs en Cascade **Description :** Les agents IA accèdent à divers outils et services pour accomplir leurs tâches. Les erreurs causées par des attaquants peuvent entraîner des défaillances dans d'autres systèmes auxquels l'agent IA est connecté, rendant l'attaque plus étendue et plus difficile à diagnostiquer. **Atténuation :** Une méthode pour éviter cela est de faire fonctionner l'Agent IA dans un environnement limité, tel que l'exécution des tâches dans un conteneur Docker, pour prévenir les attaques directes sur le système. La création de mécanismes de secours et de logique de reprise lorsque certains systèmes renvoient une erreur est une autre façon d'éviter des défaillances plus importantes. ## L'Humain dans la Boucle Une autre méthode efficace pour construire des systèmes d'Agents IA fiables est d'intégrer un humain dans la boucle. Cela crée un flux où les utilisateurs peuvent fournir des retours aux Agents pendant leur exécution. Les utilisateurs agissent essentiellement comme un agent dans un système multi-agents en approuvant ou en interrompant les processus en cours. ![Humain dans la Boucle](../../../translated_images/human-in-the-loop.e9edbe8f6d42041b4213421410823250aa750fe8bdba5601d69ed46f3ff6489d.fr.png) Voici un extrait de code utilisant AutoGen pour montrer comment ce concept est mis en œuvre : ```python # Create the agents. model_client = OpenAIChatCompletionClient(model="gpt-4o-mini") assistant = AssistantAgent("assistant", model_client=model_client) user_proxy = UserProxyAgent("user_proxy", input_func=input) # Use input() to get user input from console. # Create the termination condition which will end the conversation when the user says "APPROVE". termination = TextMentionTermination("APPROVE") # Create the team. team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination) # Run the conversation and stream to the console. stream = team.run_stream(task="Write a 4-line poem about the ocean.") # Use asyncio.run(...) when running in a script. await Console(stream) ``` ``` **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatisés basés sur l'intelligence artificielle. Bien que nous fassions de notre mieux pour garantir l'exactitude, veuillez noter que les traductions automatiques peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de recourir à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/06-building-trustworthy-agents/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/06-building-trustworthy-agents/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 12544 }
# Conception de la Planification ## Introduction Cette leçon couvrira : * Définir un objectif global clair et diviser une tâche complexe en tâches gérables. * Exploiter des sorties structurées pour des réponses plus fiables et lisibles par machine. * Appliquer une approche orientée événements pour gérer des tâches dynamiques et des entrées inattendues. ## Objectifs d'Apprentissage Après avoir terminé cette leçon, vous comprendrez : * Comment identifier et définir un objectif global pour un agent IA, en veillant à ce qu'il sache précisément ce qu'il doit accomplir. * Comment décomposer une tâche complexe en sous-tâches gérables et les organiser dans une séquence logique. * Comment équiper les agents des bons outils (par exemple, outils de recherche ou d'analyse de données), décider quand et comment les utiliser, et gérer les situations imprévues. * Comment évaluer les résultats des sous-tâches, mesurer les performances et itérer sur les actions pour améliorer le résultat final. ## Définir l'Objectif Global et Décomposer une Tâche ![Définir les Objectifs et les Tâches](../../../translated_images/defining-goals-tasks.dcc1181bbdb194704ae0fb3363371562949e8b03fd2fadc256218aaadf84a9f4.fr.png) La plupart des tâches du monde réel sont trop complexes pour être abordées en une seule étape. Un agent IA a besoin d'un objectif concis pour guider sa planification et ses actions. Par exemple, considérez l'objectif suivant : "Générer un itinéraire de voyage de 3 jours." Bien que cet objectif soit simple à énoncer, il nécessite encore d'être précisé. Plus l'objectif est clair, mieux l'agent (et les collaborateurs humains, le cas échéant) pourra se concentrer sur l'obtention du bon résultat, comme créer un itinéraire complet avec des options de vol, des recommandations d'hôtels et des suggestions d'activités. ### Décomposition des Tâches Les tâches volumineuses ou complexes deviennent plus faciles à gérer lorsqu'elles sont divisées en sous-tâches orientées vers des objectifs spécifiques. Pour l'exemple de l'itinéraire de voyage, vous pourriez décomposer l'objectif en : * Réservation de Vols * Réservation d'Hôtels * Location de Voiture * Personnalisation Chaque sous-tâche peut ensuite être traitée par des agents ou des processus dédiés. Un agent pourrait se spécialiser dans la recherche des meilleures offres de vols, un autre dans les réservations d'hôtels, etc. Un agent coordinateur ou "en aval" peut ensuite compiler ces résultats en un itinéraire cohérent pour l'utilisateur final. Cette approche modulaire permet également des améliorations progressives. Par exemple, vous pourriez ajouter des agents spécialisés pour les recommandations culinaires ou les suggestions d'activités locales, et affiner l'itinéraire au fil du temps. ### Sortie Structurée Les modèles de langage avancés (LLMs) peuvent générer des sorties structurées (par exemple, JSON) qui sont plus faciles à analyser et à traiter par des agents ou services en aval. Cela est particulièrement utile dans un contexte multi-agent, où ces tâches peuvent être exécutées après réception de la sortie de planification. Consultez ce [blogpost](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/cookbook/structured-output-agent.html) pour un aperçu rapide. Voici un exemple de snippet Python qui illustre un agent de planification simple décomposant un objectif en sous-tâches et générant un plan structuré : ### Agent de Planification avec Orchestration Multi-Agent Dans cet exemple, un agent routeur sémantique reçoit une demande utilisateur (par exemple, "J'ai besoin d'un plan d'hôtel pour mon voyage."). Le planificateur : * Reçoit le Plan d'Hôtel : Le planificateur prend le message de l'utilisateur et, sur la base d'une invite système (y compris les détails des agents disponibles), génère un plan de voyage structuré. * Liste les Agents et Leurs Outils : Le registre des agents contient une liste d'agents (par exemple, pour les vols, hôtels, locations de voitures et activités) ainsi que les fonctions ou outils qu'ils proposent. * Route le Plan vers les Agents Concernés : En fonction du nombre de sous-tâches, le planificateur envoie soit directement le message à un agent dédié (pour des scénarios de tâche unique), soit coordonne via un gestionnaire de discussion de groupe pour une collaboration multi-agent. * Résume le Résultat : Enfin, le planificateur résume le plan généré pour plus de clarté. Voici un exemple de code Python illustrant ces étapes : ```python from pydantic import BaseModel from enum import Enum from typing import List, Optional, Union class AgentEnum(str, Enum): FlightBooking = "flight_booking" HotelBooking = "hotel_booking" CarRental = "car_rental" ActivitiesBooking = "activities_booking" DestinationInfo = "destination_info" DefaultAgent = "default_agent" GroupChatManager = "group_chat_manager" # Travel SubTask Model class TravelSubTask(BaseModel): task_details: str assigned_agent: AgentEnum # we want to assign the task to the agent class TravelPlan(BaseModel): main_task: str subtasks: List[TravelSubTask] is_greeting: bool import json import os from typing import Optional from autogen_core.models import UserMessage, SystemMessage, AssistantMessage from autogen_ext.models.openai import AzureOpenAIChatCompletionClient # Create the client with type-checked environment variables client = AzureOpenAIChatCompletionClient( azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"), model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"), api_version=os.getenv("AZURE_OPENAI_API_VERSION"), azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), ) from pprint import pprint # Define the user message messages = [ SystemMessage(content="""You are an planner agent. Your job is to decide which agents to run based on the user's request. Below are the available agents specialised in different tasks: - FlightBooking: For booking flights and providing flight information - HotelBooking: For booking hotels and providing hotel information - CarRental: For booking cars and providing car rental information - ActivitiesBooking: For booking activities and providing activity information - DestinationInfo: For providing information about destinations - DefaultAgent: For handling general requests""", source="system"), UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"), ] response = await client.create(messages=messages, extra_create_args={"response_format": TravelPlan}) # Ensure the response content is a valid JSON string before loading it response_content: Optional[str] = response.content if isinstance(response.content, str) else None if response_content is None: raise ValueError("Response content is not a valid JSON string") # Print the response content after loading it as JSON pprint(json.loads(response_content)) ``` Voici la sortie du code ci-dessus, que vous pouvez ensuite utiliser pour router vers `assigned_agent` et résumer le plan de voyage pour l'utilisateur final : ```json { "is_greeting": "False", "main_task": "Plan a family trip from Singapore to Melbourne.", "subtasks": [ { "assigned_agent": "flight_booking", "task_details": "Book round-trip flights from Singapore to Melbourne." }, { "assigned_agent": "hotel_booking", "task_details": "Find family-friendly hotels in Melbourne." }, { "assigned_agent": "car_rental", "task_details": "Arrange a car rental suitable for a family of four in Melbourne." }, { "assigned_agent": "activities_booking", "task_details": "List family-friendly activities in Melbourne." }, { "assigned_agent": "destination_info", "task_details": "Provide information about Melbourne as a travel destination." } ] } ``` Un exemple de notebook contenant cet extrait de code est disponible [ici](../../../07-planning-design/code_samples/07-autogen.ipynb). ### Planification Itérative Certaines tâches nécessitent des allers-retours ou une re-planification, où le résultat d'une sous-tâche influence la suivante. Par exemple, si l'agent découvre un format de données inattendu lors de la réservation de vols, il pourrait devoir adapter sa stratégie avant de passer à la réservation d'hôtels. De plus, les retours utilisateurs (par exemple, un humain décidant de préférer un vol plus tôt) peuvent déclencher une re-planification partielle. Cette approche dynamique et itérative garantit que la solution finale s'aligne sur les contraintes du monde réel et les préférences évolutives des utilisateurs. Exemple de code : ```python from autogen_core.models import UserMessage, SystemMessage, AssistantMessage #.. same as previous code and pass on the user history, current plan messages = [ SystemMessage(content="""You are a planner agent to optimize the Your job is to decide which agents to run based on the user's request. Below are the available agents specialised in different tasks: - FlightBooking: For booking flights and providing flight information - HotelBooking: For booking hotels and providing hotel information - CarRental: For booking cars and providing car rental information - ActivitiesBooking: For booking activities and providing activity information - DestinationInfo: For providing information about destinations - DefaultAgent: For handling general requests""", source="system"), UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melboune", source="user"), AssistantMessage(content=f"Previous travel plan - {TravelPlan}", source="assistant") ] # .. re-plan and send the tasks to respective agents ``` Pour une planification plus complète, consultez le [Blogpost Magnetic One](https://www.microsoft.com/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks) pour résoudre des tâches complexes. ## Résumé Dans cet article, nous avons examiné un exemple de création d'un planificateur capable de sélectionner dynamiquement les agents disponibles définis. La sortie du planificateur décompose les tâches et attribue les agents pour qu'ils soient exécutés. On suppose que les agents ont accès aux fonctions/outils nécessaires pour effectuer la tâche. En plus des agents, vous pouvez inclure d'autres modèles comme la réflexion, le résumé, ou un chat en round-robin pour personnaliser davantage. ## Ressources Supplémentaires * L'utilisation de modèles de raisonnement o1 a prouvé des avancées significatives dans la planification de tâches complexes - TODO : Partager un exemple ? * Autogen Magnetic One - Un système multi-agent généraliste pour résoudre des tâches complexes, qui a obtenu des résultats impressionnants sur plusieurs benchmarks exigeants. Référence : [autogen-magentic-one](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-magentic-one). Dans cette implémentation, l'orchestrateur crée un plan spécifique à la tâche et délègue ces tâches aux agents disponibles. En plus de la planification, l'orchestrateur utilise un mécanisme de suivi pour surveiller l'avancement des tâches et re-planifier si nécessaire. ``` **Avertissement** : Ce document a été traduit à l'aide de services de traduction basés sur l'intelligence artificielle. Bien que nous fassions de notre mieux pour garantir l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de recourir à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/07-planning-design/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/07-planning-design/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 12365 }
# Modèles de conception multi-agents Dès que vous commencez à travailler sur un projet impliquant plusieurs agents, vous devez prendre en compte le modèle de conception multi-agents. Cependant, il n'est pas toujours évident de savoir quand passer à un système multi-agents et quels en sont les avantages. ## Introduction Dans cette leçon, nous cherchons à répondre aux questions suivantes : - Quels sont les scénarios où les systèmes multi-agents sont applicables ? - Quels sont les avantages d'utiliser des multi-agents plutôt qu'un agent unique effectuant plusieurs tâches ? - Quels sont les éléments constitutifs pour implémenter le modèle de conception multi-agents ? - Comment pouvons-nous avoir une visibilité sur les interactions entre plusieurs agents ? ## Objectifs d'apprentissage Après cette leçon, vous devriez être capable de : - Identifier les scénarios où les multi-agents sont applicables. - Reconnaître les avantages d'utiliser des multi-agents par rapport à un agent unique. - Comprendre les éléments constitutifs nécessaires pour implémenter le modèle de conception multi-agents. Quelle est la vision d'ensemble ? *Les systèmes multi-agents sont un modèle de conception qui permet à plusieurs agents de collaborer pour atteindre un objectif commun.* Ce modèle est largement utilisé dans divers domaines, notamment la robotique, les systèmes autonomes et l'informatique distribuée. ## Scénarios où les systèmes multi-agents sont applicables Quels sont donc les scénarios adaptés à l'utilisation de multi-agents ? La réponse est qu'il existe de nombreux cas où l'emploi de plusieurs agents est bénéfique, notamment dans les situations suivantes : - **Charges de travail importantes** : Les charges de travail importantes peuvent être divisées en tâches plus petites et attribuées à différents agents, permettant un traitement en parallèle et une exécution plus rapide. Un exemple classique est le traitement de grandes quantités de données. - **Tâches complexes** : Les tâches complexes, comme les charges de travail importantes, peuvent être décomposées en sous-tâches plus petites et attribuées à différents agents, chacun se spécialisant dans un aspect spécifique de la tâche. Un bon exemple est celui des véhicules autonomes où différents agents gèrent la navigation, la détection des obstacles et la communication avec d'autres véhicules. - **Expertise variée** : Différents agents peuvent avoir des expertises variées, leur permettant de gérer différents aspects d'une tâche de manière plus efficace qu'un agent unique. Par exemple, dans le domaine de la santé, des agents peuvent gérer les diagnostics, les plans de traitement et la surveillance des patients. ## Avantages d'utiliser des multi-agents par rapport à un agent unique Un système à agent unique peut fonctionner correctement pour des tâches simples, mais pour des tâches plus complexes, l'utilisation de plusieurs agents offre plusieurs avantages : - **Spécialisation** : Chaque agent peut se spécialiser dans une tâche spécifique. L'absence de spécialisation dans un système à agent unique peut entraîner une confusion lorsqu'il est confronté à une tâche complexe. Par exemple, il pourrait finir par effectuer une tâche pour laquelle il n'est pas le mieux adapté. - **Évolutivité** : Il est plus facile de faire évoluer un système en ajoutant des agents supplémentaires plutôt qu'en surchargeant un agent unique. - **Tolérance aux pannes** : Si un agent tombe en panne, les autres peuvent continuer à fonctionner, assurant ainsi la fiabilité du système. Prenons un exemple : réserver un voyage pour un utilisateur. Un système à agent unique devrait gérer tous les aspects du processus de réservation, de la recherche de vols à la réservation d'hôtels et de voitures de location. Cela nécessiterait que l'agent unique dispose d'outils pour gérer toutes ces tâches, ce qui pourrait conduire à un système complexe et monolithique, difficile à maintenir et à faire évoluer. Un système multi-agents, en revanche, pourrait avoir différents agents spécialisés dans la recherche de vols, la réservation d'hôtels et la location de voitures. Cela rendrait le système plus modulaire, plus facile à maintenir et évolutif. Comparez cela à une agence de voyage gérée comme un petit commerce familial versus une agence gérée comme une franchise. Le petit commerce familial aurait un agent unique gérant tous les aspects du processus de réservation, tandis que la franchise aurait différents agents gérant différents aspects du processus. ## Éléments constitutifs pour implémenter le modèle de conception multi-agents Avant de pouvoir implémenter le modèle de conception multi-agents, vous devez comprendre les éléments constitutifs qui le composent. Prenons à nouveau l'exemple de la réservation d'un voyage pour un utilisateur. Dans ce cas, les éléments constitutifs incluraient : - **Communication entre agents** : Les agents chargés de trouver des vols, de réserver des hôtels et de louer des voitures doivent communiquer et partager des informations sur les préférences et les contraintes de l'utilisateur. Vous devez décider des protocoles et des méthodes pour cette communication. Concrètement, cela signifie que l'agent chargé de trouver des vols doit communiquer avec l'agent chargé de réserver des hôtels pour s'assurer que l'hôtel est réservé pour les mêmes dates que le vol. Cela implique de décider *quels agents partagent des informations et comment ils les partagent*. - **Mécanismes de coordination** : Les agents doivent coordonner leurs actions pour s'assurer que les préférences et les contraintes de l'utilisateur sont respectées. Par exemple, une préférence utilisateur pourrait être d'avoir un hôtel proche de l'aéroport, tandis qu'une contrainte pourrait être que les voitures de location ne sont disponibles qu'à l'aéroport. Cela signifie que vous devez décider *comment les agents coordonnent leurs actions*. - **Architecture des agents** : Les agents doivent avoir une structure interne leur permettant de prendre des décisions et d'apprendre de leurs interactions avec l'utilisateur. Par exemple, l'agent chargé de trouver des vols doit être capable de décider quels vols recommander à l'utilisateur. Cela implique de déterminer *comment les agents prennent des décisions et apprennent de leurs interactions avec l'utilisateur*. Un exemple pourrait être qu'un agent utilise un modèle d'apprentissage automatique pour recommander des vols basés sur les préférences passées de l'utilisateur. - **Visibilité des interactions multi-agents** : Vous devez avoir une visibilité sur la manière dont les agents interagissent entre eux. Cela nécessite des outils et des techniques pour suivre les activités et les interactions des agents. Cela peut inclure des outils de journalisation, de surveillance, de visualisation et des indicateurs de performance. - **Modèles multi-agents** : Il existe différents modèles pour implémenter des systèmes multi-agents, comme des architectures centralisées, décentralisées ou hybrides. Vous devez choisir le modèle qui correspond le mieux à votre cas d'utilisation. - **Humain dans la boucle** : Dans la plupart des cas, un humain interviendra dans le processus, et vous devez définir quand les agents doivent demander une intervention humaine. Cela peut inclure des demandes spécifiques, comme un utilisateur demandant un hôtel ou un vol particulier, ou des confirmations avant de finaliser une réservation. ## Visibilité des interactions multi-agents Il est crucial d'avoir une visibilité sur la manière dont les agents interagissent entre eux. Cette visibilité est essentielle pour le débogage, l'optimisation et l'efficacité globale du système. Pour cela, vous devez disposer d'outils et de techniques permettant de suivre les activités et interactions des agents. Cela peut inclure des outils de journalisation, de surveillance, de visualisation et des indicateurs de performance. Par exemple, dans le cas de la réservation d'un voyage, vous pourriez avoir un tableau de bord affichant le statut de chaque agent, les préférences et contraintes de l'utilisateur, ainsi que les interactions entre les agents. Ce tableau de bord pourrait montrer les dates de voyage de l'utilisateur, les vols recommandés par l'agent de vol, les hôtels recommandés par l'agent hôtelier et les voitures de location recommandées par l'agent de location. Cela vous offrirait une vue claire des interactions entre les agents et de la satisfaction des préférences et contraintes de l'utilisateur. Voyons ces aspects plus en détail : - **Outils de journalisation et de surveillance** : Vous souhaitez enregistrer chaque action effectuée par un agent. Une entrée de journal peut contenir des informations sur l'agent ayant effectué l'action, l'action elle-même, l'heure de l'action et son résultat. Ces informations peuvent ensuite être utilisées pour le débogage, l'optimisation, etc. - **Outils de visualisation** : Les outils de visualisation peuvent vous aider à comprendre les interactions entre les agents de manière plus intuitive. Par exemple, vous pourriez avoir un graphique montrant le flux d'informations entre les agents, ce qui pourrait vous aider à identifier les goulets d'étranglement ou inefficacités. - **Indicateurs de performance** : Les indicateurs de performance peuvent vous aider à mesurer l'efficacité du système multi-agents. Par exemple, vous pourriez suivre le temps nécessaire pour terminer une tâche, le nombre de tâches accomplies par unité de temps, ou encore la précision des recommandations faites par les agents. ## Modèles multi-agents Explorons quelques modèles concrets que nous pouvons utiliser pour créer des applications multi-agents. Voici quelques modèles intéressants à considérer : ### Discussion de groupe Ce modèle est utile lorsque vous souhaitez créer une application de discussion de groupe où plusieurs agents peuvent communiquer entre eux. Les cas d'utilisation typiques incluent la collaboration en équipe, le support client et les réseaux sociaux. Dans ce modèle, chaque agent représente un utilisateur dans la discussion de groupe, et les messages sont échangés entre les agents via un protocole de messagerie. Les agents peuvent envoyer des messages à la discussion de groupe, recevoir des messages de celle-ci et répondre à d'autres agents. Ce modèle peut être implémenté via une architecture centralisée où tous les messages transitent par un serveur central, ou via une architecture décentralisée où les messages sont échangés directement. ![Discussion de groupe](../../../translated_images/multi-agent-group-chat.82d537c5c8dc833abbd252033e60874bc9d00df7193888b3377f8426449a0b20.fr.png) ### Transmission de tâches Ce modèle est utile lorsque vous souhaitez créer une application où plusieurs agents peuvent se transmettre des tâches. Les cas d'utilisation typiques incluent le support client, la gestion des tâches et l'automatisation des flux de travail. Dans ce modèle, chaque agent représente une tâche ou une étape d'un flux de travail, et les agents peuvent transmettre des tâches à d'autres agents en fonction de règles prédéfinies. ![Transmission de tâches](../../../translated_images/multi-agent-hand-off.ed4f0a5a58614a8a3e962fc476187e630a3ba309d066e460f017b503d0b84cfc.fr.png) ### Filtrage collaboratif Ce modèle est utile lorsque vous souhaitez créer une application où plusieurs agents peuvent collaborer pour faire des recommandations aux utilisateurs. L'intérêt d'avoir plusieurs agents collaborant est que chaque agent peut avoir une expertise différente et contribuer au processus de recommandation de diverses manières. Prenons un exemple où un utilisateur souhaite une recommandation sur la meilleure action à acheter en bourse : - **Expertise sectorielle** : Un agent pourrait être expert dans un secteur spécifique. - **Analyse technique** : Un autre agent pourrait être spécialisé dans l'analyse technique. - **Analyse fondamentale** : Un autre agent encore pourrait exceller dans l'analyse fondamentale. En collaborant, ces agents peuvent fournir une recommandation plus complète à l'utilisateur. ![Recommandation](../../../translated_images/multi-agent-filtering.719217d169391ddb118bbb726b19d4d89ee139f960f8749ccb2400efb4d0ce79.fr.png) ## Scénario : Processus de remboursement Considérons un scénario où un client cherche à obtenir un remboursement pour un produit. Plusieurs agents peuvent être impliqués dans ce processus, mais distinguons les agents spécifiques à ce processus et les agents généraux pouvant être utilisés dans d'autres contextes. **Agents spécifiques au processus de remboursement** : Voici quelques agents qui pourraient être impliqués dans le processus de remboursement : - **Agent client** : Représente le client et est responsable d'initier le processus de remboursement. - **Agent vendeur** : Représente le vendeur et est chargé de traiter le remboursement. - **Agent de paiement** : Représente le processus de paiement et est responsable de rembourser le paiement du client. - **Agent de résolution** : Représente le processus de résolution et est chargé de résoudre les problèmes éventuels pendant le processus de remboursement. - **Agent de conformité** : Représente le processus de conformité et veille à ce que le processus de remboursement respecte les réglementations et politiques en vigueur. **Agents généraux** : Ces agents peuvent être utilisés dans d'autres parties de votre entreprise. - **Agent d'expédition** : Représente le processus d'expédition et est chargé de renvoyer le produit au vendeur. Cet agent peut être utilisé à la fois pour le processus de remboursement et pour l'expédition générale d'un produit après un achat, par exemple. - **Agent de retour d'expérience** : Représente le processus de collecte des retours d'expérience et est chargé de recueillir les retours du client. Ces retours peuvent être collectés à tout moment, pas seulement pendant le processus de remboursement. - **Agent d'escalade** : Représente le processus d'escalade et est chargé de transmettre les problèmes à un niveau de support supérieur. Ce type d'agent peut être utilisé dans n'importe quel processus nécessitant une escalade. - **Agent de notification** : Représente le processus de notification et est chargé d'envoyer des notifications au client à différentes étapes du processus de remboursement. - **Agent d'analyse** : Représente le processus d'analyse et est chargé d'analyser les données relatives au processus de remboursement. - **Agent d'audit** : Représente le processus d'audit et est chargé de vérifier que le processus de remboursement est correctement exécuté. - **Agent de reporting** : Représente le processus de reporting et est chargé de générer des rapports sur le processus de remboursement. - **Agent de connaissance** : Représente le processus de gestion des connaissances et est chargé de maintenir une base de connaissances sur le processus de remboursement. Cet agent peut être informé à la fois sur les remboursements et sur d'autres aspects de votre entreprise. - **Agent de sécurité** : Représente le processus de sécurité et est chargé de garantir la sécurité du processus de remboursement. - **Agent de qualité** : Représente le processus de qualité et est chargé d'assurer la qualité du processus de remboursement. Il y a beaucoup d'agents listés ci-dessus, à la fois pour le processus de remboursement spécifique et pour les agents généraux pouvant être utilisés dans d'autres parties de votre entreprise. Cela devrait vous donner une idée de la manière de décider quels agents utiliser dans votre système multi-agents. ## Exercice Quel serait un bon exercice pour cette leçon ? Concevez un système multi-agents pour un processus de support client. Identifiez les agents impliqués dans le processus, leurs rôles et responsabilités, et comment ils interagissent entre eux. Prenez en compte à la fois les agents spécifiques au processus de support client et les agents généraux pouvant être utilisés dans d'autres parties de votre entreprise. > Réfléchissez avant de lire la solution ci-dessous, vous pourriez avoir besoin de plus d'agents que vous ne le pensez. > TIP : Pensez aux différentes étapes du processus de support client et prenez également en compte les agents nécessaires à tout système. ## Solution [Solution](./solution/solution.md) ## Questions de révision Question : Quand devriez-vous envisager d'utiliser des multi-agents ? - [] A1 : Lorsque vous avez une charge de travail légère et une tâche simple. - [] A2 : Lorsque vous avez une charge de travail importante. - [] A3 : Lorsque vous avez une tâche simple. [Solution du quiz](./solution/solution-quiz.md) ## Résumé Dans cette leçon, nous avons exploré le modèle de conception multi-agents, y compris les scénarios où les multi-agents sont applicables, les avantages d'utiliser des multi-agents par rapport à un agent unique, les éléments constitutifs pour implémenter le modèle de conception multi-agents, et comment avoir une visibilité sur les interactions entre les agents. ## Ressources supplémentaires - [Autogen design patterns](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/design-patterns/intro.html) - [Agentic design patterns](https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/) ``` **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatisés basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de recourir à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/08-multi-agent/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/08-multi-agent/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 18159 }
# Métacognition chez les Agents IA ## Introduction Bienvenue dans la leçon sur la métacognition chez les agents IA ! Ce chapitre est conçu pour les débutants curieux de savoir comment les agents IA peuvent réfléchir à leurs propres processus de réflexion. À la fin de cette leçon, vous comprendrez les concepts clés et disposerez d'exemples pratiques pour appliquer la métacognition dans la conception d'agents IA. ## Objectifs d'apprentissage Après avoir terminé cette leçon, vous serez capable de : 1. Comprendre les implications des boucles de raisonnement dans les définitions d'agents. 2. Utiliser des techniques de planification et d'évaluation pour aider les agents à s'auto-corriger. 3. Créer vos propres agents capables de manipuler du code pour accomplir des tâches. ## Introduction à la métacognition La métacognition fait référence aux processus cognitifs de haut niveau qui impliquent de penser à sa propre pensée. Pour les agents IA, cela signifie être capable d'évaluer et d'ajuster leurs actions en fonction de leur conscience de soi et de leurs expériences passées. ### Qu'est-ce que la métacognition ? La métacognition, ou "penser à penser", est un processus cognitif de haut niveau qui implique la conscience de soi et l'autorégulation de ses propres processus cognitifs. Dans le domaine de l'IA, la métacognition permet aux agents d'évaluer et d'adapter leurs stratégies et actions, ce qui conduit à une amélioration des capacités de résolution de problèmes et de prise de décision. En comprenant la métacognition, vous pouvez concevoir des agents IA non seulement plus intelligents, mais aussi plus adaptables et efficaces. ### Importance de la métacognition chez les agents IA La métacognition joue un rôle crucial dans la conception des agents IA pour plusieurs raisons : ![Importance de la Métacognition](../../../translated_images/importance-of-metacognition.e351a5983bb745d60a1a60185391a39a6751d033c8c1948ceb6ad04eff7dbeac.fr.png?WT.mc_id=academic-105485-koreyst) - **Auto-réflexion** : Les agents peuvent évaluer leur propre performance et identifier les domaines à améliorer. - **Adaptabilité** : Les agents peuvent modifier leurs stratégies en fonction des expériences passées et des environnements changeants. - **Correction d'erreurs** : Les agents peuvent détecter et corriger des erreurs de manière autonome, ce qui conduit à des résultats plus précis. - **Gestion des ressources** : Les agents peuvent optimiser l'utilisation des ressources, comme le temps et la puissance de calcul, en planifiant et en évaluant leurs actions. ## Composantes d'un agent IA Avant d'aborder les processus métacognitifs, il est essentiel de comprendre les composantes de base d'un agent IA. Un agent IA se compose généralement de : - **Persona** : La personnalité et les caractéristiques de l'agent, qui définissent comment il interagit avec les utilisateurs. - **Outils** : Les capacités et fonctions que l'agent peut effectuer. - **Compétences** : Les connaissances et l'expertise que possède l'agent. Ces composantes travaillent ensemble pour créer une "unité d'expertise" capable d'effectuer des tâches spécifiques. **Exemple** : Considérez un agent de voyage, un service qui non seulement planifie vos vacances mais ajuste également son parcours en fonction des données en temps réel et des expériences passées des clients. ### Exemple : Métacognition dans un service d'agent de voyage Imaginez que vous concevez un service d'agent de voyage alimenté par l'IA. Cet agent, appelé "Agent de Voyage", aide les utilisateurs à planifier leurs vacances. Pour intégrer la métacognition, l'Agent de Voyage doit évaluer et ajuster ses actions en fonction de sa conscience de soi et de ses expériences passées. #### Tâche actuelle La tâche actuelle est d'aider un utilisateur à planifier un voyage à Paris. #### Étapes pour accomplir la tâche 1. **Collecter les préférences de l'utilisateur** : Demander à l'utilisateur ses dates de voyage, son budget, ses centres d'intérêt (par exemple, musées, cuisine, shopping) et toute exigence spécifique. 2. **Récupérer des informations** : Rechercher des options de vol, des hébergements, des attractions et des restaurants correspondant aux préférences de l'utilisateur. 3. **Générer des recommandations** : Fournir un itinéraire personnalisé avec des détails sur les vols, les réservations d'hôtel et les activités suggérées. 4. **Ajuster en fonction des retours** : Demander à l'utilisateur des retours sur les recommandations et apporter les ajustements nécessaires. #### Ressources nécessaires - Accès aux bases de données de réservation de vols et d'hôtels. - Informations sur les attractions et restaurants parisiens. - Données de retour des utilisateurs des interactions précédentes. #### Expérience et auto-réflexion L'Agent de Voyage utilise la métacognition pour évaluer ses performances et apprendre de ses expériences passées. Par exemple : 1. **Analyse des retours des utilisateurs** : L'Agent de Voyage examine les retours des utilisateurs pour déterminer quelles recommandations ont été bien accueillies et lesquelles ne l'ont pas été. Il ajuste ses suggestions futures en conséquence. 2. **Adaptabilité** : Si un utilisateur a précédemment mentionné qu'il n'aime pas les endroits bondés, l'Agent de Voyage évitera de recommander des lieux touristiques populaires aux heures de pointe à l'avenir. 3. **Correction d'erreurs** : Si l'Agent de Voyage a commis une erreur dans une réservation passée, comme suggérer un hôtel complet, il apprend à vérifier plus rigoureusement la disponibilité avant de faire des recommandations. #### Exemple pratique pour les développeurs Voici un exemple simplifié de code que pourrait utiliser l'Agent de Voyage pour intégrer la métacognition : ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): # Search for flights, hotels, and attractions based on preferences flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) # Analyze feedback and adjust future recommendations self.user_preferences = adjust_preferences(self.user_preferences, feedback) # Example usage travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} travel_agent.adjust_based_on_feedback(feedback) ``` #### Pourquoi la métacognition est importante - **Auto-réflexion** : Les agents peuvent analyser leur performance et identifier les domaines à améliorer. - **Adaptabilité** : Les agents peuvent modifier leurs stratégies en fonction des retours et des conditions changeantes. - **Correction d'erreurs** : Les agents peuvent détecter et corriger les erreurs de manière autonome. - **Gestion des ressources** : Les agents peuvent optimiser l'utilisation des ressources, comme le temps et la puissance de calcul. En intégrant la métacognition, l'Agent de Voyage peut fournir des recommandations de voyage plus personnalisées et précises, améliorant ainsi l'expérience utilisateur globale. --- ## 2. Planification chez les agents La planification est une composante essentielle du comportement des agents IA. Elle consiste à définir les étapes nécessaires pour atteindre un objectif, en tenant compte de l'état actuel, des ressources disponibles et des obstacles possibles. ### Éléments de la planification - **Tâche actuelle** : Définir clairement la tâche. - **Étapes pour accomplir la tâche** : Décomposer la tâche en étapes gérables. - **Ressources nécessaires** : Identifier les ressources nécessaires. - **Expérience** : Utiliser les expériences passées pour informer la planification. **Exemple** : Voici les étapes que l'Agent de Voyage doit suivre pour aider un utilisateur à planifier son voyage efficacement : ### Étapes pour l'Agent de Voyage 1. **Collecter les préférences de l'utilisateur** - Demander à l'utilisateur des détails sur ses dates de voyage, son budget, ses centres d'intérêt et toute exigence spécifique. - Exemples : "Quand prévoyez-vous de voyager ?" "Quelle est votre fourchette de budget ?" "Quelles activités aimez-vous pendant vos vacances ?" 2. **Récupérer des informations** - Rechercher des options de voyage pertinentes en fonction des préférences de l'utilisateur. - **Vols** : Rechercher des vols disponibles dans le budget et les dates de voyage préférés de l'utilisateur. - **Hébergements** : Trouver des hôtels ou des locations correspondant aux préférences de l'utilisateur en matière d'emplacement, de prix et de commodités. - **Attractions et restaurants** : Identifier des attractions populaires, des activités et des options de restauration alignées sur les centres d'intérêt de l'utilisateur. 3. **Générer des recommandations** - Compiler les informations récupérées dans un itinéraire personnalisé. - Fournir des détails tels que les options de vol, les réservations d'hôtel et les activités suggérées, en veillant à adapter les recommandations aux préférences de l'utilisateur. 4. **Présenter l'itinéraire à l'utilisateur** - Partager l'itinéraire proposé avec l'utilisateur pour qu'il l'examine. - Exemple : "Voici un itinéraire suggéré pour votre voyage à Paris. Il inclut les détails des vols, des réservations d'hôtel et une liste d'activités et de restaurants recommandés. Dites-moi ce que vous en pensez !" 5. **Collecter des retours** - Demander à l'utilisateur des retours sur l'itinéraire proposé. - Exemples : "Aimez-vous les options de vol ?" "L'hôtel convient-il à vos besoins ?" "Y a-t-il des activités que vous souhaitez ajouter ou supprimer ?" 6. **Ajuster en fonction des retours** - Modifier l'itinéraire en fonction des retours de l'utilisateur. - Apporter les changements nécessaires aux recommandations de vol, d'hébergement et d'activités pour mieux répondre aux préférences de l'utilisateur. 7. **Confirmation finale** - Présenter l'itinéraire mis à jour à l'utilisateur pour confirmation finale. - Exemple : "J'ai apporté les ajustements en fonction de vos retours. Voici l'itinéraire mis à jour. Tout vous convient-il ?" 8. **Réserver et confirmer les réservations** - Une fois l'itinéraire approuvé par l'utilisateur, procéder à la réservation des vols, des hébergements et des activités pré-planifiées. - Envoyer les détails de confirmation à l'utilisateur. 9. **Fournir un support continu** - Rester disponible pour aider l'utilisateur avec des modifications ou des demandes supplémentaires avant et pendant son voyage. - Exemple : "Si vous avez besoin d'une assistance supplémentaire pendant votre voyage, n'hésitez pas à me contacter à tout moment !" ### Exemple d'interaction ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) self.user_preferences = adjust_preferences(self.user_preferences, feedback) # Example usage within a booing request travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} travel_agent.adjust_based_on_feedback(feedback) ``` ``` ```markdown L'agent de voyage formule de nouvelles requêtes de recherche en fonction des retours des utilisateurs. - Exemple : ```python if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] ``` - **Outil** : L'agent de voyage utilise des algorithmes pour classer et filtrer les nouveaux résultats de recherche, en mettant l'accent sur la pertinence basée sur les retours des utilisateurs. - Exemple : ```python new_attractions = search_attractions(preferences) new_itinerary = create_itinerary(flights, hotels, new_attractions) print("Updated Itinerary:", new_itinerary) ``` - **Évaluation** : L'agent de voyage évalue en continu la pertinence et l'exactitude de ses recommandations en analysant les retours des utilisateurs et en effectuant les ajustements nécessaires. - Exemple : ```python def adjust_preferences(preferences, feedback): if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] return preferences preferences = adjust_preferences(preferences, feedback) ``` #### Exemple pratique Voici un exemple simplifié de code Python intégrant l'approche Corrective RAG dans un agent de voyage : ```python class Travel_Agent: def __init__(self): self.user_preferences = {} self.experience_data = [] def gather_preferences(self, preferences): self.user_preferences = preferences def retrieve_information(self): flights = search_flights(self.user_preferences) hotels = search_hotels(self.user_preferences) attractions = search_attractions(self.user_preferences) return flights, hotels, attractions def generate_recommendations(self): flights, hotels, attractions = self.retrieve_information() itinerary = create_itinerary(flights, hotels, attractions) return itinerary def adjust_based_on_feedback(self, feedback): self.experience_data.append(feedback) self.user_preferences = adjust_preferences(self.user_preferences, feedback) new_itinerary = self.generate_recommendations() return new_itinerary # Example usage travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = travel_agent.generate_recommendations() print("Suggested Itinerary:", itinerary) feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} new_itinerary = travel_agent.adjust_based_on_feedback(feedback) print("Updated Itinerary:", new_itinerary) ``` ### Chargement de contexte préventif Le chargement de contexte préventif consiste à charger des informations contextuelles ou de fond pertinentes dans le modèle avant le traitement d'une requête. Cela permet au modèle d'accéder à ces informations dès le départ, ce qui peut l'aider à générer des réponses plus éclairées sans avoir besoin de récupérer des données supplémentaires pendant le processus. Voici un exemple simplifié de ce à quoi pourrait ressembler un chargement de contexte préventif pour une application d'agent de voyage en Python : ```python class TravelAgent: def __init__(self): # Pre-load popular destinations and their information self.context = { "Paris": {"country": "France", "currency": "Euro", "language": "French", "attractions": ["Eiffel Tower", "Louvre Museum"]}, "Tokyo": {"country": "Japan", "currency": "Yen", "language": "Japanese", "attractions": ["Tokyo Tower", "Shibuya Crossing"]}, "New York": {"country": "USA", "currency": "Dollar", "language": "English", "attractions": ["Statue of Liberty", "Times Square"]}, "Sydney": {"country": "Australia", "currency": "Dollar", "language": "English", "attractions": ["Sydney Opera House", "Bondi Beach"]} } def get_destination_info(self, destination): # Fetch destination information from pre-loaded context info = self.context.get(destination) if info: return f"{destination}:\nCountry: {info['country']}\nCurrency: {info['currency']}\nLanguage: {info['language']}\nAttractions: {', '.join(info['attractions'])}" else: return f"Sorry, we don't have information on {destination}." # Example usage travel_agent = TravelAgent() print(travel_agent.get_destination_info("Paris")) print(travel_agent.get_destination_info("Tokyo")) ``` #### Explication 1. **Initialisation (`__init__` method)**: The `TravelAgent` class pre-loads a dictionary containing information about popular destinations such as Paris, Tokyo, New York, and Sydney. This dictionary includes details like the country, currency, language, and major attractions for each destination. 2. **Retrieving Information (`get_destination_info` method)**: When a user queries about a specific destination, the `get_destination_info` méthode)** : Cette méthode récupère les informations pertinentes à partir du dictionnaire de contexte préchargé. En préchargeant le contexte, l'application d'agent de voyage peut répondre rapidement aux requêtes des utilisateurs sans avoir à récupérer ces informations à partir d'une source externe en temps réel. Cela rend l'application plus efficace et réactive. ### Amorçage d'un plan avec un objectif avant itération L'amorçage d'un plan avec un objectif consiste à commencer avec un objectif clair ou un résultat cible en tête. En définissant cet objectif dès le départ, le modèle peut l'utiliser comme principe directeur tout au long du processus itératif. Cela permet de s'assurer que chaque itération se rapproche de l'atteinte du résultat souhaité, rendant le processus plus efficace et ciblé. Voici un exemple de la façon dont vous pourriez amorcer un plan de voyage avec un objectif avant d'itérer pour un agent de voyage en Python : ### Scénario Un agent de voyage souhaite planifier des vacances personnalisées pour un client. L'objectif est de créer un itinéraire de voyage qui maximise la satisfaction du client en fonction de ses préférences et de son budget. ### Étapes 1. Définir les préférences et le budget du client. 2. Amorcer le plan initial en fonction de ces préférences. 3. Itérer pour affiner le plan, en optimisant la satisfaction du client. #### Code Python ```python class TravelAgent: def __init__(self, destinations): self.destinations = destinations def bootstrap_plan(self, preferences, budget): plan = [] total_cost = 0 for destination in self.destinations: if total_cost + destination['cost'] <= budget and self.match_preferences(destination, preferences): plan.append(destination) total_cost += destination['cost'] return plan def match_preferences(self, destination, preferences): for key, value in preferences.items(): if destination.get(key) != value: return False return True def iterate_plan(self, plan, preferences, budget): for i in range(len(plan)): for destination in self.destinations: if destination not in plan and self.match_preferences(destination, preferences) and self.calculate_cost(plan, destination) <= budget: plan[i] = destination break return plan def calculate_cost(self, plan, new_destination): return sum(destination['cost'] for destination in plan) + new_destination['cost'] # Example usage destinations = [ {"name": "Paris", "cost": 1000, "activity": "sightseeing"}, {"name": "Tokyo", "cost": 1200, "activity": "shopping"}, {"name": "New York", "cost": 900, "activity": "sightseeing"}, {"name": "Sydney", "cost": 1100, "activity": "beach"}, ] preferences = {"activity": "sightseeing"} budget = 2000 travel_agent = TravelAgent(destinations) initial_plan = travel_agent.bootstrap_plan(preferences, budget) print("Initial Plan:", initial_plan) refined_plan = travel_agent.iterate_plan(initial_plan, preferences, budget) print("Refined Plan:", refined_plan) ``` #### Explication du code 1. **Initialisation (`__init__` method)**: The `TravelAgent` class is initialized with a list of potential destinations, each having attributes like name, cost, and activity type. 2. **Bootstrapping the Plan (`bootstrap_plan` method)**: This method creates an initial travel plan based on the client's preferences and budget. It iterates through the list of destinations and adds them to the plan if they match the client's preferences and fit within the budget. 3. **Matching Preferences (`match_preferences` method)**: This method checks if a destination matches the client's preferences. 4. **Iterating the Plan (`iterate_plan` method)**: This method refines the initial plan by trying to replace each destination in the plan with a better match, considering the client's preferences and budget constraints. 5. **Calculating Cost (`calculate_cost` méthode)** : Cette méthode calcule le coût total du plan actuel, y compris une éventuelle nouvelle destination. #### Exemple d'utilisation - **Plan initial** : L'agent de voyage crée un plan initial basé sur les préférences du client pour les visites touristiques et un budget de 2000 $. - **Plan affiné** : L'agent de voyage itère le plan, en l'optimisant en fonction des préférences et du budget du client. En amorçant le plan avec un objectif clair (par exemple, maximiser la satisfaction du client) et en itérant pour affiner le plan, l'agent de voyage peut créer un itinéraire de voyage personnalisé et optimisé pour le client. Cette approche garantit que le plan de voyage est aligné sur les préférences et le budget du client dès le départ et s'améliore à chaque itération. ### Exploiter les LLM pour le reclassement et le scoring Les modèles de langage de grande taille (LLM) peuvent être utilisés pour le reclassement et le scoring en évaluant la pertinence et la qualité des documents récupérés ou des réponses générées. Voici comment cela fonctionne : **Récupération :** La première étape de récupération extrait un ensemble de documents ou de réponses candidats en fonction de la requête. **Reclassement :** Le LLM évalue ces candidats et les reclasse en fonction de leur pertinence et de leur qualité. Cette étape garantit que les informations les plus pertinentes et de haute qualité sont présentées en premier. **Scoring :** Le LLM attribue des scores à chaque candidat, reflétant leur pertinence et leur qualité. Cela aide à sélectionner la meilleure réponse ou le meilleur document pour l'utilisateur. En exploitant les LLM pour le reclassement et le scoring, le système peut fournir des informations plus précises et contextuellement pertinentes, améliorant ainsi l'expérience utilisateur globale. Voici un exemple de la façon dont un agent de voyage pourrait utiliser un modèle de langage de grande taille (LLM) pour le reclassement et le scoring des destinations de voyage en fonction des préférences des utilisateurs en Python : #### Scénario - Voyage basé sur les préférences Un agent de voyage souhaite recommander les meilleures destinations de voyage à un client en fonction de ses préférences. Le LLM aidera à reclasser et à noter les destinations pour s'assurer que les options les plus pertinentes sont présentées. #### Étapes : 1. Recueillir les préférences de l'utilisateur. 2. Récupérer une liste de destinations de voyage potentielles. 3. Utiliser le LLM pour reclasser et noter les destinations en fonction des préférences de l'utilisateur. Voici comment vous pouvez mettre à jour l'exemple précédent pour utiliser les services Azure OpenAI : #### Prérequis 1. Vous devez avoir un abonnement Azure. 2. Créez une ressource Azure OpenAI et obtenez votre clé API. #### Exemple de code Python ```python import requests import json class TravelAgent: def __init__(self, destinations): self.destinations = destinations def get_recommendations(self, preferences, api_key, endpoint): # Generate a prompt for the Azure OpenAI prompt = self.generate_prompt(preferences) # Define headers and payload for the request headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {api_key}' } payload = { "prompt": prompt, "max_tokens": 150, "temperature": 0.7 } # Call the Azure OpenAI API to get the re-ranked and scored destinations response = requests.post(endpoint, headers=headers, json=payload) response_data = response.json() # Extract and return the recommendations recommendations = response_data['choices'][0]['text'].strip().split('\n') return recommendations def generate_prompt(self, preferences): prompt = "Here are the travel destinations ranked and scored based on the following user preferences:\n" for key, value in preferences.items(): prompt += f"{key}: {value}\n" prompt += "\nDestinations:\n" for destination in self.destinations: prompt += f"- {destination['name']}: {destination['description']}\n" return prompt # Example usage destinations = [ {"name": "Paris", "description": "City of lights, known for its art, fashion, and culture."}, {"name": "Tokyo", "description": "Vibrant city, famous for its modernity and traditional temples."}, {"name": "New York", "description": "The city that never sleeps, with iconic landmarks and diverse culture."}, {"name": "Sydney", "description": "Beautiful harbour city, known for its opera house and stunning beaches."}, ] preferences = {"activity": "sightseeing", "culture": "diverse"} api_key = 'your_azure_openai_api_key' endpoint = 'https://your-endpoint.com/openai/deployments/your-deployment-name/completions?api-version=2022-12-01' travel_agent = TravelAgent(destinations) recommendations = travel_agent.get_recommendations(preferences, api_key, endpoint) print("Recommended Destinations:") for rec in recommendations: print(rec) ``` #### Explication du code - Preference Booker 1. **Initialisation** : Remplacez `TravelAgent` class is initialized with a list of potential travel destinations, each having attributes like name and description. 2. **Getting Recommendations (`get_recommendations` method)**: This method generates a prompt for the Azure OpenAI service based on the user's preferences and makes an HTTP POST request to the Azure OpenAI API to get re-ranked and scored destinations. 3. **Generating Prompt (`generate_prompt` method)**: This method constructs a prompt for the Azure OpenAI, including the user's preferences and the list of destinations. The prompt guides the model to re-rank and score the destinations based on the provided preferences. 4. **API Call**: The `requests` library is used to make an HTTP POST request to the Azure OpenAI API endpoint. The response contains the re-ranked and scored destinations. 5. **Example Usage**: The travel agent collects user preferences (e.g., interest in sightseeing and diverse culture) and uses the Azure OpenAI service to get re-ranked and scored recommendations for travel destinations. Make sure to replace `your_azure_openai_api_key` with your actual Azure OpenAI API key and `https://your-endpoint.com/...` par l'URL de point de terminaison réelle de votre déploiement Azure OpenAI. En exploitant le LLM pour le reclassement et le scoring, l'agent de voyage peut fournir des recommandations de voyage plus personnalisées et pertinentes aux clients, améliorant ainsi leur expérience globale. ``` ```markdown les meilleurs musées à Paris ?"). - **Intention de navigation** : L'utilisateur souhaite naviguer vers un site ou une page spécifique (par exemple, "Site officiel du musée du Louvre"). - **Intention transactionnelle** : L'utilisateur vise à effectuer une transaction, comme réserver un vol ou effectuer un achat (par exemple, "Réserver un vol pour Paris"). 2. **Conscience du contexte** : - L'analyse du contexte de la requête de l'utilisateur aide à identifier avec précision son intention. Cela inclut la prise en compte des interactions précédentes, des préférences de l'utilisateur et des détails spécifiques de la requête actuelle. 3. **Traitement du langage naturel (NLP)** : - Les techniques de NLP sont utilisées pour comprendre et interpréter les requêtes en langage naturel fournies par les utilisateurs. Cela inclut des tâches telles que la reconnaissance d'entités, l'analyse de sentiment et le traitement des requêtes. 4. **Personnalisation** : - Personnaliser les résultats de recherche en fonction de l'historique, des préférences et des retours de l'utilisateur améliore la pertinence des informations récupérées. #### Exemple pratique : Recherche avec intention dans Travel Agent Prenons Travel Agent comme exemple pour voir comment la recherche avec intention peut être mise en œuvre. 1. **Collecte des préférences de l'utilisateur** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Compréhension de l'intention de l'utilisateur** ```python def identify_intent(query): if "book" in query or "purchase" in query: return "transactional" elif "website" in query or "official" in query: return "navigational" else: return "informational" ``` 3. **Conscience du contexte** ```python def analyze_context(query, user_history): # Combine current query with user history to understand context context = { "current_query": query, "user_history": user_history } return context ``` 4. **Recherche et personnalisation des résultats** ```python def search_with_intent(query, preferences, user_history): intent = identify_intent(query) context = analyze_context(query, user_history) if intent == "informational": search_results = search_information(query, preferences) elif intent == "navigational": search_results = search_navigation(query) elif intent == "transactional": search_results = search_transaction(query, preferences) personalized_results = personalize_results(search_results, user_history) return personalized_results def search_information(query, preferences): # Example search logic for informational intent results = search_web(f"best {preferences['interests']} in {preferences['destination']}") return results def search_navigation(query): # Example search logic for navigational intent results = search_web(query) return results def search_transaction(query, preferences): # Example search logic for transactional intent results = search_web(f"book {query} to {preferences['destination']}") return results def personalize_results(results, user_history): # Example personalization logic personalized = [result for result in results if result not in user_history] return personalized[:10] # Return top 10 personalized results ``` 5. **Exemple d'utilisation** ```python travel_agent = Travel_Agent() preferences = { "destination": "Paris", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) user_history = ["Louvre Museum website", "Book flight to Paris"] query = "best museums in Paris" results = search_with_intent(query, preferences, user_history) print("Search Results:", results) ``` --- ## 4. Génération de code comme outil Les agents générateurs de code utilisent des modèles d'IA pour écrire et exécuter du code, résoudre des problèmes complexes et automatiser des tâches. ### Agents générateurs de code Les agents générateurs de code utilisent des modèles d'IA générative pour écrire et exécuter du code. Ces agents peuvent résoudre des problèmes complexes, automatiser des tâches et fournir des informations précieuses en générant et en exécutant du code dans divers langages de programmation. #### Applications pratiques 1. **Génération automatique de code** : Générer des extraits de code pour des tâches spécifiques, comme l'analyse de données, le scraping web ou l'apprentissage automatique. 2. **SQL en tant que RAG** : Utiliser des requêtes SQL pour récupérer et manipuler des données issues de bases de données. 3. **Résolution de problèmes** : Créer et exécuter du code pour résoudre des problèmes spécifiques, comme l'optimisation d'algorithmes ou l'analyse de données. #### Exemple : Agent générateur de code pour l'analyse de données Imaginons que vous conceviez un agent générateur de code. Voici comment il pourrait fonctionner : 1. **Tâche** : Analyser un jeu de données pour identifier des tendances et des modèles. 2. **Étapes** : - Charger le jeu de données dans un outil d'analyse de données. - Générer des requêtes SQL pour filtrer et agréger les données. - Exécuter les requêtes et récupérer les résultats. - Utiliser les résultats pour générer des visualisations et des insights. 3. **Ressources nécessaires** : Accès au jeu de données, outils d'analyse de données et capacités SQL. 4. **Expérience** : Utiliser les résultats d'analyses passées pour améliorer la précision et la pertinence des analyses futures. ### Exemple : Agent générateur de code pour Travel Agent Dans cet exemple, nous concevrons un agent générateur de code, Travel Agent, pour aider les utilisateurs à planifier leurs voyages en générant et en exécutant du code. Cet agent peut gérer des tâches telles que la récupération d'options de voyage, le filtrage des résultats et la compilation d'un itinéraire à l'aide de l'IA générative. #### Aperçu de l'agent générateur de code 1. **Collecte des préférences de l'utilisateur** : Collecte les entrées de l'utilisateur telles que la destination, les dates de voyage, le budget et les centres d'intérêt. 2. **Génération de code pour récupérer des données** : Génère des extraits de code pour récupérer des données sur les vols, les hôtels et les attractions. 3. **Exécution du code généré** : Exécute le code généré pour récupérer des informations en temps réel. 4. **Génération d'un itinéraire** : Compile les données récupérées dans un plan de voyage personnalisé. 5. **Ajustement en fonction des retours** : Reçoit les retours de l'utilisateur et régénère le code si nécessaire pour affiner les résultats. #### Mise en œuvre étape par étape 1. **Collecte des préférences de l'utilisateur** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Génération de code pour récupérer des données** ```python def generate_code_to_fetch_data(preferences): # Example: Generate code to search for flights based on user preferences code = f""" def search_flights(): import requests response = requests.get('https://api.example.com/flights', params={preferences}) return response.json() """ return code def generate_code_to_fetch_hotels(preferences): # Example: Generate code to search for hotels code = f""" def search_hotels(): import requests response = requests.get('https://api.example.com/hotels', params={preferences}) return response.json() """ return code ``` 3. **Exécution du code généré** ```python def execute_code(code): # Execute the generated code using exec exec(code) result = locals() return result travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) flight_code = generate_code_to_fetch_data(preferences) hotel_code = generate_code_to_fetch_hotels(preferences) flights = execute_code(flight_code) hotels = execute_code(hotel_code) print("Flight Options:", flights) print("Hotel Options:", hotels) ``` 4. **Génération d'un itinéraire** ```python def generate_itinerary(flights, hotels, attractions): itinerary = { "flights": flights, "hotels": hotels, "attractions": attractions } return itinerary attractions = search_attractions(preferences) itinerary = generate_itinerary(flights, hotels, attractions) print("Suggested Itinerary:", itinerary) ``` 5. **Ajustement en fonction des retours** ```python def adjust_based_on_feedback(feedback, preferences): # Adjust preferences based on user feedback if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] return preferences feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} updated_preferences = adjust_based_on_feedback(feedback, preferences) # Regenerate and execute code with updated preferences updated_flight_code = generate_code_to_fetch_data(updated_preferences) updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences) updated_flights = execute_code(updated_flight_code) updated_hotels = execute_code(updated_hotel_code) updated_itinerary = generate_itinerary(updated_flights, updated_hotels, attractions) print("Updated Itinerary:", updated_itinerary) ``` ### Exploitation de la conscience de l'environnement et du raisonnement Basée sur le schéma de la table, elle peut effectivement améliorer le processus de génération de requêtes en tirant parti de la conscience de l'environnement et du raisonnement. Voici un exemple de la façon dont cela peut être fait : 1. **Compréhension du schéma** : Le système comprendra le schéma de la table et utilisera cette information pour ancrer la génération de requêtes. 2. **Ajustement en fonction des retours** : Le système ajustera les préférences de l'utilisateur en fonction des retours et réfléchira aux champs du schéma qui doivent être mis à jour. 3. **Génération et exécution des requêtes** : Le système générera et exécutera des requêtes pour récupérer des données mises à jour sur les vols et les hôtels en fonction des nouvelles préférences. Voici un exemple de code Python mis à jour qui intègre ces concepts : ```python def adjust_based_on_feedback(feedback, preferences, schema): # Adjust preferences based on user feedback if "liked" in feedback: preferences["favorites"] = feedback["liked"] if "disliked" in feedback: preferences["avoid"] = feedback["disliked"] # Reasoning based on schema to adjust other related preferences for field in schema: if field in preferences: preferences[field] = adjust_based_on_environment(feedback, field, schema) return preferences def adjust_based_on_environment(feedback, field, schema): # Custom logic to adjust preferences based on schema and feedback if field in feedback["liked"]: return schema[field]["positive_adjustment"] elif field in feedback["disliked"]: return schema[field]["negative_adjustment"] return schema[field]["default"] def generate_code_to_fetch_data(preferences): # Generate code to fetch flight data based on updated preferences return f"fetch_flights(preferences={preferences})" def generate_code_to_fetch_hotels(preferences): # Generate code to fetch hotel data based on updated preferences return f"fetch_hotels(preferences={preferences})" def execute_code(code): # Simulate execution of code and return mock data return {"data": f"Executed: {code}"} def generate_itinerary(flights, hotels, attractions): # Generate itinerary based on flights, hotels, and attractions return {"flights": flights, "hotels": hotels, "attractions": attractions} # Example schema schema = { "favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"}, "avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"} } # Example usage preferences = {"favorites": "sightseeing", "avoid": "crowded places"} feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]} updated_preferences = adjust_based_on_feedback(feedback, preferences, schema) # Regenerate and execute code with updated preferences updated_flight_code = generate_code_to_fetch_data(updated_preferences) updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences) updated_flights = execute_code(updated_flight_code) updated_hotels = execute_code(updated_hotel_code) updated_itinerary = generate_itinerary(updated_flights, updated_hotels, feedback["liked"]) print("Updated Itinerary:", updated_itinerary) ``` #### Explication - Réservation basée sur les retours 1. **Conscience du schéma** : La méthode `schema` dictionary defines how preferences should be adjusted based on feedback. It includes fields like `favorites` and `avoid`, with corresponding adjustments. 2. **Adjusting Preferences (`adjust_based_on_feedback` method)**: This method adjusts preferences based on user feedback and the schema. 3. **Environment-Based Adjustments (`adjust_based_on_environment` personnalise les ajustements en fonction du schéma et des retours. 4. **Génération et exécution des requêtes** : Le système génère du code pour récupérer des données mises à jour sur les vols et les hôtels en fonction des préférences ajustées et simule l'exécution de ces requêtes. 5. **Génération d'un itinéraire** : Le système crée un itinéraire mis à jour en fonction des nouvelles données sur les vols, les hôtels et les attractions. En rendant le système conscient de l'environnement et en raisonnant en fonction du schéma, il peut générer des requêtes plus précises et pertinentes, conduisant à de meilleures recommandations de voyage et à une expérience utilisateur plus personnalisée. ### Utilisation de SQL comme technique de génération augmentée par récupération (RAG) SQL (Structured Query Language) est un outil puissant pour interagir avec des bases de données. Lorsqu'il est utilisé dans le cadre d'une approche de génération augmentée par récupération (RAG), SQL peut récupérer des données pertinentes à partir de bases de données pour informer et générer des réponses ou des actions dans les agents d'IA. Explorons comment SQL peut être utilisé comme technique RAG dans le contexte de Travel Agent. #### Concepts clés 1. **Interaction avec la base de données** : - SQL est utilisé pour interroger des bases de données, récupérer des informations pertinentes et manipuler des données. - Exemple : Récupérer des détails sur les vols, les hôtels et les attractions à partir d'une base de données de voyage. 2. **Intégration avec RAG** : - Les requêtes SQL sont générées en fonction des entrées et préférences de l'utilisateur. - Les données récupérées sont ensuite utilisées pour générer des recommandations ou des actions personnalisées. 3. **Génération dynamique de requêtes** : - L'agent d'IA génère des requêtes SQL dynamiques en fonction du contexte et des besoins de l'utilisateur. - Exemple : Personnaliser les requêtes SQL pour filtrer les résultats en fonction du budget, des dates et des centres d'intérêt. #### Applications - **Génération automatique de code** : Générer des extraits de code pour des tâches spécifiques. - **SQL en tant que RAG** : Utiliser des requêtes SQL pour manipuler des données. - **Résolution de problèmes** : Créer et exécuter du code pour résoudre des problèmes. **Exemple** : Un agent d'analyse de données : 1. **Tâche** : Analyser un jeu de données pour trouver des tendances. 2. **Étapes** : - Charger le jeu de données. - Générer des requêtes SQL pour filtrer les données. - Exécuter les requêtes et récupérer les résultats. - Générer des visualisations et des insights. 3. **Ressources** : Accès au jeu de données, capacités SQL. 4. **Expérience** : Utiliser les résultats passés pour améliorer les analyses futures. #### Exemple pratique : Utilisation de SQL dans Travel Agent 1. **Collecte des préférences de l'utilisateur** ```python class Travel_Agent: def __init__(self): self.user_preferences = {} def gather_preferences(self, preferences): self.user_preferences = preferences ``` 2. **Génération de requêtes SQL** ```python def generate_sql_query(table, preferences): query = f"SELECT * FROM {table} WHERE " conditions = [] for key, value in preferences.items(): conditions.append(f"{key}='{value}'") query += " AND ".join(conditions) return query ``` 3. **Exécution des requêtes SQL** ```python import sqlite3 def execute_sql_query(query, database="travel.db"): connection = sqlite3.connect(database) cursor = connection.cursor() cursor.execute(query) results = cursor.fetchall() connection.close() return results ``` 4. **Génération de recommandations** ```python def generate_recommendations(preferences): flight_query = generate_sql_query("flights", preferences) hotel_query = generate_sql_query("hotels", preferences) attraction_query = generate_sql_query("attractions", preferences) flights = execute_sql_query(flight_query) hotels = execute_sql_query(hotel_query) attractions = execute_sql_query(attraction_query) itinerary = { "flights": flights, "hotels": hotels, "attractions": attractions } return itinerary travel_agent = Travel_Agent() preferences = { "destination": "Paris", "dates": "2025-04-01 to 2025-04-10", "budget": "moderate", "interests": ["museums", "cuisine"] } travel_agent.gather_preferences(preferences) itinerary = generate_recommendations(preferences) print("Suggested Itinerary:", itinerary) ``` #### Exemples de requêtes SQL 1. **Requête pour les vols** ```sql SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate'; ``` 2. **Requête pour les hôtels** ```sql SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate'; ``` 3. **Requête pour les attractions** ```sql SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine'; ``` En utilisant SQL dans le cadre de la technique de génération augmentée par récupération (RAG), les agents d'IA comme Travel Agent peuvent récupérer et utiliser dynamiquement des données pertinentes pour fournir des recommandations précises et personnalisées. ### Conclusion La métacognition est un outil puissant qui peut améliorer considérablement les capacités des agents d'IA. En incorporant des processus métacognitifs, vous pouvez concevoir des agents plus intelligents, adaptables et efficaces. Utilisez les ressources supplémentaires pour explorer davantage le monde fascinant de la métacognition dans les agents d'IA. ``` **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatique basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de faire appel à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/09-metacognition/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/09-metacognition/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 50035 }
# Agents d'IA en Production ## Introduction Cette leçon couvrira : - Comment planifier efficacement le déploiement de votre agent d'IA en production. - Les erreurs courantes et les problèmes que vous pourriez rencontrer lors du déploiement de votre agent d'IA en production. - Comment gérer les coûts tout en maintenant les performances de votre agent d'IA. ## Objectifs d'apprentissage Après avoir terminé cette leçon, vous saurez/comment : - Utiliser des techniques pour améliorer les performances, les coûts et l'efficacité d'un système d'agent d'IA en production. - Évaluer vos agents d'IA et ce qu'il faut examiner. - Contrôler les coûts lors du déploiement des agents d'IA en production. Il est essentiel de déployer des agents d'IA fiables. Consultez également la leçon "Construire des agents d'IA dignes de confiance". ## Évaluation des agents d'IA Avant, pendant et après le déploiement des agents d'IA, il est crucial de mettre en place un système adéquat pour évaluer vos agents. Cela garantit que votre système est aligné sur vos objectifs et ceux de vos utilisateurs. Pour évaluer un agent d'IA, il est important de pouvoir évaluer non seulement les résultats de l'agent, mais également l'ensemble du système dans lequel il opère. Cela inclut, sans s'y limiter : - La requête initiale au modèle. - La capacité de l'agent à identifier l'intention de l'utilisateur. - La capacité de l'agent à choisir le bon outil pour accomplir la tâche. - La réponse de l'outil à la requête de l'agent. - La capacité de l'agent à interpréter la réponse de l'outil. - Le retour d'information de l'utilisateur sur la réponse de l'agent. Cela vous permet d'identifier les domaines à améliorer de manière plus modulaire. Vous pourrez ensuite surveiller l'effet des changements sur les modèles, les invites, les outils et d'autres composants avec une meilleure efficacité. ## Problèmes courants et solutions potentielles avec les agents d'IA | **Problème** | **Solution potentielle** | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | L'agent d'IA n'exécute pas les tâches de manière cohérente | - Affinez l'invite donnée à l'agent d'IA ; soyez clair sur les objectifs.<br>- Identifiez si diviser les tâches en sous-tâches et les confier à plusieurs agents peut être utile. | | L'agent d'IA entre dans des boucles continues | - Assurez-vous d'avoir des termes et conditions de terminaison clairs pour que l'agent sache quand arrêter le processus.<br>- Pour les tâches complexes nécessitant du raisonnement et de la planification, utilisez un modèle plus grand spécialisé dans ces tâches. | | Les appels aux outils par l'agent d'IA ne sont pas performants | - Testez et validez les résultats des outils en dehors du système de l'agent.<br>- Affinez les paramètres définis, les invites et les noms des outils. | | Le système multi-agents manque de cohérence | - Affinez les invites données à chaque agent pour qu'elles soient spécifiques et distinctes les unes des autres.<br>- Construisez un système hiérarchique en utilisant un agent "routeur" ou contrôleur pour déterminer quel agent est le plus adapté. | ## Gestion des coûts Voici quelques stratégies pour gérer les coûts du déploiement des agents d'IA en production : - **Mise en cache des réponses** - Identifier les requêtes et tâches courantes et fournir les réponses avant qu'elles ne passent par votre système d'agents est une bonne façon de réduire le volume de requêtes similaires. Vous pouvez même implémenter un flux pour identifier à quel point une requête est similaire à vos requêtes mises en cache en utilisant des modèles d'IA plus basiques. - **Utilisation de modèles plus petits** - Les Small Language Models (SLMs) peuvent être efficaces pour certains cas d'utilisation d'agents et réduiront considérablement les coûts. Comme mentionné précédemment, construire un système d'évaluation pour déterminer et comparer les performances par rapport à des modèles plus grands est la meilleure façon de comprendre dans quelle mesure un SLM peut convenir à votre cas d'utilisation. - **Utilisation d'un modèle routeur** - Une stratégie similaire consiste à utiliser une diversité de modèles et de tailles. Vous pouvez utiliser un LLM/SLM ou une fonction sans serveur pour router les requêtes en fonction de leur complexité vers les modèles les plus adaptés. Cela aidera également à réduire les coûts tout en assurant de bonnes performances pour les tâches appropriées. ## Félicitations Ceci est actuellement la dernière leçon de "Agents d'IA pour Débutants". Nous prévoyons d'ajouter des leçons en fonction des retours et des évolutions dans cette industrie en pleine croissance, alors revenez nous voir prochainement. Si vous souhaitez continuer à apprendre et à développer avec des agents d'IA, rejoignez le [Azure AI Community Discord](https://discord.gg/kzRShWzttr). Nous y organisons des ateliers, des tables rondes communautaires et des sessions "ask me anything". Nous avons également une collection de ressources d'apprentissage supplémentaires qui peuvent vous aider à commencer à déployer des agents d'IA en production. ``` **Avertissement** : Ce document a été traduit à l'aide de services de traduction automatique basés sur l'intelligence artificielle. Bien que nous fassions de notre mieux pour garantir l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de faire appel à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction.
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/fr/10-ai-agents-production/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/10-ai-agents-production/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 6429 }
# 課程設定 ## 簡介 呢堂會教你點樣運行呢個課程嘅代碼示例。 ## 必備條件 - 一個 GitHub 帳戶 - Python 3.12 或以上版本 ## 複製或分叉呢個 Repo 首先,請複製(clone)或者分叉(fork)GitHub 嘅 Repository。咁樣你就可以擁有課程材料嘅自己版本,方便運行、測試同埋調整代碼! 可以點擊呢個連結 [fork the repo](https://github.com/microsoft/ai-agents-for-beginners/fork) 去操作。 完成後,你應該會有一個好似以下圖示嘅分叉版本: ![Forked Repo](../../../translated_images/forked-repo.eea246a73044cc984a1e462349e36e7336204f00785e3187b7399905feeada07.hk.png) ## 獲取你嘅 GitHub Personal Access Token (PAT) 目前呢個課程使用 GitHub Models Marketplace 提供免費嘅大型語言模型(LLMs)服務,用嚟創建 AI Agents。 要使用呢個服務,你需要創建一個 GitHub 嘅 Personal Access Token。 你可以去你嘅 GitHub 帳戶嘅 [Personal Access Tokens settings](https://github.com/settings/personal-access-tokens) 頁面創建。 揀選屏幕左邊嘅 `Fine-grained tokens` 選項。 然後揀選 `Generate new token`。 ![Generate Token](../../../translated_images/generate-token.361ec40abe59b84ac68d63c23e2b6854d6fad82bd4e41feb98fc0e6f030e8ef7.hk.png) 複製你啱啱創建嘅新 Token。之後,你需要將呢個 Token 加到課程中提供嘅 `.env` 文件內。 ## 將 Token 加到環境變數 要創建你嘅 `.env` 文件,可以喺終端運行以下命令: ```bash cp .env.example .env ``` 呢條命令會複製示例文件,並喺你嘅目錄內創建一個 `.env` 文件。 打開呢個文件,然後將你創建嘅 Token 貼到 `.env` 文件中 `GITHUB_TOKEN=` 呢一行。 ## 安裝所需嘅套件 為咗確保你有齊所有運行代碼所需嘅 Python 套件,請喺終端運行以下命令。 我哋建議你創建一個 Python 虛擬環境,避免發生衝突同埋問題。 ```bash pip install -r requirements.txt ``` 呢條命令應該會安裝所有所需嘅 Python 套件。 而家你已經準備好運行課程嘅代碼,祝你學習 AI Agents 嘅世界愉快! 如果喺設定過程中遇到任何問題,可以加入我哋嘅 [Azure AI Community Discord](https://discord.gg/kzRShWzttr) 或者 [create an issue](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst)。 **免責聲明**: 本文件經由機器翻譯人工智能服務進行翻譯。儘管我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文作為權威來源。如涉及重要資訊,建議尋求專業人工翻譯。我們對因使用本翻譯而引起的任何誤解或錯誤解釋概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/00-course-setup/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/00-course-setup/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 1645 }
# 人工智能代理簡介及應用場景 歡迎來到「人工智能代理入門」課程!這門課程將為你提供構建人工智能代理的基礎知識和實際範例。 加入 [Azure AI Discord 社群](https://discord.gg/kzRShWzttr),與其他學習者和人工智能代理開發者互動,並隨時提問有關本課程的問題。 在課程開始前,我們將首先了解什麼是人工智能代理,以及如何在我們構建的應用程式和工作流程中使用它們。 ## 課程介紹 本課程將涵蓋: - 什麼是人工智能代理?有哪些不同類型的代理? - 哪些應用場景最適合人工智能代理?它們如何幫助我們? - 設計代理解決方案時的一些基本組件有哪些? ## 學習目標 完成本課程後,你應該能夠: - 理解人工智能代理的概念,以及它們與其他 AI 解決方案的區別。 - 高效應用人工智能代理。 - 為用戶和客戶設計具有生產力的代理解決方案。 ## 定義人工智能代理及其類型 ### 什麼是人工智能代理? 人工智能代理是**系統**,通過為**大型語言模型(LLMs)**提供**工具**和**知識**的訪問權限,來擴展其能力並讓它們**執行操作**。 讓我們將這個定義分解為幾個部分來理解: - **系統** - 代理不是單一組件,而是一個由多個組件組成的系統。在基礎層面,人工智能代理的組件包括: - **環境** - 定義代理運行的空間。例如,如果我們有一個旅行預訂代理,環境可能是代理用來完成任務的旅行預訂系統。 - **感測器** - 環境提供信息和反饋。代理使用感測器來收集並解釋這些信息,了解環境的當前狀態。在旅行預訂代理的例子中,感測器可能從系統中獲取酒店空房信息或機票價格。 - **執行器** - 當代理接收到環境的當前狀態後,會決定採取哪些行動來改變環境。例如,旅行預訂代理可能會為用戶預訂一間可用的房間。 ![什麼是人工智能代理?](../../../translated_images/what-are-ai-agents.125520f55950b252a429b04a9f41e0152d4dafa1f1bd9081f4f574631acb759e.hk.png?WT.mc_id=academic-105485-koreyst) **大型語言模型** - 在 LLM 出現之前,代理的概念已經存在。使用 LLM 構建代理的優勢在於其能夠解釋人類語言和數據的能力。這種能力讓 LLM 可以解釋環境信息並制定改變環境的計劃。 **執行操作** - 在代理系統之外,LLM 的行動僅限於根據用戶的提示生成內容或信息。而在代理系統內,LLM 能夠通過解釋用戶請求並使用環境中的工具來完成任務。 **工具訪問** - LLM 可使用的工具取決於 1) 它運行的環境,以及 2) 開發者的設計。例如,在旅行代理的例子中,代理的工具可能僅限於預訂系統提供的操作,或者開發者可以限制代理只能訪問航班的相關工具。 **知識** - 除了環境提供的信息,代理還可以從其他系統、服務、工具甚至其他代理中檢索知識。在旅行代理的例子中,這些知識可能包括客戶數據庫中用戶的旅行偏好信息。 ### 不同類型的代理 現在我們已經了解了人工智能代理的基本定義,讓我們看看一些具體的代理類型,以及它們如何應用於旅行預訂代理。 | **代理類型** | **描述** | **範例** | | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **簡單反射代理** | 基於預定義規則執行即時行動。 | 旅行代理解讀電子郵件內容,並將旅行投訴轉發給客戶服務部門。 | | **基於模型的反射代理** | 基於對世界的模型及其變化執行行動。 | 旅行代理根據歷史價格數據的訪問權限,優先處理價格變動較大的路線。 | | **目標導向代理** | 通過解釋目標並確定達成目標的行動來制定計劃。 | 旅行代理通過確定從當前位置到目的地所需的旅行安排(如汽車、公車、航班)來完成行程預訂。 | | **效用導向代理** | 考慮偏好並通過數值權衡取捨來確定如何達成目標。 | 旅行代理在預訂行程時通過權衡便利性與成本來最大化效用。 | | **學習型代理** | 通過響應反饋並相應調整行動來隨時間改進。 | 旅行代理通過使用客戶在行程後的調查反饋,對未來的預訂進行調整以改進服務。 | | **分層代理** | 包含多個層級代理,高層代理將任務分解為子任務,交由低層代理完成。 | 旅行代理取消行程時,將任務分解為子任務(例如取消具體的預訂),並由低層代理完成,然後向高層代理匯報。 | | **多代理系統(MAS)** | 代理以協作或競爭的方式獨立完成任務。 | 協作:多個代理分別預訂特定的旅行服務,如酒店、航班和娛樂活動。競爭:多個代理管理並競爭共享的酒店預訂日曆,為客戶預訂房間。 | ## 何時使用人工智能代理 在上一節中,我們使用旅行代理的應用場景來解釋不同類型代理在旅行預訂中的使用方式。在本課程中,我們將繼續使用這個應用場景。 讓我們看看人工智能代理最適合的應用場景類型: ![何時使用人工智能代理?](../../../translated_images/when-to-use-ai-agents.912b9a02e9e0e2af45a3e24faa4e912e334ec23f21f0cf5cb040b7e899b09cd0.hk.png?WT.mc_id=academic-105485-koreyst) - **開放性問題** - 當任務所需的步驟無法總是硬編碼進工作流程時,允許 LLM 自行決定完成任務所需的步驟。 - **多步驟流程** - 當任務需要一定的複雜性,代理需要通過多次互動使用工具或信息,而非一次性檢索時。 - **隨時間改進** - 當任務需要通過接收來自環境或用戶的反饋來改進,以提供更好的效用時。 我們會在「構建可信賴的人工智能代理」課程中詳細討論使用代理的更多考量。 ## 代理解決方案的基礎 ### 代理開發 設計人工智能代理系統的第一步是定義工具、行動和行為。在本課程中,我們專注於使用 **Azure AI Agent Service** 來定義代理。它提供以下功能: - 選擇開放模型,例如 OpenAI、Mistral 和 Llama - 通過 Tripadvisor 等供應商使用授權數據 - 使用標準化的 OpenAPI 3.0 工具 ### 代理模式 與 LLM 的溝通是通過提示完成的。由於人工智能代理具有半自動化的特性,並非總是需要在環境變化後手動重新提示 LLM。我們使用 **代理模式**,以更具規模化的方式在多步驟中提示 LLM。 本課程分為一些當前流行的代理模式進行學習。 ### 代理框架 代理框架允許開發者通過程式碼實現代理模式。這些框架提供模板、插件和工具,增強人工智能代理的協作能力。這些優勢使得人工智能代理系統的可觀察性和故障排除能力更強。 在本課程中,我們將探索基於研究的 AutoGen 框架,以及來自 Semantic Kernel 的生產級代理框架。 ``` **免責聲明**: 本文件經由機器翻譯人工智能服務翻譯而成。雖然我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文文件作為權威來源。如涉及關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或錯誤解釋概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/01-intro-to-ai-agents/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/01-intro-to-ai-agents/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 5453 }
# 探索 AI Agent 框架 AI Agent 框架係一啲專門設計嘅軟件平台,目標係簡化 AI agent 嘅開發、部署同管理。呢啲框架為開發者提供預設嘅組件、抽象層同工具,令到開發複雜嘅 AI 系統變得更加簡單。 呢啲框架幫助開發者專注於應用程式嘅獨特部分,通過為 AI agent 開發中常見嘅挑戰提供標準化嘅解決方案。佢哋提升咗構建 AI 系統嘅可擴展性、可用性同效率。 ## 簡介 呢堂課會涵蓋: - 乜嘢係 AI Agent 框架?佢哋可以幫開發者做到啲乜? - 團隊可以點樣利用呢啲框架快速原型設計、反覆改良同提升 agent 嘅能力? - 微軟開發嘅框架同工具([Autogen](https://aka.ms/ai-agents/autogen) / [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) / [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service))有乜唔同? - 我可以直接整合現有嘅 Azure 生態系統工具,定係需要獨立嘅解決方案? - 乜嘢係 Azure AI Agents Service?佢可以點樣幫到我? ## 學習目標 呢堂課嘅目標係幫你了解: - AI Agent 框架喺 AI 開發中嘅角色。 - 點樣利用 AI Agent 框架構建智能 agent。 - AI Agent 框架提供嘅關鍵功能。 - Autogen、Semantic Kernel 同 Azure AI Agent Service 嘅分別。 ## 乜嘢係 AI Agent 框架?佢哋可以幫開發者做到啲乜? 傳統嘅 AI 框架可以幫你將 AI 整合到應用程式入面,並令呢啲應用更好,方式如下: - **個性化**:AI 可以分析用戶行為同喜好,提供個人化推薦、內容同體驗。 例子:Netflix 呢類串流服務用 AI 根據用戶嘅觀看歷史推薦電影同節目,提升用戶參與度同滿意度。 - **自動化同效率**:AI 可以自動化重複性任務、簡化工作流程,提升運營效率。 例子:客戶服務應用利用 AI 驅動嘅聊天機械人處理常見查詢,縮短回應時間,令人工客服可以專注於更複雜嘅問題。 - **提升用戶體驗**:AI 可以提供智能功能,例如語音識別、自然語言處理同預測文本,改善整體用戶體驗。 例子:虛擬助手例如 Siri 同 Google Assistant 利用 AI 理解同回應語音指令,令用戶更容易操作設備。 ### 咁聽起嚟好正,但點解仲需要 AI Agent 框架? AI Agent 框架唔止係 AI 框架咁簡單。佢哋設計出嚟係為咗創建智能 agent,呢啲 agent 可以同用戶、其他 agent 同環境互動,達到特定目標。呢啲 agent 可以表現出自主行為、作決策,並適應不斷變化嘅條件。以下係 AI Agent 框架提供嘅幾個關鍵功能: - **Agent 合作同協調**:支持創建多個 AI agent,佢哋可以合作、溝通同協調,解決複雜任務。 - **任務自動化同管理**:提供機制,自動化多步工作流程、任務分配同動態任務管理。 - **上下文理解同適應**:賦予 agent 理解上下文、適應環境變化嘅能力,並根據實時信息作出決策。 總結嚟講,agent 令你做到更多,可以將自動化提升到新層次,創建能夠適應同學習環境嘅更智能系統。 ## 點樣快速原型設計、反覆改良同提升 agent 嘅能力? 呢個領域發展得好快,但大多數 AI Agent 框架都有啲共通點,可以幫你快速原型設計同反覆改良,包括模塊化組件、協作工具同實時學習。讓我哋逐一探討: - **使用模塊化組件**:AI 框架提供預設嘅組件,例如 prompts、parsers 同記憶管理。 - **利用協作工具**:設計擁有特定角色同任務嘅 agent,測試同改良協作工作流程。 - **實時學習**:實現反饋循環,令 agent 從互動中學習,並動態調整行為。 ### 使用模塊化組件 框架例如 LangChain 同 Microsoft Semantic Kernel 提供預設嘅組件,例如 prompts、parsers 同記憶管理。 **團隊點樣用呢啲**:團隊可以快速組裝呢啲組件,創建一個可用嘅原型,而唔需要從零開始,從而快速進行實驗同反覆改良。 **實際操作係點**:你可以使用預設嘅 parser 從用戶輸入中提取信息,用記憶模塊存取數據,並用 prompt 生成器同用戶互動,呢啲都唔需要你自己從頭開發。 **範例代碼**:以下係一個例子,展示點樣用預設嘅 parser 從用戶輸入中提取信息: ```python from langchain import Parser parser = Parser() user_input = "Book a flight from New York to London on July 15th" parsed_data = parser.parse(user_input) print(parsed_data) # Output: {'origin': 'New York', 'destination': 'London', 'date': 'July 15th'} ``` 由呢個例子你可以睇到,點樣利用預設嘅 parser 提取用戶輸入嘅關鍵信息,例如航班預訂請求嘅出發地、目的地同日期。呢種模塊化方法可以令你專注於高層次邏輯。 ### 利用協作工具 框架例如 CrewAI 同 Microsoft Autogen 幫助創建多個可以合作嘅 agent。 **團隊點樣用呢啲**:團隊可以設計擁有特定角色同任務嘅 agent,測試同改良協作工作流程,從而提升整體系統效率。 **實際操作係點**:你可以創建一組 agent,每個 agent 都有專門功能,例如數據檢索、分析或決策。呢啲 agent 可以溝通同分享信息,以完成共同目標,例如回答用戶查詢或完成任務。 **範例代碼 (Autogen)**: ```python # creating agents, then create a round robin schedule where they can work together, in this case in order # Data Retrieval Agent # Data Analysis Agent # Decision Making Agent agent_retrieve = AssistantAgent( name="dataretrieval", model_client=model_client, tools=[retrieve_tool], system_message="Use tools to solve tasks." ) agent_analyze = AssistantAgent( name="dataanalysis", model_client=model_client, tools=[analyze_tool], system_message="Use tools to solve tasks." ) # conversation ends when user says "APPROVE" termination = TextMentionTermination("APPROVE") user_proxy = UserProxyAgent("user_proxy", input_func=input) team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination) stream = team.run_stream(task="Analyze data", max_turns=10) # Use asyncio.run(...) when running in a script. await Console(stream) ``` 上面嘅代碼展示咗點樣創建一個涉及多個 agent 協作分析數據嘅任務。每個 agent 執行特定功能,並通過協調佢哋嘅行動完成目標任務。創建專門角色嘅 agent 可以提升任務效率同性能。 ### 實時學習 高級框架提供實時上下文理解同適應嘅能力。 **團隊點樣用呢啲**:團隊可以實現反饋循環,令 agent 從互動中學習,並動態調整行為,實現持續改良同能力提升。 **實際操作係點**:agent 可以分析用戶反饋、環境數據同任務結果,更新佢哋嘅知識庫,調整決策算法,並隨時間改進性能。呢種反覆學習過程令 agent 能夠適應變化嘅條件同用戶偏好,提升整體系統效能。 ## Autogen、Semantic Kernel 同 Azure AI Agent Service 嘅分別係咩? 有好多方法可以比較呢啲框架,以下係從設計、功能同目標用例方面嘅主要區別: ### Autogen 一個由 Microsoft Research 嘅 AI Frontiers Lab 開發嘅開源框架,專注於事件驅動、分布式嘅 *agentic* 應用,支持多個 LLMs、SLMs、工具同高級多-agent 設計模式。 Autogen 嘅核心概念係基於 agent,呢啲係自主實體,可以感知環境、作決策同採取行動以達到特定目標。agent 通過非同步消息進行溝通,令佢哋可以獨立同並行工作,提升系統可擴展性同響應能力。 ...(以下省略其餘部分,內容太長)... 根據項目目標。適用於自然語言理解、內容生成。 - **Azure AI Agent Service**:靈活的模型、企業級安全機制、數據存儲方法。適用於企業應用中安全、可擴展且靈活的 AI 代理部署。 ## 我可以直接整合現有的 Azure 生態系統工具,還是需要獨立的解決方案? 答案是肯定的,您可以直接將現有的 Azure 生態系統工具與 Azure AI Agent Service 整合,特別是因為它被設計為能與其他 Azure 服務無縫協作。例如,您可以整合 Bing、Azure AI Search 和 Azure Functions。還有與 Azure AI Foundry 的深度整合。對於 Autogen 和 Semantic Kernel,您也可以與 Azure 服務整合,但可能需要從您的代碼中調用 Azure 服務。另一種整合方式是使用 Azure SDK 從您的代理與 Azure 服務進行交互。此外,如前所述,您可以將 Azure AI Agent Service 作為 Autogen 或 Semantic Kernel 構建的代理的協調器,這將使您能輕鬆訪問 Azure 生態系統。 ## 參考資料 - [1] - [Azure Agent Service](https://techcommunity.microsoft.com/blog/azure-ai-services-blog/introducing-azure-ai-agent-service/4298357) - [2] - [Semantic Kernel and Autogen](https://devblogs.microsoft.com/semantic-kernel/microsofts-agentic-ai-frameworks-autogen-and-semantic-kernel/) - [3] - [Semantic Kernel Agent Framework](https://learn.microsoft.com/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp) - [4] - [Azure AI Agent service](https://learn.microsoft.com/azure/ai-services/agents/overview) - [5] - [Using Azure AI Agent Service with AutoGen / Semantic Kernel to build a multi-agent's solution](https://techcommunity.microsoft.com/blog/educatordeveloperblog/using-azure-ai-agent-service-with-autogen--semantic-kernel-to-build-a-multi-agen/4363121) **免責聲明**: 本文件是使用機器翻譯AI服務進行翻譯的。我們致力於追求準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件為權威來源。對於關鍵信息,建議尋求專業人工翻譯。我們對因使用本翻譯而引起的任何誤解或錯誤解釋概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/02-explore-agentic-frameworks/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/02-explore-agentic-frameworks/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 5620 }
# AI Agentic Design Principles ## 簡介 建立 AI Agentic 系統有好多唔同嘅方法。由於喺生成式 AI 設計中,模糊性係一個特性而唔係缺陷,所以工程師有時會唔知點開始。我哋創建咗一套以人為本嘅用戶體驗設計原則,幫助開發者建立以客戶為中心嘅 agentic 系統,從而解決業務需求。呢啲設計原則唔係一個具體嘅架構,而係一個幫助團隊定義同建立 agent 體驗嘅起點。 一般嚟講,agents 應該: - 擴展同提升人類能力(例如:頭腦風暴、解決問題、自動化等) - 填補知識空白(例如:讓我快速掌握知識領域、翻譯等) - 支援並促進協作,滿足我哋每個人偏好嘅合作方式 - 幫助我哋成為更好嘅自己(例如:人生教練/任務管理,幫助學習情緒調節同正念技能,建立韌性等) ## 呢堂課會講咩 - 乜嘢係 Agentic 設計原則 - 喺實施呢啲設計原則時要遵守嘅指引 - 使用設計原則嘅例子 ## 學習目標 完成呢堂課後,你將能夠: 1. 解釋乜嘢係 Agentic 設計原則 2. 解釋使用 Agentic 設計原則嘅指引 3. 明白點樣用 Agentic 設計原則建立一個 agent ## Agentic 設計原則 ![Agentic Design Principles](../../../translated_images/agentic-design-principles.9f32a64bb6e2aa5a1bdffb70111aa724058bc248b1a3dd3c6661344015604cff.hk.png?WT.mc_id=academic-105485-koreyst) ### Agent(空間) 呢個係 agent 運作嘅環境。呢啲原則指導我哋點樣設計 agents,讓佢哋能夠喺實體同數碼世界中互動。 - **連結,而唔係隔絕** – 幫助人哋連結其他人、事件同可行嘅知識,促進協作同連接。 - Agents 幫助連結事件、知識同人。 - Agents 拉近人與人之間嘅距離,而唔係設計嚟取代或者貶低人。 - **容易接觸但偶爾隱形** – agent 大部分時間喺背景運作,只有喺相關同適當時先提醒我哋。 - Agent 喺任何裝置或平台上都容易被授權用戶發現同使用。 - Agent 支援多模態輸入同輸出(聲音、語音、文字等)。 - Agent 可以喺前景同背景之間無縫切換;喺主動同被動模式之間切換,根據用戶需求進行感知。 - Agent 可能以隱形形式運作,但其背景處理路徑同與其他 Agents 嘅協作對用戶係透明同可控嘅。 ### Agent(時間) 呢個係 agent 喺時間上點樣運作。呢啲原則指導我哋點樣設計 agents 喺過去、現在同未來進行互動。 - **過去**:回顧包括狀態同上下文喺內嘅歷史。 - Agent 基於更豐富嘅歷史數據分析提供更相關嘅結果,而唔係只係事件、人或者狀態。 - Agent 由過去事件建立連接,並主動反思記憶以應對當前情況。 - **現在**:更多係提示,而唔係通知。 - Agent 採用全面嘅方式與人互動。當事件發生時,Agent 唔只係靜態通知或者其他形式化提醒。Agent 可以簡化流程或者動態生成提示,喺正確嘅時刻引導用戶注意力。 - Agent 根據上下文環境、社會同文化變化,以及用戶意圖,提供信息。 - Agent 嘅互動可以係漸進式嘅,隨住時間增長逐步提升複雜性,從而長期賦能用戶。 - **未來**:適應同進化。 - Agent 可以適應各種裝置、平台同模態。 - Agent 適應用戶行為、無障礙需求,並且可以自由定制。 - Agent 通過持續嘅用戶互動塑造同進化。 ### Agent(核心) 呢啲係 agent 設計核心嘅關鍵元素。 - **接受不確定性,但建立信任**。 - 一定程度嘅 Agent 不確定性係可以接受嘅。不確定性係 agent 設計嘅一個關鍵元素。 - 信任同透明係 Agent 設計嘅基石。 - 人類控制住 Agent 嘅開啟/關閉狀態,並且 Agent 狀態隨時清晰可見。 ## 實施呢啲原則嘅指引 當你使用上述設計原則時,請遵守以下指引: 1. **透明性**:通知用戶 AI 嘅參與,解釋佢點樣運作(包括過往行為),以及點樣提供反饋同修改系統。 2. **控制**:讓用戶可以定制、指定偏好同個性化,並對系統同其屬性擁有控制權(包括忘記功能)。 3. **一致性**:確保喺裝置同端點之間提供一致、多模態嘅體驗。盡可能使用熟悉嘅 UI/UX 元素(例如:用麥克風圖標表示語音互動),並儘量減低用戶嘅認知負擔(例如:提供簡潔嘅回應、視覺輔助同“了解更多”內容)。 ## 如何用呢啲原則同指引設計旅遊 Agent 假設你喺設計一個旅遊 Agent,可以咁樣運用設計原則同指引: 1. **透明性** – 讓用戶知道旅遊 Agent 係一個 AI 支援嘅 Agent。提供一啲基本指引,教用戶點樣開始(例如:“Hello” 信息、示例提示)。喺產品頁面清楚記錄呢啲資訊。展示用戶過去問過嘅提示列表。清楚說明點樣提供反饋(例如:讚好/踩低按鈕、發送反饋按鈕等)。明確講解 Agent 是否有使用或主題限制。 2. **控制** – 確保用戶清楚點樣喺創建 Agent 後修改,例如使用 System Prompt。讓用戶選擇 Agent 嘅詳細程度、寫作風格,以及 Agent 唔應該討論嘅內容。允許用戶查看同刪除任何相關文件或數據、提示同過去嘅對話。 3. **一致性** – 確保“分享提示”、“添加文件或圖片”同“標記某人或某物”嘅圖標係標準同易於識別嘅。用迴紋針圖標表示文件上傳/共享,用圖片圖標表示圖片上傳。 ## 其他資源 - [Practices for Governing Agentic AI Systems | OpenAI](https://openai.com) - [The HAX Toolkit Project - Microsoft Research](https://microsoft.com) - [Responsible AI Toolbox](https://responsibleaitoolbox.ai) **免責聲明**: 本文件已使用機器翻譯人工智能服務進行翻譯。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件作為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或誤釋不承擔責任。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/03-agentic-design-patterns/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/03-agentic-design-patterns/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 2797 }
# 工具使用設計模式 ## 簡介 喺呢堂課,我哋會解答以下問題: - 咩係工具使用設計模式? - 呢個模式適用於咩場景? - 實現呢個設計模式需要嘅元素/組成部分係咩? - 喺建立可信賴嘅AI代理時,使用工具使用設計模式需要注意啲咩特別事項? ## 學習目標 完成呢堂課之後,你將能夠: - 定義工具使用設計模式及其目的。 - 識別適用工具使用設計模式嘅場景。 - 理解實現呢個設計模式所需嘅關鍵元素。 - 認識使用呢個設計模式時,確保AI代理可信賴嘅考量。 ## 咩係工具使用設計模式? **工具使用設計模式**重點喺俾大型語言模型(LLMs)能夠與外部工具互動,以達到特定目標。工具係由代理執行嘅代碼,佢可以係一個簡單嘅函數,例如計算機,亦可以係第三方服務嘅API調用,例如股票價格查詢或者天氣預報。喺AI代理嘅背景下,工具係設計俾代理響應**模型生成嘅函數調用**而執行。 ## 呢個模式適用於咩場景? AI代理可以利用工具完成複雜任務、檢索信息或者做決策。工具使用設計模式通常應用喺需要動態與外部系統交互嘅場景,例如數據庫、網絡服務或者代碼解釋器。呢種能力對多種場景都好有用,包括: - **動態信息檢索:** 代理可以查詢外部API或者數據庫,獲取最新數據(例如查詢SQLite數據庫進行數據分析、獲取股票價格或者天氣信息)。 - **代碼執行與解釋:** 代理可以執行代碼或者腳本,解決數學問題、生成報告或者進行模擬。 - **工作流自動化:** 通過集成工具(例如任務調度器、電子郵件服務或者數據管道),自動化重複或者多步驟工作流。 - **客戶支持:** 代理可以與CRM系統、工單平台或者知識庫互動,解答用戶問題。 - **內容生成與編輯:** 代理可以利用工具,例如語法檢查器、文本摘要生成器或者內容安全評估工具,協助完成內容創建任務。 ## 實現工具使用設計模式需要嘅元素/組成部分係咩? ### 函數/工具調用 函數調用係俾大型語言模型(LLMs)與工具互動嘅主要方式。你可能會見到「函數」同「工具」互換使用,因為「函數」(可重用嘅代碼塊)就係代理用嚟執行任務嘅「工具」。為咗讓函數嘅代碼可以被調用,LLM需要將用戶請求同函數嘅描述進行比較。為咗做到呢點,一個包含所有可用函數描述嘅結構(schema)會被發送俾LLM。然後,LLM會選擇最適合嘅函數,返回佢嘅名稱同參數。被選中嘅函數會被執行,佢嘅回應會再返俾LLM,然後LLM利用呢啲信息回應用戶請求。 開發者想為代理實現函數調用,需要: 1. 一個支持函數調用嘅LLM模型 2. 一個包含函數描述嘅結構(schema) 3. 每個描述中提到嘅函數代碼 用一個查詢城市當前時間嘅例子嚟說明: - **初始化支持函數調用嘅LLM:** 唔係所有模型都支持函數調用,所以確認你用嘅LLM支持呢個功能好重要。[Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling)支持函數調用。我哋可以由初始化Azure OpenAI客戶端開始。 ```python # Initialize the Azure OpenAI client client = AzureOpenAI( azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), api_version="2024-05-01-preview" ) ``` - **創建函數結構(Schema):** 接住,我哋會定義一個JSON結構,包含函數名稱、函數用途嘅描述,以及函數參數嘅名稱同描述。 然後,我哋會將呢個結構同用戶請求一齊傳俾之前創建嘅客戶端,請求查詢三藩市嘅時間。需要注意嘅係,返回嘅係**工具調用**,而唔係問題嘅最終答案。如之前提到,LLM返回咗佢為任務選擇嘅函數名稱同將會傳遞俾函數嘅參數。 ```python # Function description for the model to read tools = [ { "type": "function", "function": { "name": "get_current_time", "description": "Get the current time in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city name, e.g. San Francisco", }, }, "required": ["location"], }, } } ] ``` ```python # Initial user message messages = [{"role": "user", "content": "What's the current time in San Francisco"}] # First API call: Ask the model to use the function response = client.chat.completions.create( model=deployment_name, messages=messages, tools=tools, tool_choice="auto", ) # Process the model's response response_message = response.choices[0].message messages.append(response_message) print("Model's response:") print(response_message) ``` ```bash Model's response: ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')]) ``` - **執行任務所需嘅函數代碼:** 而家LLM已經選擇咗需要運行嘅函數,接住就需要實現並執行完成任務嘅代碼。 我哋可以用Python實現查詢當前時間嘅代碼。同時,我哋亦需要編寫代碼,從response_message中提取名稱同參數以獲取最終結果。 ```python def get_current_time(location): """Get the current time for a given location""" print(f"get_current_time called with location: {location}") location_lower = location.lower() for key, timezone in TIMEZONE_DATA.items(): if key in location_lower: print(f"Timezone found for {key}") current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p") return json.dumps({ "location": location, "current_time": current_time }) print(f"No timezone data found for {location_lower}") return json.dumps({"location": location, "current_time": "unknown"}) ``` ```python # Handle function calls if response_message.tool_calls: for tool_call in response_message.tool_calls: if tool_call.function.name == "get_current_time": function_args = json.loads(tool_call.function.arguments) time_response = get_current_time( location=function_args.get("location") ) messages.append({ "tool_call_id": tool_call.id, "role": "tool", "name": "get_current_time", "content": time_response, }) else: print("No tool calls were made by the model.") # Second API call: Get the final response from the model final_response = client.chat.completions.create( model=deployment_name, messages=messages, ) return final_response.choices[0].message.content ``` ```bash get_current_time called with location: San Francisco Timezone found for san francisco The current time in San Francisco is 09:24 AM. ``` 函數調用係大部分(如果唔係全部)代理工具使用設計嘅核心,但從零開始實現有時會有挑戰。 正如我哋喺[第二課](../../../02-explore-agentic-frameworks)學到,代理框架為我哋提供咗預構建嘅組件,方便實現工具使用。 ### 使用代理框架嘅工具使用例子 - ### **[Semantic Kernel](https://learn.microsoft.com/azure/ai-services/agents/overview)** Semantic Kernel係一個開源嘅AI框架,適合用.NET、Python同Java開發大型語言模型(LLMs)嘅開發者。佢透過一個叫做[序列化](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions)嘅過程,自動將你嘅函數同參數描述傳遞俾模型,簡化咗使用函數調用嘅過程。佢仲處理模型同你代碼之間嘅雙向通信。使用代理框架例如Semantic Kernel嘅另一個好處係,你可以訪問預構建嘅工具,例如[文件搜索](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step4_assistant_tool_file_search.py)同[代碼解釋器](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py)。 以下圖解展示咗使用Semantic Kernel進行函數調用嘅過程: ![函數調用](../../../translated_images/functioncalling-diagram.b5493ea5154ad8e3e4940d2e36a49101eec1398948e5d1039942203b4f5a4209.hk.png) 喺Semantic Kernel中,函數/工具被稱為[插件](https://learn.microsoft.com/semantic-kernel/concepts/plugins/?pivots=programming-language-python)。我哋可以將`get_current_time` function we saw earlier into a plugin by turning it into a class with the function in it. We can also import the `kernel_function`裝飾器,加入函數描述。當你用GetCurrentTimePlugin創建內核時,內核會自動序列化函數同佢嘅參數,喺呢個過程中創建結構發送俾LLM。 ```python from semantic_kernel.functions import kernel_function class GetCurrentTimePlugin: async def __init__(self, location): self.location = location @kernel_function( description="Get the current time for a given location" ) def get_current_time(location: str = ""): ... ``` ```python from semantic_kernel import Kernel # Create the kernel kernel = Kernel() # Create the plugin get_current_time_plugin = GetCurrentTimePlugin(location) # Add the plugin to the kernel kernel.add_plugin(get_current_time_plugin) ``` - ### **[Azure AI Agent Service](https://learn.microsoft.com/azure/ai-services/agents/overview)** Azure AI Agent Service係一個較新嘅代理框架,旨喺幫助開發者安全地構建、部署同擴展高質量同可擴展嘅AI代理,而唔需要管理底層嘅計算同存儲資源。呢個框架對企業應用特別有用,因為佢係一個完全託管嘅服務,並提供企業級別嘅安全性。 同直接用LLM API開發相比,Azure AI Agent Service提供咗以下優勢: - 自動工具調用——唔需要解析工具調用、調用工具同處理回應;呢啲全部都喺服務端完成 - 安全管理數據——唔需要自行管理會話狀態,可以依賴threads存儲所需嘅所有信息 - 預構建工具——可以用嚟與數據源交互嘅工具,例如Bing、Azure AI Search同Azure Functions。 Azure AI Agent Service提供嘅工具可以分為兩類: 1. 知識工具: - [使用Bing Search進行信息補充](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview) - [文件搜索](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/file-search?tabs=python&pivots=overview) - [Azure AI Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search) 2. 行動工具: - [函數調用](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/function-calling?tabs=python&pivots=overview) - [代碼解釋器](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/code-interpreter?tabs=python&pivots=overview) - [OpenAI定義嘅工具](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/openapi-spec?tabs=python&pivots=overview) - [Azure Functions](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-functions?pivots=overview) Agent Service允許我哋將呢啲工具作為一個`toolset`. It also utilizes `threads` which keep track of the history of messages from a particular conversation. Imagine you are a sales agent at a company called Contoso. You want to develop a conversational agent that can answer questions about your sales data. The image below illustrates how you could use Azure AI Agent Service to analyze your sales data: ![Agentic Service In Action](../../../translated_images/agent-service-in-action.8c2d8aa8e9d91feeb29549b3fde529f8332b243875154d03907616a69198afbc.hk.jpg?WT.mc_id=academic-105485-koreyst) To use any of these tools with the service we can create a client and define a tool or toolset. To implement this practically we can use the Python code below. The LLM will be able to look at the toolset and decide whether to use the user created function, `fetch_sales_data_using_sqlite_query`,或者根據用戶請求使用預構建嘅代碼解釋器。 ```python import os from azure.ai.projects import AIProjectClient from azure.identity import DefaultAzureCredential from fecth_sales_data_functions import fetch_sales_data_using_sqlite_query # fetch_sales_data_using_sqlite_query function which can be found in a fecth_sales_data_functions.py file. from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool project_client = AIProjectClient.from_connection_string( credential=DefaultAzureCredential(), conn_str=os.environ["PROJECT_CONNECTION_STRING"], ) # Initialize function calling agent with the fetch_sales_data_using_sqlite_query function and adding it to the toolset fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query) toolset = ToolSet() toolset.add(fetch_data_function) # Initialize Code Interpreter tool and adding it to the toolset. code_interpreter = code_interpreter = CodeInterpreterTool() toolset = ToolSet() toolset.add(code_interpreter) agent = project_client.agents.create_agent( model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent", toolset=toolset ) ``` ## 使用工具使用設計模式構建可信AI代理需要注意啲咩特別事項? 使用LLM動態生成嘅SQL通常會引起安全問題,特別係SQL注入或者惡意操作(例如刪除或者篡改數據庫)嘅風險。雖然呢啲擔憂係合理嘅,但可以通過正確配置數據庫訪問權限有效減輕呢啲風險。對於大多數數據庫,呢個過程包括將數據庫設置為只讀模式。對於例如PostgreSQL或者Azure SQL嘅數據庫服務,應該為應用程序分配只讀(SELECT)角色。 喺安全環境中運行應用程序可以進一步增強保護。喺企業場景中,數據通常會從運營系統中提取並轉換到只讀數據庫或者數據倉庫,並具有用戶友好嘅結構。呢個方法可以確保數據安全,並優化性能同可訪問性,同時限制應用程序只有只讀訪問權限。 ## 其他資源 - [Azure AI Agents Service Workshop](https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/) - [Contoso Creative Writer Multi-Agent Workshop](https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop) - [Semantic Kernel Function Calling Tutorial](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions) - [Semantic Kernel Code Interpreter](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py) - [Autogen Tools](https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html) ``` **免責聲明**: 本文件是使用機器翻譯人工智能服務進行翻譯的。我們雖然努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文文件作為權威來源。對於關鍵信息,建議尋求專業人工翻譯。我們對因使用本翻譯而產生的任何誤解或錯誤解讀概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/04-tool-use/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/04-tool-use/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 12308 }
# 主動式 RAG 本課程為你提供一個全面的介紹,了解主動式檢索增強生成(Agentic RAG),這是一種新興的人工智能模式,讓大型語言模型(LLMs)能自主規劃下一步行動,同時從外部數據源獲取資訊。與傳統的靜態檢索-閱讀模式不同,主動式 RAG 涉及到多次迭代地調用 LLM,穿插使用工具或函數調用,並生成結構化的輸出。系統會評估結果,改進查詢,必要時調用額外工具,並重複這個過程,直到找到滿意的解決方案為止。 ## 課程介紹 本課程將涵蓋以下內容: - **理解主動式 RAG:** 學習這種新興的 AI 模式,讓大型語言模型(LLMs)能自主規劃下一步行動,同時從外部數據源中提取資訊。 - **掌握迭代式 Maker-Checker 模式:** 理解這種迭代調用 LLM 的循環過程,穿插工具或函數調用和結構化輸出,旨在提升正確性並處理不良查詢。 - **探索實際應用:** 確定主動式 RAG 的適用場景,例如以正確性為優先的環境、複雜的數據庫交互以及長期工作流程。 ## 學習目標 完成本課程後,你將了解以下內容: - **理解主動式 RAG:** 學習這種新興的 AI 模式,讓大型語言模型(LLMs)能自主規劃下一步行動,同時從外部數據源中提取資訊。 - **迭代式 Maker-Checker 模式:** 掌握這種迭代調用 LLM 的概念,穿插工具或函數調用和結構化輸出,旨在提升正確性並處理不良查詢。 - **掌控推理過程:** 理解系統如何自主掌控推理過程,決定如何處理問題,而不是依賴預定的路徑。 - **工作流程:** 理解主動模型如何自主決定檢索市場趨勢報告、識別競爭對手數據、關聯內部銷售數據、綜合結論並評估策略。 - **迭代循環、工具整合與記憶:** 學習系統如何依賴迴圈交互模式,跨步驟維持狀態和記憶,避免重複循環並做出更明智的決策。 - **處理失敗模式與自我糾正:** 探索系統的自我糾正機制,包括迭代與重新查詢、使用診斷工具以及在必要時依賴人工監督。 - **代理邊界:** 理解主動式 RAG 的限制,聚焦於特定領域的自主性、基礎設施依賴性以及遵守安全規範。 - **實際使用案例與價值:** 確定主動式 RAG 的適用場景,例如以正確性為優先的環境、複雜的數據庫交互以及長期工作流程。 - **治理、透明性與信任:** 學習治理與透明性的必要性,包括可解釋的推理、偏見控制以及人工監督。 ## 什麼是主動式 RAG? 主動式檢索增強生成(Agentic RAG)是一種新興的 AI 模式,讓大型語言模型(LLMs)能自主規劃下一步行動,同時從外部數據源中提取資訊。與靜態的檢索-閱讀模式不同,主動式 RAG 涉及到多次迭代地調用 LLM,穿插工具或函數調用和結構化輸出。系統會評估結果,改進查詢,必要時調用額外工具,並重複這個過程,直到找到滿意的解決方案為止。 這種迭代的 “Maker-Checker” 操作方式提升了正確性,能處理結構化數據庫(例如 NL2SQL)中的不良查詢,並確保高質量的結果。系統主動掌控其推理過程,能重寫失敗的查詢,選擇不同的檢索方法,並整合多種工具,例如 Azure AI Search 的向量檢索、SQL 數據庫或自定義 API,在最終給出答案之前。主動式系統的顯著特點是它能掌控推理過程。傳統的 RAG 實現依賴於預定的路徑,而主動式系統能自主根據所獲得的資訊質量來決定步驟順序。 ## 定義主動式檢索增強生成(Agentic RAG) 主動式檢索增強生成(Agentic RAG)是一種新興的 AI 開發模式,讓 LLMs 不僅能從外部數據源中提取資訊,還能自主規劃下一步行動。與靜態的檢索-閱讀模式或精心設計的提示序列不同,主動式 RAG 涉及到一個迭代循環,調用 LLM,穿插工具或函數調用和結構化輸出。每一步,系統都會評估已獲得的結果,決定是否需要改進查詢,必要時調用額外工具,並持續這個循環,直到找到滿意的解決方案。 這種迭代的 “Maker-Checker” 操作方式旨在提升正確性,處理結構化數據庫(例如 NL2SQL)中的不良查詢,並確保平衡且高質量的結果。系統不僅依賴於精心設計的提示鏈,還能主動掌控推理過程。它能重寫失敗的查詢,選擇不同的檢索方法,並整合多種工具,例如 Azure AI Search 的向量檢索、SQL 數據庫或自定義 API,在最終給出答案之前。這消除了對過於複雜的編排框架的需求。相反,一個相對簡單的循環 “LLM 調用 → 工具使用 → LLM 調用 → …” 就能產生精細且有根據的輸出。 ![Agentic RAG 核心循環](../../../translated_images/agentic-rag-core-loop.2224925a913fb3439f518bda61a40096ddf6aa432a11c9b5bba8d0d625e47b79.hk.png) ## 掌控推理過程 讓系統成為 “主動式” 的關鍵特質在於它能掌控推理過程。傳統的 RAG 實現通常依賴於人類預先定義的模型路徑:一條明確的思路,指導模型應該檢索什麼以及何時檢索。但當系統真正實現主動性時,它能內部決定如何處理問題。這不僅僅是執行一個腳本,而是自主根據所找到的資訊質量決定步驟順序。 例如,如果被要求制定一個產品上市策略,主動式模型不會僅僅依賴於一個明確指出整個研究和決策流程的提示。相反,主動模型會自主決定: 1. 使用 Bing Web Grounding 檢索當前市場趨勢報告。 2. 使用 Azure AI Search 識別相關的競爭對手數據。 3. 使用 Azure SQL Database 關聯歷史內部銷售數據。 4. 通過 Azure OpenAI Service 將發現綜合成一個連貫的策略。 5. 評估該策略是否存在差距或不一致之處,必要時啟動另一輪檢索。 所有這些步驟——改進查詢、選擇來源、迭代直到對答案“滿意”——都是由模型決定的,而不是由人類預先編寫的腳本。 ## 迭代循環、工具整合與記憶 ![工具整合架構](../../../translated_images/tool-integration.7b05a923e3278bf1fd2972faa228fb2ac725f166ed084362b031a24bffd26287.hk.png) 主動式系統依賴於一個迴圈交互模式: - **初始調用:** 用戶的目標(即用戶提示)被呈現給 LLM。 - **工具調用:** 如果模型發現資訊不足或指令不明確,它會選擇一個工具或檢索方法,例如向量數據庫查詢(如 Azure AI Search 的混合檢索私有數據)或結構化 SQL 調用,以獲取更多上下文。 - **評估與改進:** 在審查返回的數據後,模型會決定該資訊是否足夠。如果不夠,它會改進查詢,嘗試不同的工具或調整方法。 - **重複直到滿意:** 這個循環會持續進行,直到模型認為它有足夠的清晰度和證據來提供最終的、經過深思熟慮的回應。 - **記憶與狀態:** 系統會在各步驟間維持狀態和記憶,因此能回憶起先前的嘗試及其結果,避免重複循環並在過程中做出更明智的決策。 隨著時間的推移,這種方式會創造一種不斷演進的理解,讓模型能在沒有人工持續干預或重塑提示的情況下,完成複雜的多步驟任務。 ## 處理失敗模式與自我糾正 主動式 RAG 的自主性還包含了強大的自我糾正機制。當系統遇到瓶頸(例如檢索到不相關的文件或遇到不良查詢)時,它可以: - **迭代與重新查詢:** 與其返回低價值的回應,模型會嘗試新的搜索策略,重寫數據庫查詢或尋找替代數據集。 - **使用診斷工具:** 系統可能調用額外的功能來幫助其調試推理步驟或確認檢索數據的正確性。像 Azure AI Tracing 這樣的工具對於實現強大的可觀測性和監控至關重要。 - **依賴人工監督:** 對於高風險或持續失敗的場景,模型可能會標記不確定性並請求人工指導。一旦人類提供了糾正意見,模型可以將其納入以後的學習。 這種迭代和動態的方法讓模型能不斷改進,確保它不僅僅是一個一次性的系統,而是一個在特定會話期間從錯誤中學習的系統。 ![自我糾正機制](../../../translated_images/self-correction.3d42c31baf4a476bb89313cec58efb196b0e97959c04d7439cc23d27ef1242ac.hk.png) ## 主動性邊界 儘管在任務內部具備自主性,主動式 RAG 並不等同於通用人工智能。它的“主動性”能力局限於人類開發者提供的工具、數據源和政策。它無法創建自己的工具,也無法超出設定的領域範圍。相反,它在動態協調現有資源方面表現出色。 主要與更高級 AI 形式的區別包括: 1. **領域特定的自主性:** 主動式 RAG 系統專注於在已知領域內實現用戶定義的目標,通過查詢重寫或工具選擇等策略來改善結果。 2. **依賴基礎設施:** 系統的能力取決於開發者整合的工具和數據。沒有人工干預,它無法超越這些邊界。 3. **遵守安全規範:** 道德指導方針、合規規則和商業政策仍然非常重要。代理的自由度始終受到安全措施和監督機制的約束(希望如此)。 ## 實際使用案例與價值 主動式 RAG 在需要迭代改進和精準度的場景中表現出色: 1. **正確性優先的環境:** 在合規檢查、法規分析或法律研究中,主動模型可以反覆驗證事實,查閱多個來源,並重寫查詢,直到產生經過徹底驗證的答案。 2. **複雜的數據庫交互:** 在處理結構化數據時,查詢可能經常失敗或需要調整,系統可以自主使用 Azure SQL 或 Microsoft Fabric OneLake 改進查詢,確保最終檢索符合用戶意圖。 3. **長期工作流程:** 當新的資訊不斷出現時,長期會話可能會發生變化。主動式 RAG 可以持續整合新數據,隨著對問題空間的理解加深而調整策略。 ## 治理、透明性與信任 隨著這些系統在推理方面變得越來越自主,治理和透明性至關重要: - **可解釋的推理:** 模型可以提供查詢記錄、所查閱的來源以及其得出結論的推理步驟。像 Azure AI Content Safety 和 Azure AI Tracing / GenAIOps 這樣的工具可以幫助保持透明性並降低風險。 - **偏見控制與平衡檢索:** 開發者可以調整檢索策略,確保考慮到平衡且具有代表性的數據來源,並定期審核輸出以檢測偏見或不均衡模式,使用 Azure Machine Learning 為進階數據科學組織提供自定義模型。 - **人工監督與合規性:** 對於敏感任務,人工審查仍然是必要的。主動式 RAG 並不會取代高風險決策中的人類判斷,而是通過提供經過更徹底驗證的選項來輔助人類。 擁有能提供清晰行動記錄的工具至關重要。沒有這些工具,調試多步驟過程可能會非常困難。以下是 Literal AI(Chainlit 背後的公司)提供的 Agent 運行範例: ![AgentRunExample](../../../translated_images/AgentRunExample.27e2df23ad898772d1b3e7a3e3cd4615378e10dfda87ae8f06b4748bf8eea97d.hk.png) ![AgentRunExample2](../../../translated_images/AgentRunExample2.c0e8c78b1f2540a641515e60035abcc6a9c5e3688bae143eb6c559dd37cdee9f.hk.png) ## 結論 主動式 RAG 代表了 AI 系統在處理複雜且數據密集型任務方面的一種自然進化。通過採用迴圈交互模式,自主選擇工具,並改進查詢直到達成高質量結果,系統超越了靜態的提示執行,成為更具適應性和上下文感知的決策者。儘管仍受限於人類定義的基礎設施和道德指導方針,但這些主動性能力使企業和最終用戶能夠享受到更豐富、更動態、也更有用的 AI 互動。 ## 其他資源 - 使用 Azure OpenAI Service 實現檢索增強生成(RAG):學習如何使用自己的數據與 Azure OpenAI Service。[這個 Microsoft Learn 模組提供了實現 RAG 的全面指南](https://learn.microsoft.com/training/modules/use-own-data-azure-openai) - 使用 Azure AI Foundry 評估生成式 AI 應用:本文涵蓋了基於公開數據集的模型評估與比較,包括[主動式 AI 應用和 RAG 架構](https://learn.microsoft.com/azure/ai-studio/concepts/evaluation-approach-gen-ai) - [什麼是主動式 RAG | Weaviate](https://weaviate.io/blog/what-is-agentic-rag) - [主動式 RAG:一份關於基於代理的檢索增強生成的完整指南 – generation RAG 的新聞](https://ragaboutit.com/agentic-rag-a-complete-guide-to-agent-based-retrieval-augmented-generation/) - [主動式 RAG:使用查詢重構和自查詢為你的 RAG 提速! Hugging Face 開源 AI 手冊](https://huggingface.co/learn/cookbook/agent_rag) - [為 RAG 添加主動層](https://youtu.be/aQ4yQXeB1Ss?si=2HUqBzHoeB5tR04U) - [知識助理的未來:Jerry Liu](https://www.youtube.com/watch?v=zeAyuLc_f3Q&t=244s) - [如何構建主動式 RAG 系統](https://www.youtube.com/watch?v=AOSjiXP1jmQ) - [使用 Azure AI Foundry Agent Service 擴展你的 AI 代理](https://ignite.microsoft.com/sessions/BRK102?source=sessions) ### 學術論文 - [2303.17651 Self-Refine: Iterative Refinement with Self-Feedback](https://arxiv.org/abs/2303.17651) - [2303.11366 Reflexion: Language Agents with Verbal Reinforcement Learning](https://arxiv.org/ **免責聲明**: 此文件使用機器人工智能翻譯服務進行翻譯。雖然我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文作為權威來源。對於關鍵信息,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或錯誤解釋概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/05-agentic-rag/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/05-agentic-rag/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 6419 }
# 建立值得信賴的人工智能代理 ## 簡介 本課程將涵蓋: - 如何構建和部署安全且有效的人工智能代理 - 開發人工智能代理時的重要安全考量 - 如何在開發人工智能代理時維護數據和用戶隱私 ## 學習目標 完成本課程後,您將能夠: - 識別並減輕創建人工智能代理時的風險 - 實施安全措施,確保數據和訪問得到妥善管理 - 創建能維護數據隱私並提供優質用戶體驗的人工智能代理 ## 安全性 首先,我們來探討如何構建安全的代理應用程序。安全性意味著人工智能代理按照設計執行。作為代理應用程序的開發者,我們擁有一些方法和工具來最大化安全性: ### 構建元提示系統 如果您曾經使用大型語言模型(LLMs)構建人工智能應用程序,那麼您應該知道設計一個健全的系統提示或系統消息有多麼重要。這些提示確立了元規則、指令和指南,指導LLM如何與用戶和數據互動。 對於人工智能代理來說,系統提示更加重要,因為這些代理需要非常具體的指令來完成我們為其設計的任務。 為了創建可擴展的系統提示,我們可以使用元提示系統來構建我們應用中的一個或多個代理: ![構建元提示系統](../../../translated_images/building-a-metaprompting-system.aa7d6de2100b0ef48c3e1926dab6903026b22fc9d27fc4327162fbbb9caf960f.hk.png) #### 第一步:創建元提示或模板提示 元提示將由LLM用於生成我們創建的代理的系統提示。我們將其設計為模板,以便在需要時能有效地創建多個代理。 以下是一個我們會給LLM的元提示示例: ```plaintext You are an expert at creating AI agent assitants. You will be provided a company name, role, responsibilites and other information that you will use to provide a system prompt for. To create the system prompt, be descriptive as possible and provide a structure that a system using an LLM can better understand the role and responsibilites of the AI assistant. ``` #### 第二步:創建基本提示 下一步是創建一個基本提示來描述人工智能代理。您應該包括代理的角色、代理將完成的任務以及代理的其他職責。 以下是一個示例: ```plaintext You are a travel agent for Contoso Travel with that is great at booking flights for customers. To help customers you can perform the following tasks: lookup available flights, book flights, ask for preferences in seating and times for flights, cancel any previously booked flights and alert customers on any delays or cancellations of flights. ``` #### 第三步:向LLM提供基本提示 現在,我們可以將元提示作為系統提示,並提供我們的基本提示來優化這個過程。 這將生成一個更適合指導我們人工智能代理的提示: ```markdown **Company Name:** Contoso Travel **Role:** Travel Agent Assistant **Objective:** You are an AI-powered travel agent assistant for Contoso Travel, specializing in booking flights and providing exceptional customer service. Your main goal is to assist customers in finding, booking, and managing their flights, all while ensuring that their preferences and needs are met efficiently. **Key Responsibilities:** 1. **Flight Lookup:** - Assist customers in searching for available flights based on their specified destination, dates, and any other relevant preferences. - Provide a list of options, including flight times, airlines, layovers, and pricing. 2. **Flight Booking:** - Facilitate the booking of flights for customers, ensuring that all details are correctly entered into the system. - Confirm bookings and provide customers with their itinerary, including confirmation numbers and any other pertinent information. 3. **Customer Preference Inquiry:** - Actively ask customers for their preferences regarding seating (e.g., aisle, window, extra legroom) and preferred times for flights (e.g., morning, afternoon, evening). - Record these preferences for future reference and tailor suggestions accordingly. 4. **Flight Cancellation:** - Assist customers in canceling previously booked flights if needed, following company policies and procedures. - Notify customers of any necessary refunds or additional steps that may be required for cancellations. 5. **Flight Monitoring:** - Monitor the status of booked flights and alert customers in real-time about any delays, cancellations, or changes to their flight schedule. - Provide updates through preferred communication channels (e.g., email, SMS) as needed. **Tone and Style:** - Maintain a friendly, professional, and approachable demeanor in all interactions with customers. - Ensure that all communication is clear, informative, and tailored to the customer's specific needs and inquiries. **User Interaction Instructions:** - Respond to customer queries promptly and accurately. - Use a conversational style while ensuring professionalism. - Prioritize customer satisfaction by being attentive, empathetic, and proactive in all assistance provided. **Additional Notes:** - Stay updated on any changes to airline policies, travel restrictions, and other relevant information that could impact flight bookings and customer experience. - Use clear and concise language to explain options and processes, avoiding jargon where possible for better customer understanding. This AI assistant is designed to streamline the flight booking process for customers of Contoso Travel, ensuring that all their travel needs are met efficiently and effectively. ``` #### 第四步:迭代和改進 這個元提示系統的價值在於能夠更輕鬆地擴展多個代理的提示創建,同時隨著時間推移改進您的提示。很少有提示能在第一次就完全適用於您的全部使用場景。通過更改基本提示並運行它來進行小的調整和改進,您將能夠比較和評估結果。 ## 理解威脅 要構建值得信賴的人工智能代理,理解並減輕對人工智能代理的風險和威脅至關重要。我們來看看人工智能代理面臨的一些不同威脅,以及如何更好地計劃和準備應對這些威脅。 ![理解威脅](../../../translated_images/understanding-threats.f8fbe6fe11e025b3085fc91e82d975937ad1d672260a2aeed40458aa41798d0e.hk.png) ### 任務和指令 **描述:** 攻擊者試圖通過提示或操縱輸入來更改人工智能代理的指令或目標。 **緩解措施:** 執行驗證檢查和輸入過濾器,以在AI代理處理之前檢測潛在的危險提示。由於這些攻擊通常需要與代理頻繁交互,限制對話輪次也是防止此類攻擊的一種方法。 ### 訪問關鍵系統 **描述:** 如果人工智能代理可以訪問存儲敏感數據的系統和服務,攻擊者可能會破壞代理與這些服務之間的通信。這些可能是直接攻擊,也可能是通過代理間接獲取這些系統信息的嘗試。 **緩解措施:** 人工智能代理應僅基於需要訪問系統,以防止此類攻擊。代理與系統之間的通信也應該是安全的。實施身份驗證和訪問控制是保護這些信息的另一種方法。 ### 資源和服務過載 **描述:** 人工智能代理可以訪問不同的工具和服務來完成任務。攻擊者可能利用這一能力,通過人工智能代理發送大量請求來攻擊這些服務,可能導致系統故障或高成本。 **緩解措施:** 實施策略以限制人工智能代理向服務發出的請求數量。限制與人工智能代理的對話輪次和請求次數是防止此類攻擊的另一種方法。 ### 知識庫污染 **描述:** 這種攻擊不是直接針對人工智能代理,而是針對代理將使用的知識庫和其他服務。這可能涉及破壞代理將用於完成任務的數據或信息,導致對用戶的偏頗或非預期回應。 **緩解措施:** 定期驗證人工智能代理在工作流中使用的數據。確保對這些數據的訪問是安全的,並且只有受信任的人員才能更改,以避免此類攻擊。 ### 錯誤傳播 **描述:** 人工智能代理訪問各種工具和服務來完成任務。攻擊者引發的錯誤可能導致與人工智能代理連接的其他系統失效,使攻擊範圍擴大且更難排查。 **緩解措施:** 一種避免此問題的方法是讓人工智能代理在受限環境中運行,例如在Docker容器中執行任務,以防止直接系統攻擊。創建回退機制和重試邏輯,當某些系統響應錯誤時,可以防止更大範圍的系統故障。 ## 人工參與流程 另一種構建值得信賴的人工智能代理系統的有效方法是使用人工參與流程。這創建了一個流程,用戶可以在代理運行過程中提供反饋。用戶本質上成為多代理系統中的一個代理,通過批准或終止運行過程來進行干預。 ![人工參與流程](../../../translated_images/human-in-the-loop.e9edbe8f6d42041b4213421410823250aa750fe8bdba5601d69ed46f3ff6489d.hk.png) 以下是使用AutoGen展示如何實現這一概念的代碼片段: ```python # Create the agents. model_client = OpenAIChatCompletionClient(model="gpt-4o-mini") assistant = AssistantAgent("assistant", model_client=model_client) user_proxy = UserProxyAgent("user_proxy", input_func=input) # Use input() to get user input from console. # Create the termination condition which will end the conversation when the user says "APPROVE". termination = TextMentionTermination("APPROVE") # Create the team. team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination) # Run the conversation and stream to the console. stream = team.run_stream(task="Write a 4-line poem about the ocean.") # Use asyncio.run(...) when running in a script. await Console(stream) ``` **免責聲明**: 本文件使用機器翻譯人工智能服務進行翻譯。我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。原始語言的文件應被視為權威來源。對於關鍵信息,建議使用專業的人手翻譯。我們對因使用本翻譯而引起的任何誤解或錯誤解釋不承擔責任。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/06-building-trustworthy-agents/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/06-building-trustworthy-agents/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 6716 }
# 設計規劃 ## 簡介 呢堂課會講解以下內容: * 點樣清晰咁定義一個整體目標,並將複雜嘅任務拆解成可管理嘅細項。 * 善用結構化輸出,提供更可靠同機器可讀嘅回應。 * 採用事件驅動嘅方法,應對動態任務同突發輸入。 ## 學習目標 完成呢堂課後,你將會了解: * 點樣為 AI agent 設定清晰嘅整體目標,確保佢知道需要達成咩。 * 將複雜嘅任務分解成可管理嘅子任務,並用邏輯次序組織好。 * 為 agents 配備合適嘅工具(例如搜尋工具或數據分析工具),決定幾時同點樣使用,並處理出現嘅突發情況。 * 評估子任務嘅結果,衡量表現,並對行動進行迭代改進,以提升最終輸出。 ## 定義整體目標同拆解任務 ![定義目標同任務](../../../translated_images/defining-goals-tasks.dcc1181bbdb194704ae0fb3363371562949e8b03fd2fadc256218aaadf84a9f4.hk.png) 大部分現實世界嘅任務都太過複雜,唔可以一步完成。AI agent 需要一個簡明嘅目標嚟指導佢嘅規劃同行動。例如,考慮以下目標: "生成一個 3 日嘅旅遊行程表。" 雖然目標簡單易明,但仍然需要進一步細化。目標越清晰,agent(同人類協作者)越能專注於實現正確嘅結果,例如創建一個全面嘅行程表,包括航班選擇、酒店推薦同活動建議。 ### 任務分解 大或者複雜嘅任務可以拆分成細小、針對目標嘅子任務,咁樣會更加易處理。 以旅遊行程表為例,你可以將目標分解成以下部分: * 機票預訂 * 酒店預訂 * 汽車租賃 * 個人化設定 每個子任務可以交畀專門嘅 agents 或流程處理。例如,一個 agent 可以專注於搜尋最佳機票優惠,另一個則負責酒店預訂,等等。之後,一個協調或者“下游”agent 可以將呢啲結果整合成一個完整嘅行程表提供畀用戶。 呢種模組化嘅方法仲方便逐步改進。例如,你可以加入專門處理美食推薦或者當地活動建議嘅 agents,隨時間優化行程表。 ### 結構化輸出 大型語言模型(LLMs)可以生成結構化輸出(例如 JSON),更容易畀下游嘅 agents 或服務進一步解析同處理。呢個特別適合多 agent 嘅場景,當規劃結果生成後,可以即刻執行呢啲任務。參考呢篇 [blogpost](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/cookbook/structured-output-agent.html) 可以快速了解。 以下係一段 Python 範例代碼,展示咗一個簡單嘅規劃 agent 點樣將目標分解成子任務並生成結構化嘅計劃: ### 多 Agent 協調嘅規劃 Agent 呢個例子中,一個 Semantic Router Agent 接收用戶請求(例如,“我需要一個針對我旅行嘅酒店計劃。”)。 規劃器會: * 接收酒店計劃:規劃器根據用戶嘅信息,結合系統提示(包括可用 agent 嘅詳情),生成一個結構化嘅旅遊計劃。 * 列出 Agents 同佢哋嘅工具:agent 註冊表會保存一個 agents 嘅列表(例如航班、酒店、汽車租賃同活動),以及佢哋提供嘅功能或工具。 * 將計劃分配畀相關嘅 Agents:根據子任務數量,規劃器會直接將信息發送畀專屬 agent(單一任務情況),或者透過群組聊天管理器協調多 agent 嘅合作。 * 總結結果:最後,規劃器會將生成嘅計劃進行總結,方便理解。 以下係示例代碼展示咗呢啲步驟: ```python from pydantic import BaseModel from enum import Enum from typing import List, Optional, Union class AgentEnum(str, Enum): FlightBooking = "flight_booking" HotelBooking = "hotel_booking" CarRental = "car_rental" ActivitiesBooking = "activities_booking" DestinationInfo = "destination_info" DefaultAgent = "default_agent" GroupChatManager = "group_chat_manager" # Travel SubTask Model class TravelSubTask(BaseModel): task_details: str assigned_agent: AgentEnum # we want to assign the task to the agent class TravelPlan(BaseModel): main_task: str subtasks: List[TravelSubTask] is_greeting: bool import json import os from typing import Optional from autogen_core.models import UserMessage, SystemMessage, AssistantMessage from autogen_ext.models.openai import AzureOpenAIChatCompletionClient # Create the client with type-checked environment variables client = AzureOpenAIChatCompletionClient( azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"), model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"), api_version=os.getenv("AZURE_OPENAI_API_VERSION"), azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), api_key=os.getenv("AZURE_OPENAI_API_KEY"), ) from pprint import pprint # Define the user message messages = [ SystemMessage(content="""You are an planner agent. Your job is to decide which agents to run based on the user's request. Below are the available agents specialised in different tasks: - FlightBooking: For booking flights and providing flight information - HotelBooking: For booking hotels and providing hotel information - CarRental: For booking cars and providing car rental information - ActivitiesBooking: For booking activities and providing activity information - DestinationInfo: For providing information about destinations - DefaultAgent: For handling general requests""", source="system"), UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"), ] response = await client.create(messages=messages, extra_create_args={"response_format": TravelPlan}) # Ensure the response content is a valid JSON string before loading it response_content: Optional[str] = response.content if isinstance(response.content, str) else None if response_content is None: raise ValueError("Response content is not a valid JSON string") # Print the response content after loading it as JSON pprint(json.loads(response_content)) ``` 以上代碼嘅輸出如下,之後你可以用呢個結構化輸出分配畀 `assigned_agent`,並將旅遊計劃總結畀用戶。 ```json { "is_greeting": "False", "main_task": "Plan a family trip from Singapore to Melbourne.", "subtasks": [ { "assigned_agent": "flight_booking", "task_details": "Book round-trip flights from Singapore to Melbourne." }, { "assigned_agent": "hotel_booking", "task_details": "Find family-friendly hotels in Melbourne." }, { "assigned_agent": "car_rental", "task_details": "Arrange a car rental suitable for a family of four in Melbourne." }, { "assigned_agent": "activities_booking", "task_details": "List family-friendly activities in Melbourne." }, { "assigned_agent": "destination_info", "task_details": "Provide information about Melbourne as a travel destination." } ] } ``` 你可以喺呢度搵到包含上述代碼示例嘅 notebook:[07-autogen.ipynb](../../../07-planning-design/code_samples/07-autogen.ipynb)。 ### 迭代規劃 有啲任務需要反覆修改或者重新規劃,因為某個子任務嘅結果可能會影響下一步。例如,當 agent 發現預訂航班時數據格式出乎意料,可能需要調整策略,然後再處理酒店預訂。 另外,用戶嘅反饋(例如用戶決定佢更想搭早啲嘅航班)亦可能觸發部分重新規劃。呢種動態、迭代嘅方法可以確保最終解決方案符合現實世界嘅限制同用戶不斷變化嘅需求。 例如以下代碼: ```python from autogen_core.models import UserMessage, SystemMessage, AssistantMessage #.. same as previous code and pass on the user history, current plan messages = [ SystemMessage(content="""You are a planner agent to optimize the Your job is to decide which agents to run based on the user's request. Below are the available agents specialised in different tasks: - FlightBooking: For booking flights and providing flight information - HotelBooking: For booking hotels and providing hotel information - CarRental: For booking cars and providing car rental information - ActivitiesBooking: For booking activities and providing activity information - DestinationInfo: For providing information about destinations - DefaultAgent: For handling general requests""", source="system"), UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melboune", source="user"), AssistantMessage(content=f"Previous travel plan - {TravelPlan}", source="assistant") ] # .. re-plan and send the tasks to respective agents ``` 如果想更全面了解規劃,可以參考 Magnetic One [Blogpost](https://www.microsoft.com/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks),解釋點樣處理複雜任務。 ## 總結 喺呢篇文章中,我哋睇咗一個例子,點樣創建一個規劃器,動態選擇可用嘅 agents。規劃器嘅輸出會分解任務並分配畀 agents 執行。假設 agents 已經有執行任務所需嘅功能/工具。除此之外,你仲可以加入其他模式,例如反思、總結、輪流聊天,進一步自訂化。 ## 其他資源 * 使用 o1 推理模型喺規劃複雜任務方面表現相當先進 - TODO: 分享示例? * Autogen Magnetic One - 一個通用型多 agent 系統,用嚟解決複雜任務,喺多個挑戰性 agent 基準測試中取得咗令人印象深刻嘅結果。參考:[autogen-magentic-one](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-magentic-one)。喺呢個實現中,協調器會創建針對任務嘅計劃,並將呢啲任務分配畀可用嘅 agents。除咗規劃之外,協調器仲會用一個追蹤機制監控任務進度,並喺需要時重新規劃。 **免責聲明**: 本文件是使用機器翻譯服務進行翻譯的。我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件作為權威來源。對於關鍵資訊,建議尋求專業的人工作翻譯。我們對因使用此翻譯而引起的任何誤解或誤讀概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/07-planning-design/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/07-planning-design/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 7229 }
# 多代理設計模式 當你開始處理一個涉及多個代理的項目時,你就需要考慮多代理設計模式。然而,何時切換到多代理模式以及其優勢可能並不立刻明顯。 ## 簡介 在這一課中,我們將解答以下問題: - 哪些場景適用於多代理模式? - 為什麼使用多代理比單一代理處理多個任務更有優勢? - 實現多代理設計模式的基本構件是什麼? - 我們如何掌握多個代理之間的互動情況? ## 學習目標 完成這一課後,你應該能夠: - 辨識適用於多代理的場景。 - 認識使用多代理相較於單一代理的優勢。 - 理解實現多代理設計模式的基本構件。 更大的圖景是什麼? *多代理是一種設計模式,允許多個代理協作以實現共同目標。* 這種模式被廣泛應用於各個領域,包括機器人學、自主系統和分布式計算。 ## 適用於多代理的場景 那麼,哪些場景適合使用多代理呢?答案是,有許多情況使用多代理是有益的,特別是在以下幾種情況: - **大量工作負載**:龐大的工作負載可以被拆分為更小的任務,分配給不同的代理,從而實現並行處理並加快完成速度。例如,大型數據處理任務。 - **複雜任務**:與大量工作負載類似,複雜任務可以被分解為更小的子任務,並分配給不同的代理,每個代理專注於任務的特定方面。例如,自主車輛中,不同代理負責導航、障礙物檢測和與其他車輛通信。 - **多元專業知識**:不同代理可以擁有不同的專業知識,使其能比單一代理更有效地處理任務的不同方面。例如,在醫療領域,代理可以分別負責診斷、治療計劃和患者監控。 ## 使用多代理相較於單一代理的優勢 單一代理系統對於簡單任務可能運行良好,但對於更複雜的任務,使用多代理可以帶來幾個優勢: - **專業化**:每個代理可以專注於特定任務。單一代理缺乏專業化,可能導致在面對複雜任務時無所適從。例如,它可能執行了一個它並不擅長的任務。 - **可擴展性**:通過添加更多代理而不是讓單一代理承擔過多負載,更容易擴展系統。 - **容錯性**:如果某個代理失效,其他代理仍然可以繼續運行,從而保證系統的可靠性。 舉個例子,假設為用戶預訂旅行。單一代理系統需要處理旅行預訂過程的所有方面,從查找航班到預訂酒店和租車。為了實現這一點,單一代理需要具備處理所有這些任務的工具,這可能導致系統複雜且難以維護與擴展。而多代理系統則可以有不同的代理分別專注於查找航班、預訂酒店和租車,使系統更加模塊化、易於維護且可擴展。 這就像比較一個夫妻經營的小型旅行社與一個連鎖旅行社。夫妻店中,一個人處理所有預訂過程,而連鎖旅行社則由不同的人員分別處理預訂過程的不同部分。 ## 實現多代理設計模式的基本構件 在實現多代理設計模式之前,你需要了解構成該模式的基本構件。 讓我們通過再次查看用戶旅行預訂的例子來具體化這些構件。在這種情況下,基本構件包括: - **代理通信**:負責查找航班、預訂酒店和租車的代理需要進行通信並共享有關用戶偏好和約束的信息。你需要決定通信的協議和方法。具體來說,查找航班的代理需要與預訂酒店的代理通信,確保酒店預訂的日期與航班日期一致。這意味著代理需要共享用戶的旅行日期信息,因此你需要決定*哪些代理共享信息以及如何共享信息*。 - **協作機制**:代理需要協作以確保滿足用戶的偏好和約束。例如,用戶可能偏好靠近機場的酒店,而租車可能只能在機場提供。這意味著預訂酒店的代理需要與租車的代理協作,確保滿足用戶的偏好和約束。因此,你需要決定*代理如何協作行動*。 - **代理架構**:代理需要具備內部結構以做出決策並從與用戶的互動中學習。例如,查找航班的代理需要具備內部結構以決定向用戶推薦哪些航班。因此,你需要決定*代理如何做出決策並從與用戶的互動中學習*。例如,查找航班的代理可以使用機器學習模型,根據用戶過去的偏好推薦航班。 - **多代理互動的可視性**:你需要掌握多個代理如何互動的情況。這意味著你需要有工具和技術來跟蹤代理的活動和互動,例如日誌記錄與監控工具、可視化工具以及性能指標。 - **多代理模式**:有不同的模式可以用來實現多代理系統,比如集中式、分散式和混合式架構。你需要選擇最適合你的用例的模式。 - **人類介入**:在大多數情況下,你需要有人類介入,並需要指導代理何時尋求人類干預。例如,用戶可能要求推薦代理未建議的特定酒店或航班,或者在預訂航班或酒店之前需要確認。 ## 多代理互動的可視性 掌握多個代理如何互動非常重要。這種可視性對於調試、優化和確保整體系統的有效性至關重要。為此,你需要有工具和技術來跟蹤代理的活動和互動,例如日誌記錄與監控工具、可視化工具以及性能指標。 例如,在用戶旅行預訂的案例中,你可以有一個儀表板,顯示每個代理的狀態、用戶的偏好和約束,以及代理之間的互動。這個儀表板可以顯示用戶的旅行日期、航班代理推薦的航班、酒店代理推薦的酒店,以及租車代理推薦的租車選項。這可以讓你清楚地了解代理如何互動以及是否滿足用戶的偏好和約束。 讓我們更詳細地看看這些方面: - **日誌記錄與監控工具**:你需要記錄每個代理採取的行動。例如,一條日誌記錄可以存儲代理採取的行動、行動的時間以及行動的結果。這些信息可以用於調試、優化等。 - **可視化工具**:可視化工具可以幫助你以更直觀的方式看到代理之間的互動。例如,你可以有一個顯示代理之間信息流的圖表。這可以幫助你識別系統中的瓶頸、低效問題等。 - **性能指標**:性能指標可以幫助你跟蹤多代理系統的有效性。例如,你可以跟蹤完成任務所需的時間、每單位時間完成的任務數量,以及代理推薦的準確性。這些信息可以幫助你識別需要改進的地方並優化系統。 ## 多代理模式 讓我們深入探討一些可以用來創建多代理應用的具體模式。以下是一些值得考慮的有趣模式: ### 群組聊天 這種模式適用於創建一個多代理可以互相通信的群組聊天應用。典型的用例包括團隊協作、客戶支持和社交網絡。 在這種模式中,每個代理代表群組聊天中的一個用戶,消息通過消息協議在代理之間交換。代理可以向群組聊天發送消息、接收消息並回應其他代理的消息。 這種模式可以通過集中式架構(所有消息通過中央伺服器路由)或分散式架構(消息直接交換)實現。 ![群組聊天](../../../translated_images/multi-agent-group-chat.82d537c5c8dc833abbd252033e60874bc9d00df7193888b3377f8426449a0b20.hk.png) ### 任務交接 這種模式適用於創建一個多代理可以將任務交接給彼此的應用。 典型的用例包括客戶支持、任務管理和工作流自動化。 在這種模式中,每個代理代表工作流中的一個任務或步驟,代理可以根據預定規則將任務交接給其他代理。 ![任務交接](../../../translated_images/multi-agent-hand-off.ed4f0a5a58614a8a3e962fc476187e630a3ba309d066e460f017b503d0b84cfc.hk.png) ### 協作過濾 這種模式適用於創建一個多代理可以協作向用戶提供建議的應用。 為什麼需要多代理協作?因為每個代理可以擁有不同的專業知識,並以不同的方式為建議過程作出貢獻。 舉例來說,用戶想要獲得股市上最佳股票的建議: - **行業專家**:一個代理可能是某個特定行業的專家。 - **技術分析**:另一個代理可能是技術分析的專家。 - **基本面分析**:還有一個代理可能是基本面分析的專家。通過協作,這些代理可以為用戶提供更全面的建議。 ![建議](../../../translated_images/multi-agent-filtering.719217d169391ddb118bbb726b19d4d89ee139f960f8749ccb2400efb4d0ce79.hk.png) ## 場景:退款流程 考慮一個客戶試圖為產品獲得退款的場景,這個過程可能涉及許多代理,我們可以將其分為退款流程專用代理和可以用於其他流程的通用代理。 **退款流程專用代理**: 以下是一些可能參與退款流程的代理: - **客戶代理**:代表客戶,負責啟動退款流程。 - **賣家代理**:代表賣家,負責處理退款。 - **支付代理**:代表支付流程,負責將款項退還給客戶。 - **解決代理**:代表解決流程,負責解決退款過程中出現的問題。 - **合規代理**:代表合規流程,負責確保退款流程符合規範和政策。 **通用代理**: 這些代理可以用於業務的其他部分: - **物流代理**:代表物流流程,負責將產品退回給賣家。該代理可以用於退款流程,也可以用於購買產品的普通物流。 - **反饋代理**:代表反饋流程,負責收集客戶的反饋。反饋可以在任何時間進行,而不僅限於退款流程。 - **升級代理**:代表升級流程,負責將問題升級到更高級別的支持。這類代理可以用於任何需要升級問題的流程。 - **通知代理**:代表通知流程,負責在退款流程的各個階段向客戶發送通知。 - **分析代理**:代表分析流程,負責分析與退款流程相關的數據。 - **審核代理**:代表審核流程,負責審核退款流程以確保其正確執行。 - **報告代理**:代表報告流程,負責生成有關退款流程的報告。 - **知識代理**:代表知識流程,負責維護與退款流程相關的信息知識庫。該代理可以同時了解退款和業務的其他部分。 - **安全代理**:代表安全流程,負責確保退款流程的安全性。 - **質量代理**:代表質量流程,負責確保退款流程的質量。 上述列出了許多代理,包括退款流程專用代理以及可以用於業務其他部分的通用代理。希望這能為你在多代理系統中選擇代理提供一些靈感。 ## 作業 這一課的作業是什麼? 為客戶支持流程設計一個多代理系統。識別流程中涉及的代理、它們的角色和責任,以及它們如何互動。考慮既有針對客戶支持流程的專用代理,也有可以用於業務其他部分的通用代理。 > 在閱讀以下解答之前,先自己思考一下,可能需要的代理比你想像的更多。 > TIP: 思考客戶支持流程的不同階段,並考慮任何系統中需要的代理。 ## 解答 [解答](./solution/solution.md) ## 知識檢查 問題:什麼時候應該考慮使用多代理? - [] A1: 當你有一個小工作負載和簡單任務時。 - [] A2: 當你有一個大工作負載時。 - [] A3: 當你有一個簡單任務時。 [測驗解答](./solution/solution-quiz.md) ## 總結 在這一課中,我們探討了多代理設計模式,包括適用於多代理的場景、使用多代理相較於單一代理的優勢、實現多代理設計模式的基本構件,以及如何掌握多個代理之間的互動情況。 ## 其他資源 - [Autogen設計模式](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/design-patterns/intro.html) - [Agentic設計模式](https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/) ``` **免責聲明**: 本文件使用機器翻譯服務進行翻譯。我們致力於確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文文件作為權威來源。如涉及關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或誤讀概不負責。
{ "source": "microsoft/ai-agents-for-beginners", "title": "translations/hk/08-multi-agent/README.md", "url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/08-multi-agent/README.md", "date": "2024-11-28T10:42:52", "stars": 3317, "description": "10 Lessons to Get Started Building AI Agents", "file_size": 4872 }