diff --git a/01-introduction-to-genai/README.md b/01-introduction-to-genai/README.md index a2076b7b5..5f8c6fb93 100644 --- a/01-introduction-to-genai/README.md +++ b/01-introduction-to-genai/README.md @@ -1,12 +1,10 @@ # Introduction to Generative AI and Large Language Models -[![Introduction to Generative AI and Large Language Models](./images/01-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=36c6795a-e63c-46dd-8d69-df8bbe6e7bc9?WT.mc_id=academic-105485-koreyst) +[![Introduction to Generative AI and Large Language Models](./images/01-lesson-banner1.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson-1-gh) - +_(Click the image above to view video of this lesson)_ -*(Click the image above to view video of this lesson)* - -Generative AI is artificial intelligence capable of generating text, images and other types of content. What makes it a fantastic technology is that it democratizes AI, anyone can use it with as little as a text prompt, a sentence written in a natural language. There's no need for you to learn a language like Java or SQL to accomplish something worthwhile, all you need is to use your language, state what you want and out comes a suggestion from an AI model. The applications and impact for this is huge, you write or understand reports, write applications and much more, all in seconds. +Generative AI is artificial intelligence capable of generating text, images and other types of content. What makes it a fantastic technology is that it democratizes AI, anyone can use it with as little as a text prompt, a sentence written in a natural language. There's no need for you to learn a language like Java or SQL to accomplish something worthwhile, all you need is to use your language, state what you want and out comes a suggestion from an AI model. The applications and impact for this is huge, you write or understand reports, write applications and much more, all in seconds. In this curriculum, we’ll explore how our startup leverages generative AI to unlock new scenarios in the education world and how we address the inevitable challenges associated with the social implications of its application and the technology limitations. @@ -14,23 +12,23 @@ In this curriculum, we’ll explore how our startup leverages generative AI to u This lesson will cover: -* Introduction to the business scenario: our startup idea and mission. -* Generative AI and how we landed on the current technology landscape. -* Inner working of a large language model. -* Main capabilities and practical use cases of Large Language Models. +- Introduction to the business scenario: our startup idea and mission. +- Generative AI and how we landed on the current technology landscape. +- Inner working of a large language model. +- Main capabilities and practical use cases of Large Language Models. ## Learning Goals After completing this lesson, you will understand: -* What generative AI is and how Large Language Models work. -* How you can leverage large language models for different use cases, with a focus on education scenarios. +- What generative AI is and how Large Language Models work. +- How you can leverage large language models for different use cases, with a focus on education scenarios. -## Scenario: our educational startup +## Scenario: our educational startup -Generative Artificial Intelligence (AI) represents the pinnacle of AI technology, pushing the boundaries of what was once thought impossible. Generative AI models have several capabilities and applications, but for this curriculum we'll explore how it's revolutionizing education through a fictional startup. We'll refer to this startup as *our startup*. Our startup works in the education domain with the ambitious mission statement of +Generative Artificial Intelligence (AI) represents the pinnacle of AI technology, pushing the boundaries of what was once thought impossible. Generative AI models have several capabilities and applications, but for this curriculum we'll explore how it's revolutionizing education through a fictional startup. We'll refer to this startup as _our startup_. Our startup works in the education domain with the ambitious mission statement of -> *improving accessibility in learning, on a global scale, ensuring equitable access to education and providing personalized learning experiences to every learner, according to their needs*. +> _improving accessibility in learning, on a global scale, ensuring equitable access to education and providing personalized learning experiences to every learner, according to their needs_. Our startup team is aware we’ll not be able to achieve this goal without leveraging one of the most powerful tools of modern times – Large Language Models (LLMs). @@ -42,9 +40,9 @@ To start, let’s define some basic concepts and terminology we’ll be using th ## How did we get Generative AI? -Despite the extraordinary *hype* created lately by the announcement of generative AI models, this technology is decades in the making, with the first research efforts dating back to 60s. We're now at a point with AI having human cognitive capabilities, like conversation as shown by for example [OpenAI ChatGPT](https://openai.com/chatgpt) or [Bing Chat](https://www.microsoft.com/edge/features/bing-chat?WT.mc_id=academic-105485-koreyst), which also uses a GPT model for the web search Bing conversations. +Despite the extraordinary _hype_ created lately by the announcement of generative AI models, this technology is decades in the making, with the first research efforts dating back to 60s. We're now at a point with AI having human cognitive capabilities, like conversation as shown by for example [OpenAI ChatGPT](https://openai.com/chatgpt) or [Bing Chat](https://www.microsoft.com/edge/features/bing-chat?WT.mc_id=academic-105485-koreyst), which also uses a GPT model for the web search Bing conversations. -Backing up a bit, the very first prototypes of AI consisted of typewritten chatbots, relying on a knowledge base extracted from a group of experts and represented into a computer. The answers in the knowledge base were triggered by keywords appearing in the input text. +Backing up a bit, the very first prototypes of AI consisted of typewritten chatbots, relying on a knowledge base extracted from a group of experts and represented into a computer. The answers in the knowledge base were triggered by keywords appearing in the input text. However, it soon became clear that such approach, using typewritten chatbots, did not scale well. ### A statistical approach to AI: Machine Learning @@ -65,7 +63,7 @@ So that’s how we came to Generative AI today, which can be seen as a subset of ![AI, ML, DL and Generative AI](./images/AI-diagram.png?WT.mc_id=academic-105485-koreyst) -After decades of research in the AI field, a new model architecture – called *Transformer* – overcame the limits of RNNs, being able to get much longer sequences of text as input. Transformers are based on the attention mechanism, enabling the model to give different weights to the inputs it receives, ‘paying more attention’ where the most relevant information is concentrated, regardless of their order in the text sequence. +After decades of research in the AI field, a new model architecture – called _Transformer_ – overcame the limits of RNNs, being able to get much longer sequences of text as input. Transformers are based on the attention mechanism, enabling the model to give different weights to the inputs it receives, ‘paying more attention’ where the most relevant information is concentrated, regardless of their order in the text sequence. Most of the recent generative AI models – also known as Large Language Models (LLMs), since they work with textual inputs and outputs – are indeed based on this architecture. What’s interesting about these models – trained on a huge amount of unlabeled data from diverse sources like books, articles and websites – is that they can be adapted to a wide variety of tasks and generate grammatically correct text with a semblance of creativity. So, not only did they incredibly enhance the capacity of a machine to ‘understand’ an input text, but they enabled their capacity to generate an original response in human language. @@ -73,27 +71,27 @@ Most of the recent generative AI models – also known as Large Language Models In the next chapter we are going to explore different types of Generative AI models, but for now let’s have a look at how large language models work, with a focus on OpenAI GPT (Generative Pre-trained Transformer) models. -* **Tokenizer, text to numbers**: Large Language Models receive a text as input and generate a text as output. However, being statistical models, they work much better with numbers than text sequences. That’s why every input to the model is processed by a tokenizer, before being used by the core model. A token is a chunk of text – consisting of a variable number of characters, so the tokenizer's main task is splitting the input into an array of tokens. Then, each token is mapped with a token index, which is the integer encoding of the original text chunk. +- **Tokenizer, text to numbers**: Large Language Models receive a text as input and generate a text as output. However, being statistical models, they work much better with numbers than text sequences. That’s why every input to the model is processed by a tokenizer, before being used by the core model. A token is a chunk of text – consisting of a variable number of characters, so the tokenizer's main task is splitting the input into an array of tokens. Then, each token is mapped with a token index, which is the integer encoding of the original text chunk. ![Example of tokenization](./images/tokenizer-example.png?WT.mc_id=academic-105485-koreyst) -* **Predicting output tokens**: Given n tokens as input (with max n varying from one model to another), the model is able to predict one token as output. This token is then incorporated into the input of the next iteration, in an expanding window pattern, enabling a better user experience of getting one (or multiple) sentence as an answer. This explains why, if you ever played with ChatGPT, you might have noticed that sometimes it looks like it stops in the middle of a sentence. +- **Predicting output tokens**: Given n tokens as input (with max n varying from one model to another), the model is able to predict one token as output. This token is then incorporated into the input of the next iteration, in an expanding window pattern, enabling a better user experience of getting one (or multiple) sentence as an answer. This explains why, if you ever played with ChatGPT, you might have noticed that sometimes it looks like it stops in the middle of a sentence. -* **Selection process, probability distribution**: The output token is chosen by the model according to its probability of occurring after the current text sequence. This is because the model predicts a probability distribution over all possible ‘next tokens’, calculated based on its training. However, not always the token with the highest probability is chosen from the resulting distribution. A degree of randomness is added to this choice, in a way that the model acts in a non-deterministic fashion - we do not get the exact same output for the same input. This degree of randomness is added to simulate the process of creative thinking and it can be tuned using a model parameter called temperature. +- **Selection process, probability distribution**: The output token is chosen by the model according to its probability of occurring after the current text sequence. This is because the model predicts a probability distribution over all possible ‘next tokens’, calculated based on its training. However, not always the token with the highest probability is chosen from the resulting distribution. A degree of randomness is added to this choice, in a way that the model acts in a non-deterministic fashion - we do not get the exact same output for the same input. This degree of randomness is added to simulate the process of creative thinking and it can be tuned using a model parameter called temperature. ## How can our startup leverage Large Language Models? Now that we have a better understanding of the inner working of a large language model, let’s see some practical examples of the most common tasks they can perform pretty well, with an eye to our business scenario. -We said that the main capability of a Large Language Model is *generating a text from scratch, starting from a textual input, written in natural language*. +We said that the main capability of a Large Language Model is _generating a text from scratch, starting from a textual input, written in natural language_. But what kind of textual input and output? The input of a large language model is known as prompt, while the output is known as completion, term that refers to the model mechanism of generating the next token to complete the current input. We are going to dive deep into what is a prompt and how to design it in a way to get the most out of our model. But for now, let’s just say that a prompt may include: -* An **instruction** specifying the type of output we expect from the model. This instruction sometimes might embed some examples or some additional data. +- An **instruction** specifying the type of output we expect from the model. This instruction sometimes might embed some examples or some additional data. - 1. Summarization of an article, book, product reviews and more, along with extraction of insights from unstructured data. - - ![Example of summarization](./images/summarization-example.png?WT.mc_id=academic-105485-koreyst) + 1. Summarization of an article, book, product reviews and more, along with extraction of insights from unstructured data. + + ![Example of summarization](./images/summarization-example.png?WT.mc_id=academic-105485-koreyst)
@@ -102,20 +100,21 @@ The input of a large language model is known as prompt, while the output is know ![Example of creative writing](./images/creative-writing-example.png?WT.mc_id=academic-105485-koreyst)
- -* A **question**, asked in the form of a conversation with an agent. - + + +- A **question**, asked in the form of a conversation with an agent. + ![Example of conversation](./images/conversation-example.png?WT.mc_id=academic-105485-koreyst)
-* A chunk of **text to complete**, which implicitly is an ask for writing assistance. - +- A chunk of **text to complete**, which implicitly is an ask for writing assistance. + ![Example of text completion](./images/text-completion-example.png?WT.mc_id=academic-105485-koreyst)
-* A chunk of **code** together with the ask of explaining and documenting it, or a comment asking to generate a piece of code performing a specific task. +- A chunk of **code** together with the ask of explaining and documenting it, or a comment asking to generate a piece of code performing a specific task. ![Coding example](./images/coding-example.png?WT.mc_id=academic-105485-koreyst) @@ -127,7 +126,7 @@ Also, the output of a generative AI model is not perfect and sometimes the creat ## Assignment -Your assignment is to read up more on [generative AI](https://en.wikipedia.org/wiki/Generative_artificial_intelligence?WT.mc_id=academic-105485-koreyst) and try to identify an area where you would add generative AI today that doesn't have it. How would the impact be different from doing it the "old way", can you do something you couldn't before, or are you faster? Write a 300 word summary on what your dream AI startup would look like and include headers like "Problem", "How I would use AI", "Impact" and optionally a business plan. +Your assignment is to read up more on [generative AI](https://en.wikipedia.org/wiki/Generative_artificial_intelligence?WT.mc_id=academic-105485-koreyst) and try to identify an area where you would add generative AI today that doesn't have it. How would the impact be different from doing it the "old way", can you do something you couldn't before, or are you faster? Write a 300 word summary on what your dream AI startup would look like and include headers like "Problem", "How I would use AI", "Impact" and optionally a business plan. If you did this task, you might even be ready to apply to Microsoft's incubator, [Microsoft for Startups Founders Hub](https://www.microsoft.com/startups?WT.mc_id=academic-105485-koreyst) we offer credits for both Azure, OpenAI, mentoring and much more, check it out! @@ -141,7 +140,7 @@ What's true about large language models? A: 3, an LLM is non-deterministic, the response vary, however, you can control its variance via a temperature setting. You also shouldn't expect it to do things perfectly, it's here to do the heavy-lifting for you which often means you get a good first attempt at something that you need to gradually improve. -## Great Work! Continue the Journey +## Great Work! Continue the Journey After completing this lesson, check out our [Generative AI Learning collection](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) to continue leveling up your Generative AI knowledge! diff --git a/01-introduction-to-genai/images/01-lesson-banner1.png b/01-introduction-to-genai/images/01-lesson-banner1.png new file mode 100644 index 000000000..86d192c40 Binary files /dev/null and b/01-introduction-to-genai/images/01-lesson-banner1.png differ diff --git a/01-introduction-to-genai/translations/cn/README.md b/01-introduction-to-genai/translations/cn/README.md index bcf22a479..c78831f58 100644 --- a/01-introduction-to-genai/translations/cn/README.md +++ b/01-introduction-to-genai/translations/cn/README.md @@ -1,6 +1,6 @@ # 第一章 : 生成式人工智能和 LLMs 介绍 -[![Introduction to Generative AI and Large Language Models](../../images/01-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=36c6795a-e63c-46dd-8d69-df8bbe6e7bc9?WT.mc_id=academic-105485-koreyst) +[![Introduction to Generative AI and Large Language Models](../../images/01-lesson-banner1.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson-1-gh) _(点击该图片看本章导学视频)_ diff --git a/01-introduction-to-genai/translations/ja-jp/README.md b/01-introduction-to-genai/translations/ja-jp/README.md index 435add0aa..83ca5f893 100644 --- a/01-introduction-to-genai/translations/ja-jp/README.md +++ b/01-introduction-to-genai/translations/ja-jp/README.md @@ -1,6 +1,6 @@ # 生成 AI と大規模言語モデルの紹介 -[![Introduction to Generative AI and Large Language Models](../../images/01-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=36c6795a-e63c-46dd-8d69-df8bbe6e7bc9?WT.mc_id=academic-105485-yoterada) +[![Introduction to Generative AI and Large Language Models](./images/01-lesson-banner1.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson-1-gh) > _(上記の画像をクリックすると、レッスン・ビデオを表示します)_ diff --git a/01-introduction-to-genai/translations/ko/README.md b/01-introduction-to-genai/translations/ko/README.md index add1126b1..1320f153b 100644 --- a/01-introduction-to-genai/translations/ko/README.md +++ b/01-introduction-to-genai/translations/ko/README.md @@ -1,8 +1,8 @@ # 생성형 AI와 대형 언어 모델 (LLM) 소개 -[![Introduction to Generative AI and Large Language Models](../../images/01-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://youtu.be/vf_mZrn8ibc?WT.mc_id=academic-105485-koreyst) +[![Introduction to Generative AI and Large Language Models](./images/01-lesson-banner1.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson-1-gh) -*(이미지를 클릭하면 이 수업의 비디오를 볼 수 있습니다)* +_(이미지를 클릭하면 이 수업의 비디오를 볼 수 있습니다)_ 생성형 AI는 텍스트, 이미지 및 기타 유형의 콘텐츠를 생성할 수 있는 인공지능입니다. 이것이 훌륭한 기술인 이유는 AI를 민주화하기 때문입니다. 누구나 자연어로 작성된 문장인 텍스트 프롬프트만으로 이를 사용할 수 있습니다. Java나 SQL과 같은 언어를 배울 필요가 없으며, 당신이 원하는 것을 말하면 AI 모델에서 제안이 나옵니다. 이것의 응용 프로그램과 영향은 엄청나며, 보고서를 작성하거나 이해하고, 애플리케이션을 작성하고, 그 이상의 것들을 몇 초 만에 할 수 있습니다. @@ -12,23 +12,23 @@ 수업은 다음 내용을 다룹니다: -* 비즈니스 시나리오 소개: 우리의 스타트업 아이디어와 미션. -* 생성형 AI와 우리가 현재 기술 환경에 도달한 방법. -* 대형 언어 모델의 내부 작동 방식. -* 대형 언어 모델의 주요 기능과 실용적인 사용 사례. +- 비즈니스 시나리오 소개: 우리의 스타트업 아이디어와 미션. +- 생성형 AI와 우리가 현재 기술 환경에 도달한 방법. +- 대형 언어 모델의 내부 작동 방식. +- 대형 언어 모델의 주요 기능과 실용적인 사용 사례. ## 학습 목표 이 수업을 완료하면 다음을 이해하게 됩니다: -* 생성형 AI가 무엇인지, 대형 언어 모델이 어떻게 작동하는지. -* 교육 시나리오를 중심으로 다양한 사용 사례에 대형 언어 모델을 어떻게 활용할 수 있는지. +- 생성형 AI가 무엇인지, 대형 언어 모델이 어떻게 작동하는지. +- 교육 시나리오를 중심으로 다양한 사용 사례에 대형 언어 모델을 어떻게 활용할 수 있는지. ## 시나리오: 우리의 교육 스타트업 생성형 인공지능(AI)은 AI 기술의 정점을 나타내며, 한때 불가능하다고 생각되었던 것의 한계를 뛰어넘습니다. 생성형 AI 모델은 여러 가지 기능과 응용 프로그램을 가지고 있지만, 이 커리큘럼에서는 가상의 스타트업을 통해 교육을 혁신하는 방법을 살펴볼 것입니다. 이 스타트업을 *우리 스타트업*이라고 부르겠습니다. 우리 스타트업은 교육 분야에서 다음과 같은 야심찬 미션을 가지고 작업하고 있습니다. -> *전 세계적으로 학습의 접근성을 향상시키고, 교육에 대한 공정한 접근을 보장하며, 각 학습자의 필요에 따라 개인화된 학습 경험을 제공한다.* +> _전 세계적으로 학습의 접근성을 향상시키고, 교육에 대한 공정한 접근을 보장하며, 각 학습자의 필요에 따라 개인화된 학습 경험을 제공한다._ 우리 스타트업 팀은 이 목표를 달성하기 위해 현대의 가장 강력한 도구 중 하나인 대형 언어 모델(LLM)을 활용하지 않고는 불가능할 것임을 인식하고 있습니다. @@ -70,25 +70,25 @@ AI 분야에서 수십 년간의 연구 끝에 새로운 모델 구조인 *Trans 다음 장에서는 다양한 유형의 생성형 AI 모델을 살펴볼 것입니다. 하지만 지금은 OpenAI GPT (Generative Pre-trained Transformer) 모델을 중심으로 대형 언어 모델이 작동하는 방식에 대해 알아보겠습니다. -* **토크나이저, 텍스트를 숫자로 변환**: 대형 언어 모델은 텍스트를 입력으로 받아 텍스트를 출력합니다. 하지만 통계적 모델이기 때문에 텍스트 시퀀스보다는 숫자로 작업하는 것이 훨씬 더 잘 됩니다. 그래서 모델의 핵심 부분이 사용하기 전에 모든 입력은 토크나이저에 의해 처리됩니다. 토큰은 텍스트의 조각으로, 일정한 수의 문자로 구성됩니다. 그래서 토크나이저의 주요 작업은 입력을 토큰 배열로 분할하는 것입니다. 그런 다음 각 토큰은 토큰 인덱스와 매핑됩니다. 토큰 인덱스는 원래 텍스트 조각의 정수 인코딩입니다. +- **토크나이저, 텍스트를 숫자로 변환**: 대형 언어 모델은 텍스트를 입력으로 받아 텍스트를 출력합니다. 하지만 통계적 모델이기 때문에 텍스트 시퀀스보다는 숫자로 작업하는 것이 훨씬 더 잘 됩니다. 그래서 모델의 핵심 부분이 사용하기 전에 모든 입력은 토크나이저에 의해 처리됩니다. 토큰은 텍스트의 조각으로, 일정한 수의 문자로 구성됩니다. 그래서 토크나이저의 주요 작업은 입력을 토큰 배열로 분할하는 것입니다. 그런 다음 각 토큰은 토큰 인덱스와 매핑됩니다. 토큰 인덱스는 원래 텍스트 조각의 정수 인코딩입니다. ![Example of tokenization](../../images/tokenizer-example.png?WT.mc_id=academic-105485-koreyst) -* **출력 토큰 예측하기**: n개의 토큰을 입력으로 받으면(최대 n은 모델마다 다름) 모델은 하나의 토큰을 출력으로 예측할 수 있습니다. 이 토큰은 다음 반복의 입력에 확장 윈도우 패턴을 통해 더 나은 사용자 경험을 제공하여 하나(또는 여러) 문장을 답변으로 얻을 수 있습니다. 이를 통해 ChatGPT을 사용한 적이 있다면 때때로 문장 중간에 멈춰 있는 것처럼 보이는 이유를 설명할 수 있습니다. +- **출력 토큰 예측하기**: n개의 토큰을 입력으로 받으면(최대 n은 모델마다 다름) 모델은 하나의 토큰을 출력으로 예측할 수 있습니다. 이 토큰은 다음 반복의 입력에 확장 윈도우 패턴을 통해 더 나은 사용자 경험을 제공하여 하나(또는 여러) 문장을 답변으로 얻을 수 있습니다. 이를 통해 ChatGPT을 사용한 적이 있다면 때때로 문장 중간에 멈춰 있는 것처럼 보이는 이유를 설명할 수 있습니다. -* **선택 과정, 확률 분포**: 출력 토큰은 현재 텍스트 시퀀스 다음에 발생할 확률에 따라 모델에 의해 선택됩니다. 이는 모델이 훈련을 기반으로 가능한 ’다음 토큰’에 대한 확률 분포를 예측하기 때문입니다. 그러나 항상 결과 분포에서 가장 높은 확률을 가진 토큰이 선택되는 것은 아닙니다. 이 선택에는 일정한 무작위성이 추가되어, 모델이 비결정적인 방식으로 작동합니다 - 즉, 동일한 입력에 대해 정확히 동일한 출력을 얻지 않습니다. 이 무작위성의 정도는 창의적 사고 과정을 시뮬레이션하기 위해 추가되며, temperature라는 모델 매개변수를 사용하여 조정할 수 있습니다. +- **선택 과정, 확률 분포**: 출력 토큰은 현재 텍스트 시퀀스 다음에 발생할 확률에 따라 모델에 의해 선택됩니다. 이는 모델이 훈련을 기반으로 가능한 ’다음 토큰’에 대한 확률 분포를 예측하기 때문입니다. 그러나 항상 결과 분포에서 가장 높은 확률을 가진 토큰이 선택되는 것은 아닙니다. 이 선택에는 일정한 무작위성이 추가되어, 모델이 비결정적인 방식으로 작동합니다 - 즉, 동일한 입력에 대해 정확히 동일한 출력을 얻지 않습니다. 이 무작위성의 정도는 창의적 사고 과정을 시뮬레이션하기 위해 추가되며, temperature라는 모델 매개변수를 사용하여 조정할 수 있습니다. ## 우리 스타트업이 대형 언어 모델을 어떻게 활용할 수 있을까요? -이제 우리는 대형 언어 모델의 내부 작동 방식에 대해 더 잘 이해하게 되었으니, 그들이 잘 수행할 수 있는 가장 일반적인 작업들의 실제 예시를 살펴보면서 우리 비즈니스 시나리오에 대한 고려사항을 살펴보겠습니다. 앞서 말했듯이, 대형 언어 모델의 주요 능력은 *자연어로 작성된 텍스트 입력을 시작으로, 텍스트를 처음부터 생성하는 것입니다.* +이제 우리는 대형 언어 모델의 내부 작동 방식에 대해 더 잘 이해하게 되었으니, 그들이 잘 수행할 수 있는 가장 일반적인 작업들의 실제 예시를 살펴보면서 우리 비즈니스 시나리오에 대한 고려사항을 살펴보겠습니다. 앞서 말했듯이, 대형 언어 모델의 주요 능력은 _자연어로 작성된 텍스트 입력을 시작으로, 텍스트를 처음부터 생성하는 것입니다._ 그러나 어떤 종류의 텍스트 입력과 출력이 있을까요? 대형 언어 모델의 입력은 프롬프트(prompt) 라고 알려져 있고, 출력은 completion이라고 알려져 있습니다. 이는 모델이 현재 입력을 완성하기 위해 다음 토큰을 생성하는 메커니즘을 가리킵니다. 우리는 프롬프트가 무엇인지, 그리고 어떻게 설계해야 모델에서 최대의 효과를 얻을 수 있는지에 대해 깊이 파고들 것입니다. 하지만 지금은, 프롬프트가 다음을 포함할 수 있다고만 말하겠습니다: -* **지시 (instruction)** 를 통해 모델로부터 기대하는 출력 유형을 지정할 수 있습니다. 지시는 때때로 일부 예시나 추가 데이터를 포함할 수 있습니다. +- **지시 (instruction)** 를 통해 모델로부터 기대하는 출력 유형을 지정할 수 있습니다. 지시는 때때로 일부 예시나 추가 데이터를 포함할 수 있습니다. - 1. 기사, 책, 제품 리뷰 등의 요약, 더불어 비구조화된 데이터로부터 인사이트를 추출합니다. - - ![Example of summarization](../../images/summarization-example.png?WT.mc_id=academic-105485-koreyst) + 1. 기사, 책, 제품 리뷰 등의 요약, 더불어 비구조화된 데이터로부터 인사이트를 추출합니다. + + ![Example of summarization](../../images/summarization-example.png?WT.mc_id=academic-105485-koreyst)
@@ -97,22 +97,21 @@ AI 분야에서 수십 년간의 연구 끝에 새로운 모델 구조인 *Trans ![Example of creative writing](../../images/creative-writing-example.png?WT.mc_id=academic-105485-koreyst)
- -* **질문 (question)** 을 통해 대화 형식으로 에이전트에게 질문을 물어볼 수 있습니다. - + + +- **질문 (question)** 을 통해 대화 형식으로 에이전트에게 질문을 물어볼 수 있습니다. + ![Example of conversation](../../images/conversation-example.png?WT.mc_id=academic-105485-koreyst)
-* **완성해야 할 텍스트**를 제공함으로써 암시적으로 글쓰기 도움을 요청할 수 있습니다. - +- **완성해야 할 텍스트**를 제공함으로써 암시적으로 글쓰기 도움을 요청할 수 있습니다. + ![Example of text completion](../../images/text-completion-example.png?WT.mc_id=academic-105485-koreyst)
-* **코드**에서 그것을 설명하고 문서화하라는 요청을 하거나 특정 작업을 수행하는 코드 조각을 생성할 수 있습니다. - - +- **코드**에서 그것을 설명하고 문서화하라는 요청을 하거나 특정 작업을 수행하는 코드 조각을 생성할 수 있습니다. ![Coding example](../../images/coding-example.png?WT.mc_id=academic-105485-koreyst) @@ -124,7 +123,7 @@ AI 분야에서 수십 년간의 연구 끝에 새로운 모델 구조인 *Trans ## 과제 -당신의 과제는 [생성형 AI]((https://en.wikipedia.org/wiki/Generative_artificial_intelligence?WT.mc_id=academic-105485-koreyst))에 대해 더 많이 읽어보고, 현재 생성형 AI가 없는 영역에서 어디에 생성형 AI를 활용할 것인지를 파악하는 것입니다. "옛날 방식"과 비교했을 때 영향력은 어떻게 달라질까요, 이전에 할 수 없었던 것을 할 수 있게 되었나요, 아니면 더 빨라졌나요? “문제”, “AI를 어떻게 사용할 것인가”, “영향력” 그리고 선택적으로 비즈니스 계획을 포함한 헤더를 사용하여 꿈의 AI 스타트업이 어떤 모습일지에 대한 300단어 요약을 작성해보세요. +당신의 과제는 [생성형 AI](<(https://en.wikipedia.org/wiki/Generative_artificial_intelligence?WT.mc_id=academic-105485-koreyst)>)에 대해 더 많이 읽어보고, 현재 생성형 AI가 없는 영역에서 어디에 생성형 AI를 활용할 것인지를 파악하는 것입니다. "옛날 방식"과 비교했을 때 영향력은 어떻게 달라질까요, 이전에 할 수 없었던 것을 할 수 있게 되었나요, 아니면 더 빨라졌나요? “문제”, “AI를 어떻게 사용할 것인가”, “영향력” 그리고 선택적으로 비즈니스 계획을 포함한 헤더를 사용하여 꿈의 AI 스타트업이 어떤 모습일지에 대한 300단어 요약을 작성해보세요. 이 과제를 수행하면, 여러분은 Microsoft의 인큐베이터인 [Microsoft for Startups Founders Hub](https://www.microsoft.com/startups?WT.mc_id=academic-105485-koreyst)에 지원할 준비가 되어있을지도 모릅니다. 우리는 Azure, OpenAI, 멘토링 등에 대한 크레딧을 제공하며, 더 많은 것들을 확인해보세요! @@ -142,4 +141,4 @@ AI 분야에서 수십 년간의 연구 끝에 새로운 모델 구조인 *Trans 이 강의를 완료한 후에는 [Generative AI 학습 컬렉션](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst)을 확인하여 Generative AI 지식을 계속 향상시켜 보세요! -Lesson 2로 이동하여 [다양한 LLM 유형 탐색 및 비교](../../../02-exploring-and-comparing-different-llms/translations/ko/README.md?WT.mc_id=academic-105485-koreyst)하는 방법을 살펴보겠습니다! \ No newline at end of file +Lesson 2로 이동하여 [다양한 LLM 유형 탐색 및 비교](../../../02-exploring-and-comparing-different-llms/translations/ko/README.md?WT.mc_id=academic-105485-koreyst)하는 방법을 살펴보겠습니다! diff --git a/01-introduction-to-genai/translations/pt-br/README.md b/01-introduction-to-genai/translations/pt-br/README.md index cde436f2f..47dd2eddb 100644 --- a/01-introduction-to-genai/translations/pt-br/README.md +++ b/01-introduction-to-genai/translations/pt-br/README.md @@ -1,6 +1,6 @@ # Introdução à Inteligência Artificial Generativa e Grandes Modelos de Linguagem -[![Introduction to Generative AI and Large Language Models](../../images/01-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=36c6795a-e63c-46dd-8d69-df8bbe6e7bc9?WT.mc_id=academic-105485-koreyst) +[![Introduction to Generative AI and Large Language Models](./images/01-lesson-banner1.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson-1-gh) _(Clique na imagem acima para assistir ao vídeo desta lição)_ diff --git a/02-exploring-and-comparing-different-llms/README.md b/02-exploring-and-comparing-different-llms/README.md index 2845c8844..40423970e 100644 --- a/02-exploring-and-comparing-different-llms/README.md +++ b/02-exploring-and-comparing-different-llms/README.md @@ -1,8 +1,8 @@ # Exploring and comparing different LLMs -[![Exploring and comparing different LLMs](./images/02-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=39aa0f98-826a-4f71-a24d-e888a8e80246?WT.mc_id=academic-105485-koreyst) +[![Exploring and comparing different LLMs](./images/02-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson2-gh) -> *Click the image above to view video of this lesson* +> _Click the image above to view video of this lesson_ With the previous lesson, we have seen how Generative AI is changing the technology landscape, how Large Language Models (LLMs) work and how a business - like our startup - can apply them to their use cases and grow! In this chapter, we're looking to compare and contrast different types of large language models (LLMs) to understand their pros and cons. @@ -83,13 +83,13 @@ Image generation models are models that generate images. These models are often Text and code generation models are models that generate text or code. These models are often used for text summarization, translation, and question answering. Text generation models are often trained on large datasets of text, such as [BookCorpus](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/Zhu_Aligning_Books_and_ICCV_2015_paper.html?WT.mc_id=academic-105485-koreyst), and can be used to generate new text, or to answer questions. Code generation models, like [CodeParrot](https://huggingface.co/codeparrot?WT.mc_id=academic-105485-koreyst), are often trained on large datasets of code, such as GitHub, and can be used to generate new code, or to fix bugs in existing code. - ![Text and code generation](./images/Text.png?WT.mc_id=academic-105485-koreyst) +![Text and code generation](./images/Text.png?WT.mc_id=academic-105485-koreyst) ### Encoder-Decoder versus Decoder-only To talk about the different types of architectures of LLMs, let's use an analogy. -Imagine your manager gave you a task for writing a quiz for the students. You have two colleagues; one oversees creating the content and the other oversees reviewing them. +Imagine your manager gave you a task for writing a quiz for the students. You have two colleagues; one oversees creating the content and the other oversees reviewing them. The content creator is like a Decoder only model, they can look at the topic and see what you already wrote and then he can write a course based on that. They are very good at writing engaging and informative content, but they are not very good at understanding the topic and the learning objectives. Some examples of Decoder models are GPT family models, such as GPT-3. @@ -101,7 +101,7 @@ Imagine that we can have someone as well who could create and review the quiz, t Now, let's talk about the difference between a service and a model. A service is a product that is offered by a Cloud Service Provider, and is often a combination of models, data, and other components. A model is the core component of a service, and is often a foundation model, such as an LLM. -Services are often optimized for production use and are often easier to use than models, via a graphical user interface. However, services are not always available for free, and may require a subscription or payment to use, in exchange for leveraging the service owner’s equipment and resources, optimizing expenses and scaling easily. An example of service is [Azure OpenAI Service](https://learn.microsoft.com/azure/ai-services/openai/overview?WT.mc_id=academic-105485-koreyst), which offers a pay-as-you-go rate plan, meaning users are charged proportionally to how much they use the service Also, Azure OpenAI Service offers enterprise-grade security and responsible AI framework on top of the models' capabilities. +Services are often optimized for production use and are often easier to use than models, via a graphical user interface. However, services are not always available for free, and may require a subscription or payment to use, in exchange for leveraging the service owner’s equipment and resources, optimizing expenses and scaling easily. An example of service is [Azure OpenAI Service](https://learn.microsoft.com/azure/ai-services/openai/overview?WT.mc_id=academic-105485-koreyst), which offers a pay-as-you-go rate plan, meaning users are charged proportionally to how much they use the service Also, Azure OpenAI Service offers enterprise-grade security and responsible AI framework on top of the models' capabilities. Models are just the Neural Network, with the parameters, weights, and others. Allowing companies to run locally, however, would need to buy equipment, build structure to scale and buy a license or use an open-source model. A model like LLaMA is available to be used, requiring computational power to run the model. @@ -167,7 +167,7 @@ Prompt engineering with context is the most cost-effective approach to kick-off LLMs have the limitation that they can use only the data that has been used during their training to generate an answer. This means that they don’t know anything about the facts that happened after their training process, and they cannot access non-public information (like company data). This can be overcome through RAG, a technique that augments prompt with external data in the form of chunks of documents, considering prompt length limits. This is supported by Vector database tools (like [Azure Vector Search](https://learn.microsoft.com/azure/search/vector-search-overview?WT.mc_id=academic-105485-koreyst)) that retrieve the useful chunks from varied pre-defined data sources and add them to the prompt Context. -This technique is very helpful when a business doesn’t have enough data, enough time, or resources to fine-tune an LLM, but still wishes to improve performance on a specific workload and reduce risks of fabrications, i.e., mystification of reality or harmful content. +This technique is very helpful when a business doesn’t have enough data, enough time, or resources to fine-tune an LLM, but still wishes to improve performance on a specific workload and reduce risks of fabrications, i.e., mystification of reality or harmful content. ### Fine-tuned model diff --git a/02-exploring-and-comparing-different-llms/images/02-lesson-banner.png b/02-exploring-and-comparing-different-llms/images/02-lesson-banner.png index 344ba84aa..c601cae16 100644 Binary files a/02-exploring-and-comparing-different-llms/images/02-lesson-banner.png and b/02-exploring-and-comparing-different-llms/images/02-lesson-banner.png differ diff --git a/03-using-generative-ai-responsibly/README.md b/03-using-generative-ai-responsibly/README.md index 621697eb0..6f76609c2 100644 --- a/03-using-generative-ai-responsibly/README.md +++ b/03-using-generative-ai-responsibly/README.md @@ -1,8 +1,8 @@ # Using Generative AI Responsibly -[![Using Generative AI Responsibly](./images/03-lesson-banner.png?WT.mc_id=academic-105485-koreyst)]() +[![Using Generative AI Responsibly](./images/03-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson3-gh) -> **Video Coming Soon** +> _Click the image above to view video of this lesson_ It's easy to be fascinated with AI and generative AI in particular, but you need to consider how you would use it responsibly. You need to consider things like how to ensure the output is fair, non-harmful and more. This chapter aims to provide you with mentioned context, what to consider, and how to take active steps to improve your AI usage. @@ -16,7 +16,7 @@ This lesson will cover: ## Learning Goals -After completing this lesson you will know: +After completing this lesson you will know: - The importance of Responsible AI when building Generative AI applications. - When to think and apply the core principles of Responsible AI when building Generative AI applications. @@ -46,15 +46,15 @@ The model produces a response like the one below: ![Prompt saying "Who was the sole survivor of the Titanic"](../03-using-generative-ai-responsibly/images/ChatGPT-titanic-survivor-prompt.webp?WT.mc_id=academic-105485-koreyst) -> *(Source: [Flying bisons](https://flyingbisons.com?WT.mc_id=academic-105485-koreyst))* +> _(Source: [Flying bisons](https://flyingbisons.com?WT.mc_id=academic-105485-koreyst))_ This is a very confident and thorough answer. Unfortunately, it is incorrect. Even with a minimal amount of research, one would discover there was more than one survivor of the Titanic disaster. For a student who is just starting to research this topic, this answer can be persuasive enough to not be questioned and treated as fact. The consequences of this can lead to the AI system being unreliable and negatively impact the reputation of our startup. -With each iteration of any given LLM, we have seen performance improvements around minimizing hallucinations. Even with this improvement, we as application builders and users still need to remain aware of these limitations. +With each iteration of any given LLM, we have seen performance improvements around minimizing hallucinations. Even with this improvement, we as application builders and users still need to remain aware of these limitations. ### Harmful Content -We covered in the earlier section when an LLM produces incorrect or nonsensical responses. Another risk we need to be aware of is when a model responds with harmful content. +We covered in the earlier section when an LLM produces incorrect or nonsensical responses. Another risk we need to be aware of is when a model responds with harmful content. Harmful content can be defined as: @@ -96,9 +96,9 @@ It is now time to find ways where we can prevent or limit the potential harm cau - **Metaprompt**. Metaprompts and grounding are ways we can direct or limit the model based on certain behaviors and information. This could be using system inputs to define certain limits of the model. In addition, providing outputs that are more relevant to the scope or domain of the system. - It can also be using techniques like Retrieval Augmented Generation (RAG) to have the model only pull information from a selection of trusted sources. There is a lesson later in this course for [building search applications](../08-building-search-applications/README.md?WT.mc_id=academic-105485-koreyst) +It can also be using techniques like Retrieval Augmented Generation (RAG) to have the model only pull information from a selection of trusted sources. There is a lesson later in this course for [building search applications](../08-building-search-applications/README.md?WT.mc_id=academic-105485-koreyst) -- **User Experience**. The final layer is where the user interacts directly with the model through our application’s interface in some way. In this way we can design the UI/UX to limit the user on the types of inputs they can send to the model as well as text or images displayed to the user. When deploying the AI application, we also must be transparent about what our Generative AI application can and can’t do. +- **User Experience**. The final layer is where the user interacts directly with the model through our application’s interface in some way. In this way we can design the UI/UX to limit the user on the types of inputs they can send to the model as well as text or images displayed to the user. When deploying the AI application, we also must be transparent about what our Generative AI application can and can’t do. We have an entire lesson dedicated to [Designing UX for AI Applications](../12-designing-ux-for-ai-applications/README.md?WT.mc_id=academic-105485-koreyst) @@ -110,7 +110,7 @@ Building an operational practice around your AI applications is the final stage. ## Tools -While the work of developing Responsible AI solutions may seem like a lot, it is work well worth the effort. As the area of Generative AI grows, more tooling to help developers efficiently integrate responsibility into their workflows will mature. For example, the [Azure AI Content Safety](https://learn.microsoft.com/azure/ai-services/content-safety/overview?WT.mc_id=academic-105485-koreyst ) can help detect harmful content and images via an API request. +While the work of developing Responsible AI solutions may seem like a lot, it is work well worth the effort. As the area of Generative AI grows, more tooling to help developers efficiently integrate responsibility into their workflows will mature. For example, the [Azure AI Content Safety](https://learn.microsoft.com/azure/ai-services/content-safety/overview?WT.mc_id=academic-105485-koreyst) can help detect harmful content and images via an API request. ## Knowledge check diff --git a/03-using-generative-ai-responsibly/images/03-lesson-banner.png b/03-using-generative-ai-responsibly/images/03-lesson-banner.png index cb0e0b1aa..6dd782334 100644 Binary files a/03-using-generative-ai-responsibly/images/03-lesson-banner.png and b/03-using-generative-ai-responsibly/images/03-lesson-banner.png differ diff --git a/03-using-generative-ai-responsibly/translations/cn/README.md b/03-using-generative-ai-responsibly/translations/cn/README.md index 732f3e420..5be4a7fd4 100644 --- a/03-using-generative-ai-responsibly/translations/cn/README.md +++ b/03-using-generative-ai-responsibly/translations/cn/README.md @@ -1,6 +1,6 @@ # 第三章 : 负责任地使用生成式人工智能 -[![Using Generative AI Responsibly](../../images/03-lesson-banner.png?WT.mc_id=academic-105485-koreyst)]() +[![Using Generative AI Responsibly](../../images/03-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson3-gh) > **导学视频即将上架,敬请期待** diff --git a/03-using-generative-ai-responsibly/translations/ja-jp/README.md b/03-using-generative-ai-responsibly/translations/ja-jp/README.md index e57345ee0..85b17be46 100644 --- a/03-using-generative-ai-responsibly/translations/ja-jp/README.md +++ b/03-using-generative-ai-responsibly/translations/ja-jp/README.md @@ -1,6 +1,6 @@ # 生成 AI の責任ある使用 -[![生成 AI の責任ある使用](../../images/03-lesson-banner.png?WT.mc_id=academic-105485-yoterada)]() +[![生成 AI の責任ある使用](../../images/03-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://aka.ms/gen-ai-lesson3-gh) > **ビデオは近日公開予定** @@ -14,7 +14,7 @@ AI、特に生成 AI にとても強い興味は抱くのは理解できます - 責任ある AI の基本原則と、それが生成 AI とどう結びつくのか - 戦略とツールを使って、責任ある AI の原則をどのように実践するのか -## 学習目標 +## 学習目標 このレッスンを修了すると、下記を理解できます: @@ -24,7 +24,7 @@ AI、特に生成 AI にとても強い興味は抱くのは理解できます ## 責任ある AI の原則 -生成 AI に対する興味は、今までにないほど高まっています。この盛り上がりは、新たな開発者や関心、資金をこの業界にもたらしています。これは、生成 AI を使用して新しい製品や、新しい企業を創業する人々にとって非常に好意的な状況ですが、同時に責任を持って進めるのも重要です。 +生成 AI に対する興味は、今までにないほど高まっています。この盛り上がりは、新たな開発者や関心、資金をこの業界にもたらしています。これは、生成 AI を使用して新しい製品や、新しい企業を創業する人々にとって非常に好意的な状況ですが、同時に責任を持って進めるのも重要です。 このコースでは、スタートアップが AI を利用した教育製品の実装に焦点を当てます。公平性、包括性、信頼性・安全性、セキュリティ・プライバシー、透明性、説明責任といった責任ある AI の原則に基づいて、これらが製品における生成 AI の活用と、どのように関連していくのかについて考えます。 @@ -32,7 +32,7 @@ AI、特に生成 AI にとても強い興味は抱くのは理解できます 製品開発時、「利用者の利益を最優先に考える顧客中心のアプローチ」で進めると、最良の結果が得られます。 -生成 AI は、利用者に役立つ回答、情報、ガイダンス、コンテンツを生成する力があります。こうした作業の多くは手作業を必要とせずに実行でき、それによって非常に素晴らしい成果を生み出せます。しかし、適切な計画と戦略がなければ、残念ながら利用者、製品、そして社会全体に悪影響をもたらす場合もあります。 +生成 AI は、利用者に役立つ回答、情報、ガイダンス、コンテンツを生成する力があります。こうした作業の多くは手作業を必要とせずに実行でき、それによって非常に素晴らしい成果を生み出せます。しかし、適切な計画と戦略がなければ、残念ながら利用者、製品、そして社会全体に悪影響をもたらす場合もあります。 下記に記載する、潜在的に害を及ぼす可能性のある例(全てではありませんが)をご覧ください: @@ -56,7 +56,7 @@ AI、特に生成 AI にとても強い興味は抱くのは理解できます > プロンプト:タイタニックの唯一の生き残りは誰ですか? > 回答:タイタニック号の事故の唯一の生存者は、チャールズ・ジョーギンでした。彼はイギリスのパン職人で、タイタニック号のチーフ・ベーカリー職人でした。ジョーギンは、転覆した救命ボートにしがみつき、極寒の海で数時間耐え、RMS カルパチアに救助されたと伝えられています。彼の生存は、彼が大量のアルコールを摂取していたため、極度の寒さに耐えられたのではないかと伝えられています。ジョーギンは 1956 年まで生存し、後にタイタニック号の事故の経験について証言しました。 -> *(Source: [Flying bisons](https://flyingbisons.com?WT.mc_id=academic-105485-yoterada))* +> _(Source: [Flying bisons](https://flyingbisons.com?WT.mc_id=academic-105485-yoterada))_ これはとても自信に満ちて、詳細な回答結果です。しかし残念ながら、この回答は間違っています。タイタニック号の生存者は複数名いたという事実が、調査結果から判明しています。一方で、この課題研究を始めたばかりの学生にとって、この回答は疑う余地のないほど、そして事実として受け入れられるほどの説得力があります。このような間違いのある回答結果から、学生は AI システムを信頼できなくなり、さらにはスタートアップ企業の評判にも悪影響を及ぼす可能性があります。 @@ -64,9 +64,9 @@ LLM のバージョンを更新するごとに、幻覚を減らす方向でパ ### 有害なコンテンツ -前のセクションで、LLM が不正確、または無意味な回答を出力する可能性について触れました。もう一つ注意すべきリスクは、モデルが有害なコンテンツを回答する場合です。 +前のセクションで、LLM が不正確、または無意味な回答を出力する可能性について触れました。もう一つ注意すべきリスクは、モデルが有害なコンテンツを回答する場合です。 -有害なコンテンツには以下のようなものがあります: +有害なコンテンツには以下のようなものがあります: - 自傷行為や、特定グループへの危害を助長、または奨励する指示 - 憎悪や侮辱的な内容 @@ -74,7 +74,7 @@ LLM のバージョンを更新するごとに、幻覚を減らす方向でパ - 違法なコンテンツを探す方法や、犯罪を犯す方法 - 性的に露骨な内容 -スタートアップでは、このようなコンテンツが学生に見られないように、適切なツールと戦略を確実に導入したいと考えています。 +スタートアップでは、このようなコンテンツが学生に見られないように、適切なツールと戦略を確実に導入したいと考えています。 ### 公平性の欠如 @@ -96,7 +96,7 @@ LLM のバージョンを更新するごとに、幻覚を減らす方向でパ ### 潜在的な危害の軽減 -AI モデルとその出力によって引き起こされる、潜在的な問題を防ぐ、または抑制する方法を検討する時が来ました。これを4つの異なるレイヤーで考えます。 +AI モデルとその出力によって引き起こされる、潜在的な問題を防ぐ、または抑制する方法を検討する時が来ました。これを 4 つの異なるレイヤーで考えます。 ![Mitigation Layers](../../images/mitigation-layers.png?WT.mc_id=academic-105485-yoterada) @@ -114,7 +114,7 @@ AI モデルとその出力によって引き起こされる、潜在的な問 - **ユーザー・エクスペリエンス**:最後のレイヤーは、ユーザ・インターフェースです。利用者はどのような形であれ、アプリケーションが提供するインターフェイスを利用してモデルとやりとりを行います。適切な UI/UX を設計し、モデルに送信する入力の種類や利用者で表示されるテキストや画像を制限できます。AI アプリケーションをデプロイする際、生成 AI アプリケーションでできる処理と、できない処理について透明性を持って利用者に伝える必要があります。 - 本レッスンの最終章に「[12. AI アプリケーションの UX デザイン](../../../12-designing-ux-for-ai-applications/translations/ja-jp/README.md?WT.mc_id=academic-105485-yoterada)」に特化したレッスンがあります。 + 本レッスンの最終章に「[12. AI アプリケーションの UX デザイン](../../../12-designing-ux-for-ai-applications/translations/ja-jp/README.md?WT.mc_id=academic-105485-yoterada)」に特化したレッスンがあります。 - **モデルを評価**:大規模言語モデル(LLM)は、そのモデルがどのようなデータを使って学習されたのかを完全に把握できないため、扱うのが難しい場合があります。それでもなお、モデルの性能や出力は常に検証すべきです。特に出力の正確性、類似性、根拠の正しさ、関連性の評価は重要です。これにより、利害関係者や利用者に透明性と信頼性を提供できます。 @@ -130,7 +130,7 @@ AI モデルとその出力によって引き起こされる、潜在的な問 責任ある AI の利用を確実にするために、どのような点に考慮する必要があるのでしょうか? -1. 常に回答が正しい +1. 常に回答が正しい 2. AI が悪用されたり犯罪目的で利用されないように注意する 3. AI が偏りや差別的な内容を含まないようにする @@ -138,10 +138,10 @@ A: 2 と 3 が正解です。責任ある AI を導入し、害を及ぼす可 ## 🚀 Challenge -[Azure AI Content Safety](https://learn.microsoft.com/azure/ai-services/content-safety/overview?WT.mc_id=academic-105485-yoterada) について調べ、ご自身の用途に適用できるかご検討ください。 +[Azure AI Content Safety](https://learn.microsoft.com/azure/ai-services/content-safety/overview?WT.mc_id=academic-105485-yoterada) について調べ、ご自身の用途に適用できるかご検討ください。 ## お疲れ様でした! 次のレッスンを続ける -このレッスン終了後、[生成 AI 学習コレクション](https://aka.ms/genai-collection?WT.mc_id=academic-105485-yoterada)をチェックして、生成 AI の知識をさらに深めましょう。 +このレッスン終了後、[生成 AI 学習コレクション](https://aka.ms/genai-collection?WT.mc_id=academic-105485-yoterada)をチェックして、生成 AI の知識をさらに深めましょう。 レッスン 4 では、[プロンプト・エンジニアリングの基本](../../../04-prompt-engineering-fundamentals/translations/ja-jp/README.md?WT.mc_id=academic-105485-yoterada)について学びます! diff --git a/03-using-generative-ai-responsibly/translations/ko/README.md b/03-using-generative-ai-responsibly/translations/ko/README.md index a476ac701..190f99272 100644 --- a/03-using-generative-ai-responsibly/translations/ko/README.md +++ b/03-using-generative-ai-responsibly/translations/ko/README.md @@ -1,6 +1,6 @@ -# 책임감 있게 생성형 AI 사용하기 +# 책임감 있게 생성형 AI 사용하기 -[![Using Generative AI Responsibly](../../images/03-lesson-banner.png?WT.mc_id=academic-105485-koreyst)]() +[![Using Generative AI Responsibly](../../images/03-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson3-gh) > **비디오 제공 예정** @@ -16,7 +16,7 @@ AI 및 특히 생성형 AI에 매료되는 것은 쉽지만, 우리는 책임 ## 학습 목표 -이 장이 끝나면 다음을 이해하게 될 것입니다: +이 장이 끝나면 다음을 이해하게 될 것입니다: - 생성형 AI 애플리케이션을 개발할 때 '책임 있는 AI'의 중요성. - 생성형 AI 애플리케이션을 개발할 때 '책임 있는 AI'의 핵심 원칙을 언제 생각하고 적용해야 하는지. @@ -30,9 +30,9 @@ AI 및 특히 생성형 AI에 매료되는 것은 쉽지만, 우리는 책임 ## 왜 '책임 있는 AI'를 우선시해야 하는가 -제품을 만드는 것에 있어, 사용자의 이익을 최우선으로 하는 인간 중심적인 접근 방식은 가장 좋은 결과를 가져옵니다. +제품을 만드는 것에 있어, 사용자의 이익을 최우선으로 하는 인간 중심적인 접근 방식은 가장 좋은 결과를 가져옵니다. -생성형 AI의 특별한 점은 사용자에게 도움이 되는 답변, 정보, 지침 및 콘텐츠를 만들 수 있는 능력입니다. 이러한 것은 매뉴얼 단계를 많이 거치지 않아도 인상적인 결과를 얻을 수 있습니다. 하지만 적절한 계획과 전략이 없으면 사용자, 제품, 그리고 사회 전체에게 해로운 결과를 끼칠 수도 있습니다. +생성형 AI의 특별한 점은 사용자에게 도움이 되는 답변, 정보, 지침 및 콘텐츠를 만들 수 있는 능력입니다. 이러한 것은 매뉴얼 단계를 많이 거치지 않아도 인상적인 결과를 얻을 수 있습니다. 하지만 적절한 계획과 전략이 없으면 사용자, 제품, 그리고 사회 전체에게 해로운 결과를 끼칠 수도 있습니다. 이에 대해 몇가지(전체가 아님) 잠재적으로 해로운 결과를 살펴보겠습니다: @@ -40,18 +40,17 @@ AI 및 특히 생성형 AI에 매료되는 것은 쉽지만, 우리는 책임 환각 (Hallucinations)은 LLM이 완전히 비논리적이거나, 잘못되거나 다른 정보 출처를 기반으로 일반적으로 알고 있는 것과 다른 내용을 생성할 때 사용하는 용어입니다. - 예를 들어 우리 스타트업의 기능 중 하나로 학생들이 모델에게 역사와 관련한 질문을 할 수 있도록 하는 경우를 생각해 보겠습니다. 학생이 '타이타닉의 유일한 생존자는 누구였나요?'라는 질문을 한 경우 모델은 아래와 같이 응답할 수 있습니다: ![Prompt saying "Who was the sole survivor of the Titanic"](../../../03-using-generative-ai-responsibly/images/ChatGPT-titanic-survivor-prompt.webp?WT.mc_id=academic-105485-koreyst) -> *(Source: [Flying bisons](https://flyingbisons.com?WT.mc_id=academic-105485-koreyst))* +> _(Source: [Flying bisons](https://flyingbisons.com?WT.mc_id=academic-105485-koreyst))_ -이 대답은 매우 확신에 차있고 철저합 답변처럼 느껴지지만, 불행하게도 부정확한 답변입니다. 조사를 아주 조금만 해보더라도 우리는 타이타닉에서 생존한 사람은 한명 이상임을 찾을 수 있습니다. 그러나 이 주제를 처음 조사하기 시작하는 학생에게는 이 답변은 충분히 설득력이 있는 것처럼 보이고, 의심하지 않고 사실처럼 생각할 수도 있습니다. 이러한 결과들은 AI 시스템을 불안정하고 신뢰할 수 없게 만들어 우리의 스타트업의 평판에 부정적인 영향을 미칠수도 있습니다. +이 대답은 매우 확신에 차있고 철저합 답변처럼 느껴지지만, 불행하게도 부정확한 답변입니다. 조사를 아주 조금만 해보더라도 우리는 타이타닉에서 생존한 사람은 한명 이상임을 찾을 수 있습니다. 그러나 이 주제를 처음 조사하기 시작하는 학생에게는 이 답변은 충분히 설득력이 있는 것처럼 보이고, 의심하지 않고 사실처럼 생각할 수도 있습니다. 이러한 결과들은 AI 시스템을 불안정하고 신뢰할 수 없게 만들어 우리의 스타트업의 평판에 부정적인 영향을 미칠수도 있습니다. 각 LLM의 반복마다 Hallucination을 최소화하는 성능 향상이 있었지만, 이러한 개선에도 불구하고 응용 프로그램 빌더 및 사용자로서 이러한 제한에 대해 계속 알아야 합니다. -### 유해한 콘텐츠 +### 유해한 콘텐츠 이전 섹션에서 우리는 LLM이 부정확하거나 비논리적인 응답을 생성할 때를 다뤘습니다. 또 다른 리스크는 모델이 유해한 콘텐츠로 응답할 때 발생합니다. @@ -91,13 +90,13 @@ AI 및 특히 생성형 AI에 매료되는 것은 쉽지만, 우리는 책임 - **모델**. 올바른 사용 사례에 적합한 모델 선택. GPT-4와 같이 크고 복잡한 모델은 더 작고 구체적인 사용 사례에 적용할 때 유해한 콘텐츠의 위험을 더 많이 초래할 수 있습니다. 훈련 데이터를 사용하여 세밀하게 조정하면 해로운 콘텐츠의 위험을 줄일 수 있습니다. -- **안전 시스템**. 안전 시스템은 플랫폼에 있는 도구와 구성의 모음으로 모델이 해로운 콘텐츠 생산하는 것을 막습니다. Azure OpenAI 서비스의 콘텐츠 필터링 시스템이 이것에 대한 예시입니다. 안전 시스템은 또한 탈옥 공격 및 봇의 요청과 같은 활동을 감지해야 합니다. +- **안전 시스템**. 안전 시스템은 플랫폼에 있는 도구와 구성의 모음으로 모델이 해로운 콘텐츠 생산하는 것을 막습니다. Azure OpenAI 서비스의 콘텐츠 필터링 시스템이 이것에 대한 예시입니다. 안전 시스템은 또한 탈옥 공격 및 봇의 요청과 같은 활동을 감지해야 합니다. -- **메타프롬프트**. 메타프롬프트와 그라운딩은 특정 행동 및 정보를 기반으로 모델을 제한하거나 안내하는 방법입니다. 이것은 시스템 입력을 사용하여 모델의 특정 한계를 정의하거나 시스템의 범위나 도메인과 관련이 더 있는 출력을 제공할 수 있습니다. +- **메타프롬프트**. 메타프롬프트와 그라운딩은 특정 행동 및 정보를 기반으로 모델을 제한하거나 안내하는 방법입니다. 이것은 시스템 입력을 사용하여 모델의 특정 한계를 정의하거나 시스템의 범위나 도메인과 관련이 더 있는 출력을 제공할 수 있습니다. 또한 Retrieval Augmented Generation (RAG)과 같은 방법을 사용하여 모델이 검증된 출처들에서 선택하여 정보를 가져올 수 있도록 할 수 있습니다. 추후에 이에 관한 수업이 있습니다. [검색 애플리케이션 구축](../../../08-building-search-applications/translations/ko/README.md?WT.mc_id=academic-105485-koreyst) -- **사용자 경험**. 최종 레이어는 사용자가 모델과 어떤 방식으로든 응용 프로그램 인터페이스를 통해 직접 상호 작용하는 곳입니다. 이를 통해 UI/UX를 디자인하여 사용자가 모델로 보낼 수 있는 입력 유형과 사용자에게 표시되는 텍스트 또는 이미지를 제한할 수 있습니다. AI 애플리케이션을 배포할 때에는 또한 생성형 AI 애플리케이션이 무엇을 할 수 있고 할 수 없는지에 대해 투명하게 밝혀야 합니다. +- **사용자 경험**. 최종 레이어는 사용자가 모델과 어떤 방식으로든 응용 프로그램 인터페이스를 통해 직접 상호 작용하는 곳입니다. 이를 통해 UI/UX를 디자인하여 사용자가 모델로 보낼 수 있는 입력 유형과 사용자에게 표시되는 텍스트 또는 이미지를 제한할 수 있습니다. AI 애플리케이션을 배포할 때에는 또한 생성형 AI 애플리케이션이 무엇을 할 수 있고 할 수 없는지에 대해 투명하게 밝혀야 합니다. 이에 관한 전체 내용을 담은 수업이 있습니다. [AI 애플리케이션을 위한 UX 디자인](../../../12-designing-ux-for-ai-applications/translations/ko/README.md?WT.mc_id=academic-105485-koreyst) @@ -109,7 +108,7 @@ AI 및 특히 생성형 AI에 매료되는 것은 쉽지만, 우리는 책임 ## 도구들 -책임 있는 AI 솔루션을 개발하는 작업은 많아 보일 수 있지만 그 노력은 확실히 가치 있는 작업입니다. 생성형 AI의 영역이 넓어질 수록 개발자가 책임을 효율적으로 통합할 수 있는 도구들이 많이 생기게 될 것 입니다. 예를 들어 [Azure AI Content Safety](https://learn.microsoft.com/azure/ai-services/content-safety/overview?WT.mc_id=academic-105485-koreyst )는 유해한 콘텐츠 및 이미지를 API 요청을 통해 감지하는 데 도움이 될 수 있습니다. +책임 있는 AI 솔루션을 개발하는 작업은 많아 보일 수 있지만 그 노력은 확실히 가치 있는 작업입니다. 생성형 AI의 영역이 넓어질 수록 개발자가 책임을 효율적으로 통합할 수 있는 도구들이 많이 생기게 될 것 입니다. 예를 들어 [Azure AI Content Safety](https://learn.microsoft.com/azure/ai-services/content-safety/overview?WT.mc_id=academic-105485-koreyst)는 유해한 콘텐츠 및 이미지를 API 요청을 통해 감지하는 데 도움이 될 수 있습니다. ## 문제 diff --git a/03-using-generative-ai-responsibly/translations/pt-br/README.md b/03-using-generative-ai-responsibly/translations/pt-br/README.md index 5f27220c1..3fad6346e 100644 --- a/03-using-generative-ai-responsibly/translations/pt-br/README.md +++ b/03-using-generative-ai-responsibly/translations/pt-br/README.md @@ -1,6 +1,6 @@ # Usando a IA Generativa de Forma Responsável -[![Usando a IA Generativa de Forma Responsável](../../images/03-lesson-banner.png?WT.mc_id=academic-105485-koreyst)]() +[![Usando a IA Generativa de Forma Responsável](../../images/03-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson3-gh) > **Vídeo em Breve** diff --git a/04-prompt-engineering-fundamentals/README.md b/04-prompt-engineering-fundamentals/README.md index 56396863d..1907b5651 100644 --- a/04-prompt-engineering-fundamentals/README.md +++ b/04-prompt-engineering-fundamentals/README.md @@ -1,6 +1,6 @@ # Prompt Engineering Fundamentals -[![Prompt Engineering Fundamentals](./images/04-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=eb8a0805-5623-4da8-b3c3-1b0ecccffa64?WT.mc_id=academic-105485-koreyst) +[![Prompt Engineering Fundamentals](./images/04-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson4-gh) The way your write your prompt to an LLM also matters. A carefully-crafted prompt can achieve a better quality of response. But what exactly do terms like _prompt_ and _prompt engineering_ mean? And how do I improve the prompt _input_ that I send to the LLM? These are the questions we'll try to answer with in this chapter and the next. @@ -39,7 +39,6 @@ Want to get the big picture of what this lesson covers before you dive in? Check ![Illustrated Guide to Prompt Engineering](./images/04-prompt-engineering-sketchnote.png?WT.mc_id=academic-105485-koreyst) - ## Our Startup Now, let's talk about how _this topic_ relates to our startup mission to [bring AI innovation to education](https://educationblog.microsoft.com/2023/06/collaborating-to-bring-ai-innovation-to-education?WT.mc_id=academic-105485-koreyst). We want to build AI-powered applications of _personalized learning_ - so let's think about how different users of our application might "design" prompts: diff --git a/04-prompt-engineering-fundamentals/images/04-lesson-banner.png b/04-prompt-engineering-fundamentals/images/04-lesson-banner.png index 8dc8de253..7a260a434 100644 Binary files a/04-prompt-engineering-fundamentals/images/04-lesson-banner.png and b/04-prompt-engineering-fundamentals/images/04-lesson-banner.png differ diff --git a/04-prompt-engineering-fundamentals/translations/cn/README.md b/04-prompt-engineering-fundamentals/translations/cn/README.md index d337185cf..4052037e8 100644 --- a/04-prompt-engineering-fundamentals/translations/cn/README.md +++ b/04-prompt-engineering-fundamentals/translations/cn/README.md @@ -1,6 +1,6 @@ # 第四章:提示工程基础 -[![Prompt Engineering Fundamentals](../../images/04-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=d54c0c69-b183-4a6c-80ed-8b1a8f299cff?WT.mc_id=academic-105485-koreyst) +[![Prompt Engineering Fundamentals](../../images/04-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson4-gh) 如何撰写 LLM 的提示很重要,精心设计的提示可以比不精心设计的提示取得更好的结果。 但这些概念到底是什么,提示、提示工程以及我如何改进我发送给 LLMs 的内容? 诸如此类的问题正是本章和下一章想要解答的。 diff --git a/04-prompt-engineering-fundamentals/translations/ja-jp/README.md b/04-prompt-engineering-fundamentals/translations/ja-jp/README.md index bb85d4b88..5a31f5337 100644 --- a/04-prompt-engineering-fundamentals/translations/ja-jp/README.md +++ b/04-prompt-engineering-fundamentals/translations/ja-jp/README.md @@ -1,6 +1,6 @@ # プロンプト・エンジニアリングの基礎 -[![Prompt Engineering Fundamentals](../../images/04-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=d54c0c69-b183-4a6c-80ed-8b1a8f299cff?WT.mc_id=academic-105485-koreyst) +[![Prompt Engineering Fundamentals](../../images/04-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://aka.ms/gen-ai-lesson4-gh) 大規模言語モデル (LLM) では、プロンプトの書き方がとても重要で、慎重に作成したプロンプトは、そうでないものに比べ良い結果をもたらします。しかし、プロンプトやプロンプト・エンジニアリングとは一体どういう物なのでしょうか?また、LLM に送信する内容をどのようにして改善すればいいのでしょうか?この章と次の章では、そうした疑問に答えたいと思います。 diff --git a/04-prompt-engineering-fundamentals/translations/ko/README.md b/04-prompt-engineering-fundamentals/translations/ko/README.md index 2d4fafda0..904c644e7 100644 --- a/04-prompt-engineering-fundamentals/translations/ko/README.md +++ b/04-prompt-engineering-fundamentals/translations/ko/README.md @@ -1,6 +1,6 @@ # 프롬프트 엔지니어링 기초 -[![Prompt Engineering Fundamentals](../../images/04-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://youtu.be/r2ItK3UMVTk?WT.mc_id=academic-105485-koreyst) +[![Prompt Engineering Fundamentals](../../images/04-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson4-gh) LLM에게 어떻게 프롬프트를 작성하는지는 중요합니다. 신중하게 작성된 프롬프트는 그렇지 않은 프롬프트보다 더 좋은 결과를 얻을 수 있습니다. 그런데 이런 개념들, 프롬프트, 프롬프트 엔지니어링이 무엇인지, 그리고 LLM에게 보내는 것을 어떻게 개선할 수 있는지에 대한 질문들은 바로 이 장과 다가올 장에서 답변하려고 합니다. @@ -28,7 +28,7 @@ _생성형 AI_ 는 사용자의 요청에 응답하여 새로운 콘텐츠(예: 이번 수업에 따른 Jupyter 노트북은 배운 내용을 시도해볼 수 있는 _샌드박스_ 환경을 제공합니다. 여기서는 각 단계에서 또는 마지막의 코드 도전 과제에서 배운 것을 시도해볼 수 있습니다. 연습문제를 실행하려면 다음이 필요합니다: 1. Azure OpenAI API 키 - 배포된 LLM의 서비스 엔드포인트입니다. -2. 파이썬 런타임 - 노트북을 실행할 수 있는 환경입니다. +2. 파이썬 런타임 - 노트북을 실행할 수 있는 환경입니다. 이 저장소는 Python 3 런타임이 포함된 _dev 컨테이너_ 로 구성되어 있습니다. GitHub 코드스페이스에서 저장소를 열거나 로컬 Docker 데스크톱에서 열면 런타임이 자동으로 활성화됩니다. 그런 다음 노트북을 열고 Python 3.x 커널을 선택하여 노트북을 실행 준비합니다. @@ -42,9 +42,9 @@ _생성형 AI_ 는 사용자의 요청에 응답하여 새로운 콘텐츠(예: 이제, _본 주제_ 가 우리 스타트업의 [교육에 AI 혁신을 가져오기](https://educationblog.microsoft.com/2023/06/collaborating-to-bring-ai-innovation-to-education?WT.mc_id=academic-105485-koreyst) 미션과 어떻게 관련되는지에 대해 이야기해보겠습니다. 우리는 _개인화된 학습_ (personalized learning)의 AI 기반 응용 프로그램을 구축하고자 합니다. 그러니 애플리케이션 목표와 모델에 대한 다양한 사용자들이 프롬프트를 "디자인" 할 수 있는 방법에 대해 생각해보겠습니다: -- **관리자** 는 AI가 _커리큘럼 데이터를 분석하여 부족한 부분을 식별_ 하도록 요청할 수 있습니다. AI는 결과를 요약하거나 코드로 시각화할 수 있습니다. -- **교육자** 는 _대상 그룹과 주제에 대한 레슨 계획을 생성_ 하도록 AI에게 요청할 수 있습니다. AI는 지정된 형식으로 개인화된 계획을 작성할 수 있습니다. -- **학생** 들은 _어려운 주제를 가르쳐 달라고 AI에게 요청_ 할 수 있습니다. 이제 AI는 학생의 수준에 맞게 수업, 힌트 및 예제를 안내할 수 있습니다. +- **관리자** 는 AI가 _커리큘럼 데이터를 분석하여 부족한 부분을 식별_ 하도록 요청할 수 있습니다. AI는 결과를 요약하거나 코드로 시각화할 수 있습니다. +- **교육자** 는 _대상 그룹과 주제에 대한 레슨 계획을 생성_ 하도록 AI에게 요청할 수 있습니다. AI는 지정된 형식으로 개인화된 계획을 작성할 수 있습니다. +- **학생** 들은 _어려운 주제를 가르쳐 달라고 AI에게 요청_ 할 수 있습니다. 이제 AI는 학생의 수준에 맞게 수업, 힌트 및 예제를 안내할 수 있습니다. 이것은 빙산의 일각에 불과합니다. [Prompts For Education](https://github.com/microsoft/prompts-for-edu/tree/main?WT.mc_id=academic-105485-koreyst)를 확인해보세요 - 교육 전문가들이 선별한 오픈 소스 프롬프트 라이브러리로, 더 다양한 가능성을 알 수 있습니다! _샌드박스에서 이러한 프롬프트 중 일부를 실행하거나 OpenAI Playground를 사용하여 결과를 확인해보세요!_ @@ -183,8 +183,8 @@ Illustrated with examples. 먼저 기본 프롬프트부터 시작해보겠습니다. 이는 다른 맥락 없이 모델에게 보내지는 텍스트 입력입니다. 예를 들어, OpenAI [Completion API](https://platform.openai.com/docs/api-reference/completions?WT.mc_id=academic-105485-koreyst)에 미국 국가 애국가의 처음 몇 단어를 보내면 모델은 즉시 다음 몇 줄을 포함한 응답을 _완성_ 합니다. 이는 기본적인 예측 동작을 보여줍니다. -| 프롬프트 (입력) | 완성 (출력) | -| :----------------- | :----------------------------------------------------------------------------------------------------------------------------------------- | +| 프롬프트 (입력) | 완성 (출력) | +| :----------------- | :-------------------------------------------------------------------------------------------------- | | Oh say can you see | "The Star-Spangled Banner"라는 미국의 국가 애국가 가사를 시작하고 있는 것 같습니다. 전체 가사는 ... | ### 복잡한 프롬프트 @@ -209,10 +209,10 @@ response = openai.chat.completions.create( 위의 예시에서 사용자 프롬프트는 정보 요청으로 해석될 수 있는 간단한 텍스트 쿼리였습니다. _지시_ 프롬프트를 사용하면 해당 텍스트를 사용하여 AI에게 더 자세한 작업을 지정하여 더 나은 안내를 제공할 수 있습니다. 다음은 예시입니다: -| 프롬프트 (입력) | 완성 (출력) | 지시 유형 | -| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------- | :------------------ | -| 시민 전쟁에 대한 설명을 작성하세요. | _간단한 단락을 반환합니다._ | 간단한 | -| 시민 전쟁에 대한 설명을 작성하세요. 주요 날짜와 사건을 제공하고 그들의 의미를 설명하세요. | _단락 다음에 주요 사건 날짜와 설명이 포함된 목록을 반환합니다._ | 복잡한 | +| 프롬프트 (입력) | 완성 (출력) | 지시 유형 | +| :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------------- | :---------------- | +| 시민 전쟁에 대한 설명을 작성하세요. | _간단한 단락을 반환합니다._ | 간단한 | +| 시민 전쟁에 대한 설명을 작성하세요. 주요 날짜와 사건을 제공하고 그들의 의미를 설명하세요. | _단락 다음에 주요 사건 날짜와 설명이 포함된 목록을 반환합니다._ | 복잡한 | | 시민 전쟁에 대한 설명을 1단락으로 작성하세요. 주요 날짜와 그들의 의미를 가진 3개의 불릿 포인트를 제공하세요. 또한 주요 역사 인물과 그들의 기여를 가진 3개의 불릿 포인트를 제공하세요. 결과를 JSON 파일로 반환하세요 | _텍스트 상자에 더 많은 세부 정보를 JSON 형식으로 반환합니다. 파일로 복사하여 필요에 따라 유효성을 검사할 수 있습니다._ | 복잡한. 형식화됨. | ## 주요 콘텐츠 (Primary Content) @@ -224,8 +224,8 @@ response = openai.chat.completions.create( 다음은 "이를 2문장으로 요약하세요"라는 지시사항이 있는 예시입니다. -| 프롬프트 (입력) | 완성 (출력) | -| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 프롬프트 (입력) | 완성 (출력) | +| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | 주피터는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다. 이는 태양의 천분의 일 질량을 가진 가스 행성으로, 태양계의 다른 행성들의 질량의 2.5배입니다. 주피터는 밤하늘에서 맨 눈으로 볼 수 있는 가장 밝은 물체 중 하나이며, 기록된 역사 이전부터 고대 문명에 알려져 있습니다. 이는 로마 신 주피터에게 이름을 따왔습니다. 지구에서 볼 때, 주피터는 반사된 빛이 가시적인 그림자를 만들 정도로 충분히 밝으며, 달과 금성 이후 밤하늘에서 평균적으로 세 번째로 밝은 천체입니다.
**이를 2문장으로 요약하세요** | 주피터는 태양계에서 가장 큰 행성으로 밤하늘에서 가장 밝은 물체 중 하나입니다. 로마 신 주피터에게 이름을 따온 이 가스 행성은 태양계의 다른 행성들의 질량의 2.5배입니다. | 주요 콘텐츠 세그먼트는 더 효과적인 지시사항을 만들기 위해 다양한 방법으로 사용될 수 있습니다: @@ -246,12 +246,12 @@ response = openai.chat.completions.create( - 원하는 출력의 몇 가지 예시 - 새로운 예시의 시작 (암묵적인 작업 설명이 됨) -| 학습 유형 | 프롬프트 (입력) | 완성 (출력) | -| :------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------- | -| 제로-샷 | "The Sun is Shining". 스페인어로 번역 | "El Sol está brillando". | -| 원-샷 | "The Sun is Shining" => ""El Sol está brillando".
"It's a Cold and Windy Day" => | "Es un día frío y ventoso". | -| 퓨-샷 | The player ran the bases => 야구
The player hit an ace => 테니스
The player hit a six => 크리켓
The player made a slam-dunk => | 농구 | -| | | | +| 학습 유형 | 프롬프트 (입력) | 완성 (출력) | +| :-------- | :----------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------- | +| 제로-샷 | "The Sun is Shining". 스페인어로 번역 | "El Sol está brillando". | +| 원-샷 | "The Sun is Shining" => ""El Sol está brillando".
"It's a Cold and Windy Day" => | "Es un día frío y ventoso". | +| 퓨-샷 | The player ran the bases => 야구
The player hit an ace => 테니스
The player hit a six => 크리켓
The player made a slam-dunk => | 농구 | +| | | | 제로샷 프롬프팅에서는 명시적인 지시사항("스페인어로 번역")을 제공해야 했지만, 원샷 프롬프팅 예시에서는 추론됩니다. 퓨샷 예시는 더 많은 예시를 추가함으로써 추가 지시사항 없이 모델이 더 정확한 추론을 할 수 있는 방법을 보여줍니다. @@ -259,16 +259,16 @@ response = openai.chat.completions.create( 기본 콘텐츠를 사용하는 또 다른 기법은 예시 대신 _힌트_ 를 제공하는 것입니다. 이 경우, 우리는 원하는 응답 형식을 반영하는 스니펫으로 모델을 _시작시킴_ 으로써 모델을 올바른 방향으로 이끄는 역할을 합니다. 그럼 모델은 그 힌트를 받아들여 해당 방향으로 계속 진행합니다. -| 힌트 수 | 프롬프트 (입력) | 완성 (출력) | -| :------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 0 | 주피터는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다. 이는 태양의 천분의 일 질량을 가진 가스 행성으로, 태양계의 다른 행성들의 질량의 2.5배입니다. 주피터는 밤하늘에서 맨 눈으로 볼 수 있는 가장 밝은 물체 중 하나이며, 기록된 역사 이전부터 고대 문명에 알려져 있습니다.
**이를 요약하세요** | 주피터는 태양계에서 가장 큰 행성으로 밤하늘에서 가장 밝은 물체 중 하나입니다. 로마 신 주피터에게 이름을 따온 이 가스 행성은 태양계의 다른 행성들의 질량의 2.5배입니다. | -| 1 | 주피터는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다. 이는 태양의 천분의 일 질량을 가진 가스 행성으로, 태양계의 다른 행성들의 질량의 2.5배입니다. 주피터는 밤하늘에서 맨 눈으로 볼 수 있는 가장 밝은 물체 중 하나이며, 기록된 역사 이전부터 고대 문명에 알려져 있습니다.
**이를 요약하세요**
우리가 배운 것은 주피터 | 는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다. 이는 태양의 천분의 일 질량을 가진 가스 행성으로, 태양계의 다른 행성들의 질량의 2.5배입니다. 맨 눈으로 볼 수 있으며 고대 문명부터 알려져 왔습니다. | -| 2 | 주피터는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다. 이는 태양의 천분의 일 질량을 가진 가스 행성으로, 태양계의 다른 행성들의 질량의 2.5배입니다. 주피터는 밤하늘에서 맨 눈으로 볼 수 있는 가장 밝은 물체 중 하나이며, 기록된 역사 이전부터 고대 문명에 알려져 있습니다.
**이를 요약하세요**
우리가 배운 상위 3가지 사실: | 1. 주피터는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다.
2. 이는 태양의 천분의 일 질량을 가진 가스 행성입니다...
3. 주피터는 고대부터 맨 눈으로 볼 수 있었습니다 ... | -| | | | +| 힌트 수 | 프롬프트 (입력) | 완성 (출력) | +| :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 0 | 주피터는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다. 이는 태양의 천분의 일 질량을 가진 가스 행성으로, 태양계의 다른 행성들의 질량의 2.5배입니다. 주피터는 밤하늘에서 맨 눈으로 볼 수 있는 가장 밝은 물체 중 하나이며, 기록된 역사 이전부터 고대 문명에 알려져 있습니다.
**이를 요약하세요** | 주피터는 태양계에서 가장 큰 행성으로 밤하늘에서 가장 밝은 물체 중 하나입니다. 로마 신 주피터에게 이름을 따온 이 가스 행성은 태양계의 다른 행성들의 질량의 2.5배입니다. | +| 1 | 주피터는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다. 이는 태양의 천분의 일 질량을 가진 가스 행성으로, 태양계의 다른 행성들의 질량의 2.5배입니다. 주피터는 밤하늘에서 맨 눈으로 볼 수 있는 가장 밝은 물체 중 하나이며, 기록된 역사 이전부터 고대 문명에 알려져 있습니다.
**이를 요약하세요**
우리가 배운 것은 주피터 | 는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다. 이는 태양의 천분의 일 질량을 가진 가스 행성으로, 태양계의 다른 행성들의 질량의 2.5배입니다. 맨 눈으로 볼 수 있으며 고대 문명부터 알려져 왔습니다. | +| 2 | 주피터는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다. 이는 태양의 천분의 일 질량을 가진 가스 행성으로, 태양계의 다른 행성들의 질량의 2.5배입니다. 주피터는 밤하늘에서 맨 눈으로 볼 수 있는 가장 밝은 물체 중 하나이며, 기록된 역사 이전부터 고대 문명에 알려져 있습니다.
**이를 요약하세요**
우리가 배운 상위 3가지 사실: | 1. 주피터는 태양으로부터 다섯 번째 행성이며 태양계에서 가장 큰 행성입니다.
2. 이는 태양의 천분의 일 질량을 가진 가스 행성입니다...
3. 주피터는 고대부터 맨 눈으로 볼 수 있었습니다 ... | +| | | | ### 프롬프트 템플릿 -프롬프트 템플릿은 필요에 따라 저장하고 재사용할 수 있는 _프롬프트를 위한 미리 정의된 레시피_입니다. 가장 간단한 형태에서는 [OpenAI의 예시](https://platform.openai.com/examples?WT.mc_id=academic-105485-koreyst)와 같이 상호작용 프롬프트 구성 요소(사용자 및 시스템 메시지)와 API 기반 요청 형식을 모두 제공하여 재사용을 지원합니다. +프롬프트 템플릿은 필요에 따라 저장하고 재사용할 수 있는 *프롬프트를 위한 미리 정의된 레시피*입니다. 가장 간단한 형태에서는 [OpenAI의 예시](https://platform.openai.com/examples?WT.mc_id=academic-105485-koreyst)와 같이 상호작용 프롬프트 구성 요소(사용자 및 시스템 메시지)와 API 기반 요청 형식을 모두 제공하여 재사용을 지원합니다. [LangChain의 예시](https://python.langchain.com/docs/modules/model_io/prompts/prompt_templates/?WT.mc_id=academic-105485-koreyst)와 같이 더 복잡한 형태에서는 _플레이스홀더_ 를 포함하여 다양한 소스(사용자 입력, 시스템 컨텍스트, 외부 데이터 소스 등)의 데이터로 교체하여 동적으로 프롬프트를 생성할 수 있습니다. 이를 통해 규모에 맞게 일관된 사용자 경험을 **프로그래밍 방식**으로 구현할 수 있는 재사용 가능한 프롬프트 라이브러리를 만들 수 있습니다. @@ -317,17 +317,17 @@ Illustrate it with some exercises. 이제 [Open AI](https://help.openai.com/en/articles/6654000-best-practices-for-prompt-engineering-with-openai-api?WT.mc_id=academic-105485-koreyst)와 [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/concepts/prompt-engineering#best-practices?WT.mc_id=academic-105485-koreyst) 전문가들이 권장하는 일반적인 모범 사례를 살펴보겠습니다. -| 항목 | 이유 | -| :-------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| 최신 모델 평가하기 | 새로운 모델 세대는 향상된 기능과 품질을 가질 가능성이 높지만, 더 높은 비용이 발생할 수도 있습니다. 영향을 평가한 후 이동 결정을 내립니다. | -| 지시사항과 컨텍스트 분리하기 | 모델/공급자가 지시사항, 주요 콘텐츠 및 보조 콘텐츠를 명확하게 구분하기 위한 _구분자_ 를 정의하는지 확인하세요. 이는 모델이 토큰에 더 정확한 가중치를 할당할 수 있도록 도와줍니다. | -| 구체적이고 명확하게 작성하기 | 원하는 컨텍스트, 결과, 길이, 형식, 스타일 등에 대해 더 많은 세부 정보를 제공하세요. 이는 응답의 품질과 일관성을 높일 것입니다. 재사용 가능한 템플릿으로 레시피를 작성하세요. | -| 상세 설명과 예시 사용하기 | 모델은 "보여주고 설명하기" 접근법에 더 잘 반응할 수 있습니다. 지시사항만 제공하는 `zero-shot` 접근법으로 시작한 다음, 원하는 출력의 몇 가지 예시를 제공하는 `few-shot`으로 세부 조정해보세요. 유추법을 사용하세요. | -| 시작 단어나 구문을 사용하여 완성 시작하기 | 응답의 시작점으로 사용할 수 있는 몇 가지 선행 단어나 구문을 제공하여 원하는 결과로 모델을 유도하세요. | -| 반복하기 | 때로는 모델에게 반복해서 지시해야 할 수도 있습니다. 주요 콘텐츠 앞뒤로 지시사항을 제공하거나, 지시사항과 시작 단어를 함께 사용하는 등의 방법을 사용하세요. 작동하는지 확인하기 위해 반복적으로 검증하세요. | -| 순서가 중요합니다 | 모델에 정보를 제공하는 순서는 출력에 영향을 줄 수 있습니다. 최근성 편향을 통해 학습 예제에서도 다른 옵션을 시도해보세요. | -| 모델에 "탈출구"를 제공하기 | 모델이 작업을 완료할 수 없는 경우 제공할 수 있는 _대체_ 완성 응답을 제공하세요. 이렇게 하면 모델이 잘못된 또는 가짜 응답을 생성할 가능성이 줄어듭니다. | -| | | +| 항목 | 이유 | +| :---------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 최신 모델 평가하기 | 새로운 모델 세대는 향상된 기능과 품질을 가질 가능성이 높지만, 더 높은 비용이 발생할 수도 있습니다. 영향을 평가한 후 이동 결정을 내립니다. | +| 지시사항과 컨텍스트 분리하기 | 모델/공급자가 지시사항, 주요 콘텐츠 및 보조 콘텐츠를 명확하게 구분하기 위한 _구분자_ 를 정의하는지 확인하세요. 이는 모델이 토큰에 더 정확한 가중치를 할당할 수 있도록 도와줍니다. | +| 구체적이고 명확하게 작성하기 | 원하는 컨텍스트, 결과, 길이, 형식, 스타일 등에 대해 더 많은 세부 정보를 제공하세요. 이는 응답의 품질과 일관성을 높일 것입니다. 재사용 가능한 템플릿으로 레시피를 작성하세요. | +| 상세 설명과 예시 사용하기 | 모델은 "보여주고 설명하기" 접근법에 더 잘 반응할 수 있습니다. 지시사항만 제공하는 `zero-shot` 접근법으로 시작한 다음, 원하는 출력의 몇 가지 예시를 제공하는 `few-shot`으로 세부 조정해보세요. 유추법을 사용하세요. | +| 시작 단어나 구문을 사용하여 완성 시작하기 | 응답의 시작점으로 사용할 수 있는 몇 가지 선행 단어나 구문을 제공하여 원하는 결과로 모델을 유도하세요. | +| 반복하기 | 때로는 모델에게 반복해서 지시해야 할 수도 있습니다. 주요 콘텐츠 앞뒤로 지시사항을 제공하거나, 지시사항과 시작 단어를 함께 사용하는 등의 방법을 사용하세요. 작동하는지 확인하기 위해 반복적으로 검증하세요. | +| 순서가 중요합니다 | 모델에 정보를 제공하는 순서는 출력에 영향을 줄 수 있습니다. 최근성 편향을 통해 학습 예제에서도 다른 옵션을 시도해보세요. | +| 모델에 "탈출구"를 제공하기 | 모델이 작업을 완료할 수 없는 경우 제공할 수 있는 _대체_ 완성 응답을 제공하세요. 이렇게 하면 모델이 잘못된 또는 가짜 응답을 생성할 가능성이 줄어듭니다. | +| | | 모든 모범 사례와 마찬가지로, 모델, 작업 및 도메인에 따라 _결과가 달라질 수 있습니다._ 이를 시작점으로 사용하고, 가장 잘 작동하는 방법을 찾기 위해 반복적으로 개선하세요. 새로운 모델과 도구가 사용 가능해질 때마다 프롬프트 엔지니어링 프로세스를 지속적으로 재평가하고, 프로세스의 확장성과 응답 품질에 초점을 맞추세요. @@ -362,7 +362,7 @@ Link to a copy of that Notebook with the prompts filled in and run, showing what - 런타임 커널을 선택하세요. 옵션 1 또는 2를 사용하는 경우, 개발 컨테이너에서 제공하는 기본 Python 3.10.x 커널을 선택하면 됩니다. -이제 연습문제를 실행할 준비가 되었습니다. 여기서는 _정답과 오답_이 없습니다. 대신, 시행착오를 통해 옵션을 탐색하고, 주어진 모델과 응용 프로그램 도메인에 대한 직관을 구축하는 것입니다. +이제 연습문제를 실행할 준비가 되었습니다. 여기서는 *정답과 오답*이 없습니다. 대신, 시행착오를 통해 옵션을 탐색하고, 주어진 모델과 응용 프로그램 도메인에 대한 직관을 구축하는 것입니다. _이러한 이유로 이 레슨에는 코드 솔루션 세그먼트가 없습니다. 대신, 노트북에는 "My Solution:"이라는 제목의 Markdown 셀이 있어 참고용으로 한 가지 예시 출력을 보여줍니다._ diff --git a/04-prompt-engineering-fundamentals/translations/pt-br/README.md b/04-prompt-engineering-fundamentals/translations/pt-br/README.md index 21adfb946..3bc1c7ab3 100644 --- a/04-prompt-engineering-fundamentals/translations/pt-br/README.md +++ b/04-prompt-engineering-fundamentals/translations/pt-br/README.md @@ -1,6 +1,6 @@ # Fundamentos de Engenharia de Prompt -[![Prompt Engineering Fundamentals](../../images/04-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=d54c0c69-b183-4a6c-80ed-8b1a8f299cff?WT.mc_id=academic-105485-koreyst) +[![Prompt Engineering Fundamentals](../../images/04-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson4-gh) A forma como você escreve seu prompt para o LLM importa. Um prompt cuidadosamente elaborado pode alcançar um resultado melhor do que um que não é. Mas o que são esses conceitos, prompt, Engenharia de Prompt e como posso melhorar o que envio para o LLM? Perguntas como essas são o que este capítulo e o próximo estão procurando responder. diff --git a/05-advanced-prompts/README.md b/05-advanced-prompts/README.md index e8150ca5b..b7e2e4629 100644 --- a/05-advanced-prompts/README.md +++ b/05-advanced-prompts/README.md @@ -1,6 +1,6 @@ # Creating Advanced prompts -[![Creating Advanced Prompts](./images/05-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=f3615e46-dbca-477c-832d-21eef95cd9f3?WT.mc_id=academic-105485-koreyst) +[![Creating Advanced Prompts](./images/05-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson5-gh) Let's recap some learnings from the previous chapter: @@ -234,32 +234,32 @@ def customers(): AI Answer: - ```text - Sure, here are three suggestions to improve the code: +```text +Sure, here are three suggestions to improve the code: - Import the correct module: The first line should import Flask instead of flask. The correct import statement should be from flask import Flask. +Import the correct module: The first line should import Flask instead of flask. The correct import statement should be from flask import Flask. - Add a main function: Add a if __name__ == '__main__': block to the end of the file to run the application when the file is executed. +Add a main function: Add a if __name__ == '__main__': block to the end of the file to run the application when the file is executed. - Use f-strings: Use f-strings to format the return statements in the route functions. For example, return 'Products' can be changed to return f'This is the {request.path} page'. - ``` +Use f-strings: Use f-strings to format the return statements in the route functions. For example, return 'Products' can be changed to return f'This is the {request.path} page'. +``` - ```python - from flask import Flask, request +```python +from flask import Flask, request - app = Flask(__name__) +app = Flask(__name__) - @app.route('/products') - def products(): - return f'This is the {request.path} page' +@app.route('/products') +def products(): + return f'This is the {request.path} page' - @app.route('/customers') - def customers(): - return f'This is the {request.path} page' +@app.route('/customers') +def customers(): + return f'This is the {request.path} page' - if __name__ == '__main__': - app.run() - ``` +if __name__ == '__main__': + app.run() +``` As you can see, the above AI response is improving the first suggested code thanks to critiquing the first answer. @@ -278,41 +278,41 @@ Here's an example prompt: > prompt: How can I create a crisis plan to mitigate a pandemic in 5 steps? > LLM answer: - ```text - 1. Identify the risks - 1. Identify the stakeholders - 1. Identify the resources - 1. Identify the actions - 1. Identify the communication channels - ``` +```text +1. Identify the risks +1. Identify the stakeholders +1. Identify the resources +1. Identify the actions +1. Identify the communication channels +``` It's identified 5 steps, but can we determine if this is correct? Let's ask the LLM to explain each step: > prompt: Explain the first step in more detail, what are the risks in detail with a pandemic? - ```text - The risks are the following: +```text +The risks are the following: - - Loss of life - - Loss of business - - Loss of reputation - - Loss of customers - - Loss of employees - ``` +- Loss of life +- Loss of business +- Loss of reputation +- Loss of customers +- Loss of employees +``` At this point, we want to make sure the LLM is correct so we ask it to explain the first risk in more detail and hope it's consistent with the answer above: > prompt: In a Pandemic, which is the biggest risk and why? - ```text - The biggest risk is loss of life because it's the most important thing to protect. - ``` +```text +The biggest risk is loss of life because it's the most important thing to protect. +``` > What are the two biggest risks in a pandemic? - ```text - The two biggest risks are loss of life and loss of business. - ``` +```text +The two biggest risks are loss of life and loss of business. +``` At this point, the LLM is consistent and mentions "life" and "business" as the top two risks. We can now continue to the next step and feel fairly confident. However, we shouldn't trust the LLM blindly, we should always verify the output. @@ -322,107 +322,107 @@ LLMs are nondeterministic by nature, meaning that you will get different results > "Generate code for a Python Web API" - ```python - # Import necessary modules - import flask - from flask import request, jsonify +```python +# Import necessary modules +import flask +from flask import request, jsonify - # Create a Flask app - app = flask.Flask(__name__) +# Create a Flask app +app = flask.Flask(__name__) - # Create a route for the API - @app.route('/api', methods=['GET']) - def api(): - # Get the data from the request - data = request.args +# Create a route for the API +@app.route('/api', methods=['GET']) +def api(): + # Get the data from the request + data = request.args - # Process the data - result = process_data(data) + # Process the data + result = process_data(data) - # Return the result as JSON - return jsonify(result) + # Return the result as JSON + return jsonify(result) - # Function to process the data - def process_data(data): - # Do something with the data - result = data + 1 +# Function to process the data +def process_data(data): + # Do something with the data + result = data + 1 - # Return the result - return result + # Return the result + return result - # Run the app - if __name__ == '__main__': - app.run() +# Run the app +if __name__ == '__main__': + app.run() - ``` +``` Running the same prompt again generates a slightly different response: - ```python - #import necessary packages - import flask - from flask import request, jsonify - - #create the Flask application - app = flask.Flask(__name__) - app.config["DEBUG"] = True - - #create a list of books - books = [ - {'id': 0, - 'title': 'A Fire Upon the Deep', - 'author': 'Vernor Vinge', - 'first_sentence': 'The coldsleep itself was dreamless.', - 'year_published': '1992'}, - {'id': 1, - 'title': 'The Ones Who Walk Away From Omelas', - 'author': 'Ursula K. Le Guin', - 'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.', - 'published': '1973'}, - {'id': 2, - 'title': 'Dhalgren', - 'author': 'Samuel R. Delany', - 'first_sentence': 'to wound the autumnal city.', - 'published': '1975'} - ] - - #create an endpoint for the API - @app.route('/', methods=['GET']) - def home(): - return '''

Books API

-

A prototype API for retrieving books.

''' - - #create an endpoint to return all books - @app.route('/api/v1/resources/books/all', methods=['GET']) - def api_all(): - return jsonify(books) - - #create an endpoint to return a single book - @app.route('/api/v1/resources/books', methods=['GET']) - def api_id(): - #check if an ID was provided as part of the URL - #if ID is provided, assign it to a variable - #if no ID is provided, display an error - if 'id' in request.args: - id = int(request.args['id']) - else: - return "Error: No id field provided. Please specify an id." - - #create an empty list for our results - results = [] - - #loop through the data and match results that fit the requested ID - #IDs are unique, but other fields might return many results - for book in books: - if book['id'] == id: - results.append(book) - - #use the jsonify function from Flask to convert our list of - #Python dictionaries to the JSON format - return jsonify(results) - - app.run() - ``` +```python +#import necessary packages +import flask +from flask import request, jsonify + +#create the Flask application +app = flask.Flask(__name__) +app.config["DEBUG"] = True + +#create a list of books +books = [ + {'id': 0, + 'title': 'A Fire Upon the Deep', + 'author': 'Vernor Vinge', + 'first_sentence': 'The coldsleep itself was dreamless.', + 'year_published': '1992'}, + {'id': 1, + 'title': 'The Ones Who Walk Away From Omelas', + 'author': 'Ursula K. Le Guin', + 'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.', + 'published': '1973'}, + {'id': 2, + 'title': 'Dhalgren', + 'author': 'Samuel R. Delany', + 'first_sentence': 'to wound the autumnal city.', + 'published': '1975'} +] + +#create an endpoint for the API +@app.route('/', methods=['GET']) +def home(): + return '''

Books API

+

A prototype API for retrieving books.

''' + +#create an endpoint to return all books +@app.route('/api/v1/resources/books/all', methods=['GET']) +def api_all(): + return jsonify(books) + +#create an endpoint to return a single book +@app.route('/api/v1/resources/books', methods=['GET']) +def api_id(): + #check if an ID was provided as part of the URL + #if ID is provided, assign it to a variable + #if no ID is provided, display an error + if 'id' in request.args: + id = int(request.args['id']) + else: + return "Error: No id field provided. Please specify an id." + + #create an empty list for our results + results = [] + + #loop through the data and match results that fit the requested ID + #IDs are unique, but other fields might return many results + for book in books: + if book['id'] == id: + results.append(book) + + #use the jsonify function from Flask to convert our list of + #Python dictionaries to the JSON format + return jsonify(results) + +app.run() +``` > So is the varied output a problem? @@ -436,137 +436,137 @@ Temperature is a value between 0 and 1, where 0 is the most deterministic and 1 > "Generate code for a Python Web API" - ```python - #import necessary libraries - import flask - from flask import request, jsonify +```python +#import necessary libraries +import flask +from flask import request, jsonify - #create an instance of the Flask class - app = flask.Flask(__name__) +#create an instance of the Flask class +app = flask.Flask(__name__) - #create an endpoint for the API - @app.route('/api/v1/endpoint', methods=['GET']) - def api_endpoint(): - #get the request data - data = request.get_json() +#create an endpoint for the API +@app.route('/api/v1/endpoint', methods=['GET']) +def api_endpoint(): + #get the request data + data = request.get_json() - #process the data - result = process_data(data) + #process the data + result = process_data(data) - #return the result - return jsonify(result) + #return the result + return jsonify(result) - #function to process the data - def process_data(data): - #process the data - result = {'result': 'success'} +#function to process the data +def process_data(data): + #process the data + result = {'result': 'success'} - #return the result - return result + #return the result + return result - #run the Flask app - if __name__ == '__main__': - app.run() +#run the Flask app +if __name__ == '__main__': + app.run() - ``` +``` Running the prompt again gives us this outcome: - ```python - #import necessary libraries - import flask - from flask import request, jsonify +```python +#import necessary libraries +import flask +from flask import request, jsonify - #create a Flask app - app = flask.Flask(__name__) +#create a Flask app +app = flask.Flask(__name__) - #create a route for the API - @app.route('/api', methods=['GET']) - def api_call(): - #get the data from the request - data = request.get_json() +#create a route for the API +@app.route('/api', methods=['GET']) +def api_call(): + #get the data from the request + data = request.get_json() - #process the data - result = process_data(data) + #process the data + result = process_data(data) - #return the result - return jsonify(result) + #return the result + return jsonify(result) - #define the process_data function - def process_data(data): - #do something with the data - result = data + 1 +#define the process_data function +def process_data(data): + #do something with the data + result = data + 1 - #return the result - return result + #return the result + return result - #run the app - if __name__ == '__main__': - app.run() +#run the app +if __name__ == '__main__': + app.run() - ``` +``` There's only a tiny difference between these two outputs. Let's do the opposite this time, let's set the temperature to 0.9: - ```python - # Import necessary libraries - import flask - from flask import request, jsonify +```python +# Import necessary libraries +import flask +from flask import request, jsonify - # Create a Flask app - app = flask.Flask(__name__) +# Create a Flask app +app = flask.Flask(__name__) - # Create a route for the API - @app.route('/api', methods=['GET']) - def api_call(): - # Get the data from the request - data = request.args +# Create a route for the API +@app.route('/api', methods=['GET']) +def api_call(): + # Get the data from the request + data = request.args - # Process the data - result = process_data(data) + # Process the data + result = process_data(data) - # Return the result - return jsonify(result) + # Return the result + return jsonify(result) - # Function to process the data - def process_data(data): - # Do something with the data - result = data + 1 +# Function to process the data +def process_data(data): + # Do something with the data + result = data + 1 - # Return the result - return result + # Return the result + return result - # Run the app - if __name__ == '__main__': - app.run() +# Run the app +if __name__ == '__main__': + app.run() - ``` +``` and the second attempt at 0.9 as temperature value: - ```python - import flask - from flask import request, jsonify +```python +import flask +from flask import request, jsonify - # create the Flask app - app = flask.Flask(__name__) - app.config['DEBUG'] = True +# create the Flask app +app = flask.Flask(__name__) +app.config['DEBUG'] = True - # create some test data - books = [ - {'id': 0, 'title': 'A Fire Upon The Deep', 'author': 'Vernor Vinge', 'first_sentence': 'The coldsleep itself was dreamless.', 'year_published': '1992'}, - {'id': 1, 'title': 'The Ones Who Walk Away From Omelas', 'author': 'Ursula K. Le Guin', 'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.', 'published': '1973'}, - {'id': 2, 'title': 'Dhalgren', 'author': 'Samuel R. Delany', 'first_sentence': 'to wound the autumnal city.', 'published': '1975'} - ] +# create some test data +books = [ + {'id': 0, 'title': 'A Fire Upon The Deep', 'author': 'Vernor Vinge', 'first_sentence': 'The coldsleep itself was dreamless.', 'year_published': '1992'}, + {'id': 1, 'title': 'The Ones Who Walk Away From Omelas', 'author': 'Ursula K. Le Guin', 'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.', 'published': '1973'}, + {'id': 2, 'title': 'Dhalgren', 'author': 'Samuel R. Delany', 'first_sentence': 'to wound the autumnal city.', 'published': '1975'} +] - # create an endpoint - @app.route('/', methods=['GET']) - def home(): - return '''

Welcome to our book API!

''' +# create an endpoint +@app.route('/', methods=['GET']) +def home(): + return '''

Welcome to our book API!

''' - @app.route('/api/v1/resources/books +@app.route('/api/v1/resources/books - ``` +``` As you can see, the results couldn't be more varied. @@ -590,19 +590,19 @@ Here are some good practices to consider: Here's code in Python showing how to build a simple API using Flask: - ```python - from flask import Flask, request +```python +from flask import Flask, request - app = Flask(__name__) +app = Flask(__name__) - @app.route('/') - def hello(): - name = request.args.get('name', 'World') - return f'Hello, {name}!' +@app.route('/') +def hello(): + name = request.args.get('name', 'World') + return f'Hello, {name}!' - if __name__ == '__main__': - app.run() - ``` +if __name__ == '__main__': + app.run() +``` Use an AI assistant like GitHub Copilot or ChatGPT and apply the "self-refine" technique to improve the code. diff --git a/05-advanced-prompts/images/05-lesson-banner.png b/05-advanced-prompts/images/05-lesson-banner.png index 58b2cd8f9..9f2c49d00 100644 Binary files a/05-advanced-prompts/images/05-lesson-banner.png and b/05-advanced-prompts/images/05-lesson-banner.png differ diff --git a/05-advanced-prompts/translations/cn/README.md b/05-advanced-prompts/translations/cn/README.md index df634c1bd..17e234091 100644 --- a/05-advanced-prompts/translations/cn/README.md +++ b/05-advanced-prompts/translations/cn/README.md @@ -1,6 +1,6 @@ # 第五章:创建高级的提示工程技巧 -[![Creating Advanced Prompts](../../images/05-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=f3615e46-dbca-477c-832d-21eef95cd9f3?WT.mc_id=academic-105485-koreyst) +[![Creating Advanced Prompts](../../images/05-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson5-gh) 让我们回顾一下上一章的一些知识: diff --git a/05-advanced-prompts/translations/ja-jp/README.md b/05-advanced-prompts/translations/ja-jp/README.md index 0c1b61499..04ee094e5 100644 --- a/05-advanced-prompts/translations/ja-jp/README.md +++ b/05-advanced-prompts/translations/ja-jp/README.md @@ -1,6 +1,6 @@ # 高度なプロンプトの作成 -[![高度なプロンプトの作成](../../images/05-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=f3615e46-dbca-477c-832d-21eef95cd9f3?WT.mc_id=academic-105485-yoterada) +[![高度なプロンプトの作成](../../images/05-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://aka.ms/gen-ai-lesson5-gh) 前章までの学習内容をいくつかおさらいしましょう。 diff --git a/05-advanced-prompts/translations/ko/README.md b/05-advanced-prompts/translations/ko/README.md index 1b89bc47a..71886844a 100644 --- a/05-advanced-prompts/translations/ko/README.md +++ b/05-advanced-prompts/translations/ko/README.md @@ -1,6 +1,6 @@ # 고급 프롬프트 생성 -[![Creating Advanced Prompts](../../images/05-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://youtu.be/32GBH6BTWZQ?WT.mc_id=academic-105485-koreyst) +[![Creating Advanced Prompts](../../images/05-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson5-gh) 이전 장에서 배운 내용을 간단히 되짚어보겠습니다: @@ -74,8 +74,8 @@ LLM을 프롬프트하기 위해 몇 가지 기본적인 기법을 사용할 수 Chain-of-thought는 LLM을 일련의 단계를 거쳐 가르치는 매우 흥미로운 기술입니다. 이 아이디어는 LLM에게 어떻게 해야 하는지 이해시키는 방법입니다. 다음 예시를 고려해보세요. Chain-of-thought를 사용하는 경우와 그렇지 않은 경우를 비교해보세요: - - 프롬프트: "앨리스는 사과를 5개 가지고 있습니다. 3개의 사과를 던지고, 2개를 밥에게 주었고, 밥이 하나를 다시 돌려줬을 때, 앨리스는 몇 개의 사과를 가지고 있을까요?" - - 답변: 5 +- 프롬프트: "앨리스는 사과를 5개 가지고 있습니다. 3개의 사과를 던지고, 2개를 밥에게 주었고, 밥이 하나를 다시 돌려줬을 때, 앨리스는 몇 개의 사과를 가지고 있을까요?" +- 답변: 5 LLM은 5라고 답했지만, 이는 잘못된 답입니다. 정답은 계산에 따라 (5 - 3 - 2 + 1 = 1) 1개의 사과입니다. @@ -90,10 +90,10 @@ Chain-of-thought를 시도해보겠습니다. Chain-of-thought를 적용하는 다음과 같이 해보겠습니다: - 프롬프트: "리사는 사과를 7개 가지고 있습니다. 1개의 사과를 던지고, 4개의 사과를 바트에게 주고, 바트가 하나를 다시 돌려줍니다: - 7 - 1 = 6 - 6 - 4 = 2 - 2 + 1 = 3 - 앨리스는 사과를 5개 가지고 있습니다. 3개의 사과를 던지고, 2개를 밥에게 주고, 밥이 하나를 다시 돌려준다면, 앨리스는 몇 개의 사과를 가지고 있을까요?" + 7 - 1 = 6 + 6 - 4 = 2 + 2 + 1 = 3 + 앨리스는 사과를 5개 가지고 있습니다. 3개의 사과를 던지고, 2개를 밥에게 주고, 밥이 하나를 다시 돌려준다면, 앨리스는 몇 개의 사과를 가지고 있을까요?" - 답변: 1 비슷한 예제, 계산 방법, 그리고 원래의 프롬프트를 포함한 긴 프롬프트를 작성하고, 올바른 답인 1에 도달합니다. @@ -108,7 +108,7 @@ Chain-of-thought는 매우 강력한 기술임을 알 수 있습니다. ```text {{company}}: {{company_name}} - {{products}}: + {{products}}: {{products_list}} 다음 예산과 요구 사항에 따라 보험을 제안해주세요: 예산: {{budget}} @@ -121,9 +121,9 @@ Chain-of-thought는 매우 강력한 기술임을 알 수 있습니다. ```text 보험 회사: ACME Insurance - 보험 상품 (월 별 비용): + 보험 상품 (월 별 비용): - 자동차, 저렴함, 500 USD - - 자동차, 비쌈, 1100 USD + - 자동차, 비쌈, 1100 USD - 주택, 저렴함, 600 USD - 주택, 비쌈, 1200 USD - 생명, 저렴함, 100 USD @@ -139,9 +139,9 @@ Chain-of-thought는 매우 강력한 기술임을 알 수 있습니다. , and Life insurance 예산과 요구 사항에 따라 ACME 보험으로부터 다음과 같은 보험 패키지를 제안합니다: - - 자동차, 저렴함, 500 USD - - 주택, 저렴함, 600 USD - - 생명, 저렴함, 100 USD + - 자동차, 저렴함, 500 USD + - 주택, 저렴함, 600 USD + - 생명, 저렴함, 100 USD 총 비용: $1,200 USD ``` @@ -149,9 +149,9 @@ Chain-of-thought는 매우 강력한 기술임을 알 수 있습니다. ```text 보험 회사: ACME Insurance - 보험 상품 (월 별 비용): + 보험 상품 (월 별 비용): - 유형: 자동차, 저렴함, 비용: 500 USD - - 유형: 자동차, 비쌈, 비용: 1100 USD + - 유형: 자동차, 비쌈, 비용: 1100 USD - 유형: 주택, 저렴함, 비용: 600 USD - 유형: 주택, 비쌈, 비용: 1200 USD - 유형: 생명, 저렴함, 비용: 100 USD @@ -206,11 +206,11 @@ AI 답변: ```python import flask app = Flask(__name__) - + @app.route('/products') def products(): return 'Products' - + @app.route('/customers') def customers(): return 'Customers' @@ -222,27 +222,27 @@ AI 답변: ```text 물론, 다음은 코드를 개선하기 위한 세 가지 제안입니다: - + 올바른 모듈을 가져오세요: 첫 번째 줄은 flask 대신에 Flask를 가져와야 합니다. 올바른 import 문은 from flask import Flask여야 합니다. - + main 함수를 추가하세요: 파일이 실행될 때 애플리케이션을 실행하기 위해 if __name__ == '__main__': 블록을 파일의 끝에 추가하세요. - + f-strings를 사용하세요: route 함수에서 반환문을 포맷팅하기 위해 f-strings를 사용하세요. 예를 들어, return 'Products'를 return f'This is the {request.path} page'로 변경할 수 있습니다. ``` ```python from flask import Flask, request - + app = Flask(__name__) - + @app.route('/products') def products(): return f'This is the {request.path} page' - + @app.route('/customers') def customers(): return f'This is the {request.path} page' - + if __name__ == '__main__': app.run() ``` @@ -261,7 +261,7 @@ Maieutic prompting은 자기 개선 (Self-refine)과 유사한 기술이지만, 다음은 예시 프롬프트입니다: -> 프롬프트: 5단계로 팬데믹을 완화하기 위한 위기 대응 계획을 어떻게 작성할 수 있을까요? +> 프롬프트: 5단계로 팬데믹을 완화하기 위한 위기 대응 계획을 어떻게 작성할 수 있을까요? LLM 답변: @@ -279,7 +279,7 @@ LLM 답변: ```text 다음은 위험 요소입니다: - + - 생명의 손실 - 사업의 손실 - 평판의 손실 @@ -313,34 +313,34 @@ LLM은 본질적으로 결정론적이지 않으므로, 동일한 프롬프트 # 필요한 라이브러리 가져오기 import flask from flask import request, jsonify - + # Flask 앱 인스턴스 생성 app = flask.Flask(__name__) - + # API를 위한 엔드포인트 생성 @app.route('/api', methods=['GET']) def api(): # 요청 데이터 가져오기 data = request.args - + # 데이터 처리 result = process_data(data) - + # 결과를 JSON 형식으로 반환 return jsonify(result) - + # 데이터 처리 함수 def process_data(data): # 데이터 처리 수행 result = data + 1 - + # 결과 반환 return result - + # 앱 실행 if __name__ == '__main__': app.run() - + ``` 동일한 프롬프트를 다시 실행하면 약간 다른 응답이 생성됩니다: @@ -349,11 +349,11 @@ LLM은 본질적으로 결정론적이지 않으므로, 동일한 프롬프트 # 필요한 패키지 가져오기 import flask from flask import request, jsonify - + # Flask 앱 생성 app = flask.Flask(__name__) app.config["DEBUG"] = True - + # 책 목록 생성 books = [ {'id': 0, @@ -372,18 +372,18 @@ LLM은 본질적으로 결정론적이지 않으므로, 동일한 프롬프트 'first_sentence': 'to wound the autumnal city.', 'published': '1975'} ] - + # API를 위한 엔드포인트 생성 @app.route('/', methods=['GET']) def home(): return '''

Books API

책을 검색하기 위한 프로토 타입 API입니다.

''' - + # 모든 책 반환을 위한 엔드포인트 생성 @app.route('/api/v1/resources/books/all', methods=['GET']) def api_all(): return jsonify(books) - + # 단일 책 반환을 위한 엔드포인트 생성 @app.route('/api/v1/resources/books', methods=['GET']) def api_id(): @@ -394,19 +394,19 @@ LLM은 본질적으로 결정론적이지 않으므로, 동일한 프롬프트 id = int(request.args['id']) else: return "오류: ID 필드가 제공되지 않았습니다. ID를 지정해주세요." - + # 결과를 저장할 빈 리스트 생성 results = [] - + # 데이터를 반복하며 요청된 ID와 일치하는 결과 찾기 # ID는 고유하지만 다른 필드는 여러 결과를 반환할 수 있음 for book in books: if book['id'] == id: results.append(book) - + # Flask의 jsonify 함수를 사용하여 Python 사전의 리스트를 JSON 형식으로 변환 return jsonify(results) - + app.run() ``` @@ -426,34 +426,34 @@ temperature는 0과 1 사이의 값으로, 0은 가장 결정적이고 1은 가 # 필요한 라이브러리 가져오기 import flask from flask import request, jsonify - + # Flask 앱 생성 app = flask.Flask(__name__) - + # API를 위한 엔드포인트 생성 @app.route('/api/v1/endpoint', methods=['GET']) def api_endpoint(): # 요청 데이터 가져오기 data = request.get_json() - + # 데이터 처리 result = process_data(data) - + # 결과 반환 return jsonify(result) - + # 데이터 처리 함수 정의 def process_data(data): # 데이터 처리 result = {'result': 'success'} - + # 결과 반환 return result - + # Flask 앱 실행 if __name__ == '__main__': app.run() - + ``` 프롬프트를 다시 실행하면 다음과 같은 결과가 나옵니다: @@ -462,34 +462,34 @@ temperature는 0과 1 사이의 값으로, 0은 가장 결정적이고 1은 가 # 필요한 라이브러리 가져오기 import flask from flask import request, jsonify - + # Flask 앱 생성 app = flask.Flask(__name__) - + # API를 위한 엔드포인트 생성 @app.route('/api', methods=['GET']) def api_call(): # 요청 데이터 가져오기 data = request.get_json() - + # 데이터 처리 result = process_data(data) - + # 결과 반환 return jsonify(result) - + # 데이터 처리 함수 정의 def process_data(data): # 데이터 처리 result = data + 1 - + # 결과 반환 return result - + # Flask 앱 실행 if __name__ == '__main__': app.run() - + ``` 이 두 출력 사이에는 아주 작은 차이만 있습니다. 이번에는 반대로 temperature를 0.9로 설정해 보겠습니다: @@ -498,34 +498,34 @@ temperature는 0과 1 사이의 값으로, 0은 가장 결정적이고 1은 가 # 필요한 라이브러리 가져오기 import flask from flask import request, jsonify - + # Flask 앱 생성 app = flask.Flask(__name__) - + # API를 위한 엔드포인트 생성 @app.route('/api', methods=['GET']) def api_call(): # 요청 데이터 가져오기 data = request.args - + # 데이터 처리 result = process_data(data) - + # 결과 반환 return jsonify(result) - + # 데이터 처리 함수 정의 def process_data(data): # 데이터 처리 result = data + 1 - + # 결과 반환 return result - + # Flask 앱 실행 if __name__ == '__main__': app.run() - + ``` 그리고 temperature 값을 0.9로 설정한 두 번째 시도: @@ -533,25 +533,25 @@ temperature는 0과 1 사이의 값으로, 0은 가장 결정적이고 1은 가 ```python import flask from flask import request, jsonify - + # Flask 앱 생성 app = flask.Flask(__name__) app.config['DEBUG'] = True - + # 테스트 데이터 생성 books = [ {'id': 0, 'title': 'A Fire Upon The Deep', 'author': 'Vernor Vinge', 'first_sentence': 'The coldsleep itself was dreamless.', 'year_published': '1992'}, {'id': 1, 'title': 'The Ones Who Walk Away From Omelas', 'author': 'Ursula K. Le Guin', 'first_sentence': 'With a clamor of bells that set the swallows soaring, the Festival of Summer came to the city Omelas, bright-towered by the sea.', 'published': '1973'}, {'id': 2, 'title': 'Dhalgren', 'author': 'Samuel R. Delany', 'first_sentence': 'to wound the autumnal city.', 'published': '1975'} ] - + # 엔드포인트 생성 @app.route('/', methods=['GET']) def home(): return '''

도서 API에 오신 것을 환영합니다!

''' - + @app.route('/api/v1/resources/books - + ``` 보시다시피, 결과는 매우 다양합니다. @@ -578,14 +578,14 @@ temperature는 0과 1 사이의 값으로, 0은 가장 결정적이고 1은 가 ```python from flask import Flask, request - + app = Flask(__name__) - + @app.route('/') def hello(): name = request.args.get('name', 'World') return f'Hello, {name}!' - + if __name__ == '__main__': app.run() ``` diff --git a/05-advanced-prompts/translations/pt-br/README.md b/05-advanced-prompts/translations/pt-br/README.md index 9d5728c35..355b53c1e 100644 --- a/05-advanced-prompts/translations/pt-br/README.md +++ b/05-advanced-prompts/translations/pt-br/README.md @@ -1,6 +1,6 @@ # Criando prompts avançados -[![Creating Advanced Prompts](../../images/05-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=f3615e46-dbca-477c-832d-21eef95cd9f3?WT.mc_id=academic-105485-koreyst) +[![Creating Advanced Prompts](../../images/05-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson5-gh) Vamos recapitular algumas aprendizagens do capítulo anterior: diff --git a/06-text-generation-apps/README.md b/06-text-generation-apps/README.md index c5dc041eb..65bbf1743 100644 --- a/06-text-generation-apps/README.md +++ b/06-text-generation-apps/README.md @@ -1,6 +1,6 @@ # Building Text Generation Applications -[![Building Text Generation Applications](./images/06-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=bf3f3528-9871-4628-8616-b4b03cb23dcd?WT.mc_id=academic-105485-koreyst) +[![Building Text Generation Applications](./images/06-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson6-gh) > _(Click the image above to view video of this lesson)_ diff --git a/06-text-generation-apps/images/06-lesson-banner.png b/06-text-generation-apps/images/06-lesson-banner.png index b852b288a..b79977997 100644 Binary files a/06-text-generation-apps/images/06-lesson-banner.png and b/06-text-generation-apps/images/06-lesson-banner.png differ diff --git a/06-text-generation-apps/translations/cn/README.md b/06-text-generation-apps/translations/cn/README.md index 36b5ef213..4cbe1d58c 100644 --- a/06-text-generation-apps/translations/cn/README.md +++ b/06-text-generation-apps/translations/cn/README.md @@ -1,6 +1,6 @@ # 第六章:创建文本生成应用 -[![Building Text Generation Applications](../../images/06-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=bf3f3528-9871-4628-8616-b4b03cb23dcd?WT.mc_id=academic-105485-koreyst) +[![Building Text Generation Applications](../../images/06-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson6-gh) > _(点击该图片看本章导学视频)_ @@ -56,7 +56,7 @@ 您需要找到一种与 LLMs 结合的方法,通常使用以下两种方法: -- 使用API,您将根据提示构建 Web 请求并返回生成的文本。 +- 使用 API,您将根据提示构建 Web 请求并返回生成的文本。 - 使用库,库有助于封装 API 调用,使其更易于使用。 ## Libraries/SDKs diff --git a/06-text-generation-apps/translations/ja-jp/README.md b/06-text-generation-apps/translations/ja-jp/README.md index 4b0a834a5..3d3dad64e 100644 --- a/06-text-generation-apps/translations/ja-jp/README.md +++ b/06-text-generation-apps/translations/ja-jp/README.md @@ -1,6 +1,6 @@ # テキスト生成アプリケーションの構築 -[![Building Text Generation Applications](../../images/06-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=bf3f3528-9871-4628-8616-b4b03cb23dcdt?WT.mc_id=academic-105485-yoterada) +[![Building Text Generation Applications](../../images/06-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://aka.ms/gen-ai-lesson6-gh) > _(上記の画像をクリックすると、レッスン・ビデオを表示します)_ diff --git a/06-text-generation-apps/translations/ko/README.md b/06-text-generation-apps/translations/ko/README.md index 276299feb..e059ca43e 100644 --- a/06-text-generation-apps/translations/ko/README.md +++ b/06-text-generation-apps/translations/ko/README.md @@ -1,8 +1,8 @@ # 텍스트 생성 애플리케이션 개발 -[![Building Text Generation Applications](../../images/06-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://youtu.be/5jKHzY6-4s8?WT.mc_id=academic-105485-koreyst) +[![Building Text Generation Applications](../../images/06-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson6-gh) -> *(위의 이미지를 클릭하여 이 수업의 동영상을 시청하세요.)* +> _(위의 이미지를 클릭하여 이 수업의 동영상을 시청하세요.)_ 지금까지 이 커리큘럼을 통해 프롬프트와 "프롬프트 엔지니어링"이라는 전체적인 개념과 같은 핵심 개념들을 보셨습니다. ChatGPT, Office 365, Microsoft Power Platform 등 다양한 도구들은 프롬프트를 사용하여 어떤 작업을 수행하는 데 도움을 주는 것을 확인하실 수 있습니다. @@ -107,7 +107,7 @@ pip install openai > API 키를 코드와 분리하는 것이 좋습니다. 이를 위해 환경 변수를 사용할 수 있습니다. > > - 환경 변수 `OPENAI_API_KEY`를 API 키로 설정하세요. -> `export OPENAI_API_KEY='sk-...'` +> `export OPENAI_API_KEY='sk-...'` ### Azure 설정 구성 @@ -127,8 +127,7 @@ openai.api_base = os.getenv("API_BASE") - `api_version`은 사용하려는 API의 버전입니다. 작성 시점에서 최신 버전은 `2023-05-15`입니다. - `api_base`는 API의 엔드포인트입니다. API 키 옆에 Azure Portal에서 찾을 수 있습니다. -> [!NOTE] -> `os.getenv`는 환경 변수를 읽는 함수입니다. `OPENAI_API_KEY`와 `API_BASE`와 같은 환경 변수를 읽을 때 사용할 수 있습니다. 이러한 환경 변수는 터미널에서 설정하거나 `dotenv`와 같은 라이브러리를 사용하여 설정할 수 있습니다. +> [!NOTE] > `os.getenv`는 환경 변수를 읽는 함수입니다. `OPENAI_API_KEY`와 `API_BASE`와 같은 환경 변수를 읽을 때 사용할 수 있습니다. 이러한 환경 변수는 터미널에서 설정하거나 `dotenv`와 같은 라이브러리를 사용하여 설정할 수 있습니다. ## 텍스트 생성 @@ -164,39 +163,39 @@ print(completion.choices[0].message.content) 1. 가상 환경을 생성하고 openai를 설치하세요: - ```bash - python -m venv venv - source venv/bin/activate - pip install openai - ``` - + ```bash + python -m venv venv + source venv/bin/activate + pip install openai + ``` + > [!NOTE] > Windows를 사용하는 경우 `source venv/bin/activate` 대신 `venv\Scripts\activate`를 입력하세요. > [!NOTE] > Azure Open AI 키를 찾으려면 [https://portal.azure.com/](https://portal.azure.com/?WT.mc_id=academic-105485-koreyst)로 이동하여 `Open AI`를 검색한 다음 `Open AI 리소스`를 선택하고 `Keys and Endpoint`를 선택하고 `Key 1` 값을 복사하세요. -1. *app.py* 파일을 생성하고 다음 코드를 추가하세요: +1. _app.py_ 파일을 생성하고 다음 코드를 추가하세요: - ```python - import openai + ```python + import openai - openai.api_key = "" + openai.api_key = "" - openai.api_type = 'azure' - openai.api_version = '2023-05-15' - openai.api_base = "" - deployment_name = "" + openai.api_type = 'azure' + openai.api_version = '2023-05-15' + openai.api_base = "" + deployment_name = "" - # add your completion code - prompt = "Complete the following: Once upon a time there was a" + # add your completion code + prompt = "Complete the following: Once upon a time there was a" - # make completion - completion = openai.Completion.create(engine= deployment_name, model="davinci-002", prompt=prompt) - - # print response - print(completion.choices[0].text) - ``` + # make completion + completion = openai.Completion.create(engine= deployment_name, model="davinci-002", prompt=prompt) + + # print response + print(completion.choices[0].text) + ``` > [!NOTE] > Azure Open AI를 사용하는 경우, `api_type`을 `azure`로 설정하고 `api_key`를 Azure Open AI 키로 설정해야 합니다. @@ -230,8 +229,8 @@ print(completion.choices[0].message.content) 위의 프롬프트를 주면 다음과 유사한 응답을 받을 수 있습니다: ```output -1. Roasted Chicken and Vegetables: -Ingredients: +1. Roasted Chicken and Vegetables: +Ingredients: - 4 chicken thighs - 2 potatoes, cut into cubes - 2 carrots, cut into cubes @@ -241,8 +240,8 @@ Ingredients: - 1 teaspoon dried oregano - Salt and pepper, to taste -2. Chicken and Potato Stew: -Ingredients: +2. Chicken and Potato Stew: +Ingredients: - 2 tablespoons olive oil - 1 onion, diced - 2 cloves garlic, minced @@ -254,8 +253,8 @@ Ingredients: - 1 cup chicken broth - Salt and pepper, to taste -3. Chicken and Potato Bake: -Ingredients: +3. Chicken and Potato Bake: +Ingredients: - 2 tablespoons olive oil - 2 chicken breasts, cut into cubes - 2 potatoes, cut into cubes @@ -267,8 +266,8 @@ Ingredients: - 1 cup chicken broth - Salt and pepper, to taste -4. Chicken and Potato Soup: -Ingredients: +4. Chicken and Potato Soup: +Ingredients: - 2 tablespoons olive oil - 1 onion, diced - 2 cloves garlic, minced @@ -280,8 +279,8 @@ Ingredients: - 4 cups chicken broth - Salt and pepper, to taste -5. Chicken and Potato Hash: -Ingredients: +5. Chicken and Potato Hash: +Ingredients: - 2 tablespoons olive oil - 2 chicken breasts, cut into cubes - 2 potatoes, cut into cubes @@ -303,8 +302,8 @@ Ingredients: 이제 새로운 결과가 있습니다: ```output -1. Roasted Chicken and Vegetables: -Ingredients: +1. Roasted Chicken and Vegetables: +Ingredients: - 4 chicken thighs - 2 potatoes, cut into cubes - 2 carrots, cut into cubes @@ -313,8 +312,8 @@ Ingredients: - 1 teaspoon dried oregano - Salt and pepper, to taste -2. Chicken and Potato Stew: -Ingredients: +2. Chicken and Potato Stew: +Ingredients: - 2 tablespoons olive oil - 1 onion, diced - 2 chicken breasts, cut into cubes @@ -325,8 +324,8 @@ Ingredients: - 1 cup chicken broth - Salt and pepper, to taste -3. Chicken and Potato Bake: -Ingredients: +3. Chicken and Potato Bake: +Ingredients: - 2 tablespoons olive oil - 2 chicken breasts, cut into cubes - 2 potatoes, cut into cubes @@ -337,8 +336,8 @@ Ingredients: - 1 cup chicken broth - Salt and pepper, to taste -4. Chicken and Potato Soup: -Ingredients: +4. Chicken and Potato Soup: +Ingredients: - 2 tablespoons olive oil - 1 onion, diced - 2 chicken breasts, cut into cubes @@ -349,8 +348,8 @@ Ingredients: - 4 cups chicken broth - Salt and pepper, to taste -5. Chicken and Potato Hash: -Ingredients: +5. Chicken and Potato Hash: +Ingredients: - 2 tablespoons olive oil - 2 chicken breasts, cut into cubes - 2 potatoes, cut into cubes @@ -358,7 +357,7 @@ Ingredients: - 1 onion, diced - 1 teaspoon dried oregano -Shopping List: +Shopping List: - Olive oil - Onion - Thyme @@ -373,50 +372,50 @@ Shopping List: 이제 우리가 시나리오를 플레이했으니, 해당 시나리오와 일치하는 코드를 작성해 봅시다. 다음 단계를 따라주세요: -1. 기존의 *app.py* 파일을 시작점으로 사용합니다. +1. 기존의 _app.py_ 파일을 시작점으로 사용합니다. 2. `prompt` 변수를 찾아서 다음과 같이 코드를 변경합니다: - ```python - prompt = "Show me 5 recipes for a dish with the following ingredients: chicken, potatoes, and carrots. Per recipe, list all the ingredients used" - ``` + ```python + prompt = "Show me 5 recipes for a dish with the following ingredients: chicken, potatoes, and carrots. Per recipe, list all the ingredients used" + ``` - 코드를 실행하면 다음과 유사한 출력이 표시됩니다: + 코드를 실행하면 다음과 유사한 출력이 표시됩니다: - ```output - -Chicken Stew with Potatoes and Carrots: 3 tablespoons oil, 1 onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 bay leaf, 1 thyme sprig, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 1 1/2 cups chicken broth, 1/2 cup dry white wine, 2 tablespoons chopped fresh parsley, 2 tablespoons unsalted butter, 1 1/2 pounds boneless, skinless chicken thighs, cut into 1-inch pieces - -Oven-Roasted Chicken with Potatoes and Carrots: 3 tablespoons extra-virgin olive oil, 1 tablespoon Dijon mustard, 1 tablespoon chopped fresh rosemary, 1 tablespoon chopped fresh thyme, 4 cloves garlic, minced, 1 1/2 pounds small red potatoes, quartered, 1 1/2 pounds carrots, quartered lengthwise, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 1 (4-pound) whole chicken - -Chicken, Potato, and Carrot Casserole: cooking spray, 1 large onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and shredded, 1 potato, peeled and shredded, 1/2 teaspoon dried thyme leaves, 1/4 teaspoon salt, 1/4 teaspoon black pepper, 2 cups fat-free, low-sodium chicken broth, 1 cup frozen peas, 1/4 cup all-purpose flour, 1 cup 2% reduced-fat milk, 1/4 cup grated Parmesan cheese - - -One Pot Chicken and Potato Dinner: 2 tablespoons olive oil, 1 pound boneless, skinless chicken thighs, cut into 1-inch pieces, 1 large onion, chopped, 3 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 bay leaf, 1 thyme sprig, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 2 cups chicken broth, 1/2 cup dry white wine - - -Chicken, Potato, and Carrot Curry: 1 tablespoon vegetable oil, 1 large onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 teaspoon ground coriander, 1 teaspoon ground cumin, 1/2 teaspoon ground turmeric, 1/2 teaspoon ground ginger, 1/4 teaspoon cayenne pepper, 2 cups chicken broth, 1/2 cup dry white wine, 1 (15-ounce) can chickpeas, drained and rinsed, 1/2 cup raisins, 1/2 cup chopped fresh cilantro - ``` + ```output + -Chicken Stew with Potatoes and Carrots: 3 tablespoons oil, 1 onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 bay leaf, 1 thyme sprig, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 1 1/2 cups chicken broth, 1/2 cup dry white wine, 2 tablespoons chopped fresh parsley, 2 tablespoons unsalted butter, 1 1/2 pounds boneless, skinless chicken thighs, cut into 1-inch pieces + -Oven-Roasted Chicken with Potatoes and Carrots: 3 tablespoons extra-virgin olive oil, 1 tablespoon Dijon mustard, 1 tablespoon chopped fresh rosemary, 1 tablespoon chopped fresh thyme, 4 cloves garlic, minced, 1 1/2 pounds small red potatoes, quartered, 1 1/2 pounds carrots, quartered lengthwise, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 1 (4-pound) whole chicken + -Chicken, Potato, and Carrot Casserole: cooking spray, 1 large onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and shredded, 1 potato, peeled and shredded, 1/2 teaspoon dried thyme leaves, 1/4 teaspoon salt, 1/4 teaspoon black pepper, 2 cups fat-free, low-sodium chicken broth, 1 cup frozen peas, 1/4 cup all-purpose flour, 1 cup 2% reduced-fat milk, 1/4 cup grated Parmesan cheese - > 참고: LLM은 결정론적이지 않으므로 프로그램을 실행할 때마다 다른 결과를 얻을 수 있습니다. + -One Pot Chicken and Potato Dinner: 2 tablespoons olive oil, 1 pound boneless, skinless chicken thighs, cut into 1-inch pieces, 1 large onion, chopped, 3 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 bay leaf, 1 thyme sprig, 1/2 teaspoon salt, 1/4 teaspoon black pepper, 2 cups chicken broth, 1/2 cup dry white wine - 좋아요, 어떻게 개선할 수 있는지 알아봅시다. 개선하기 위해 코드가 유연하도록 만들어야 합니다. 따라서 재료와 레시피 수를 개선하고 변경할 수 있어야 합니다. + -Chicken, Potato, and Carrot Curry: 1 tablespoon vegetable oil, 1 large onion, chopped, 2 cloves garlic, minced, 1 carrot, peeled and chopped, 1 potato, peeled and chopped, 1 teaspoon ground coriander, 1 teaspoon ground cumin, 1/2 teaspoon ground turmeric, 1/2 teaspoon ground ginger, 1/4 teaspoon cayenne pepper, 2 cups chicken broth, 1/2 cup dry white wine, 1 (15-ounce) can chickpeas, drained and rinsed, 1/2 cup raisins, 1/2 cup chopped fresh cilantro + ``` -1. 다음과 같이 코드를 변경해 봅시다: + > 참고: LLM은 결정론적이지 않으므로 프로그램을 실행할 때마다 다른 결과를 얻을 수 있습니다. - ```python - no_recipes = input("No of recipes (for example, 5: ") + 좋아요, 어떻게 개선할 수 있는지 알아봅시다. 개선하기 위해 코드가 유연하도록 만들어야 합니다. 따라서 재료와 레시피 수를 개선하고 변경할 수 있어야 합니다. - ingredients = input("List of ingredients (for example, chicken, potatoes, and carrots: ") - - # interpolate the number of recipes into the prompt an ingredients - prompt = f"Show me {no_recipes} recipes for a dish with the following ingredients: {ingredients}. Per recipe, list all the ingredients used" - ``` +3. 다음과 같이 코드를 변경해 봅시다: - 코드를 테스트 실행하면 결과가 다음과 같을 수 있습니다: + ```python + no_recipes = input("No of recipes (for example, 5: ") - ```output - No of recipes (for example, 5: 3 - List of ingredients (for example, chicken, potatoes, and carrots: milk,strawberries + ingredients = input("List of ingredients (for example, chicken, potatoes, and carrots: ") - -Strawberry milk shake: milk, strawberries, sugar, vanilla extract, ice cubes - -Strawberry shortcake: milk, flour, baking powder, sugar, salt, unsalted butter, strawberries, whipped cream - -Strawberry milk: milk, strawberries, sugar, vanilla extract - ``` + # interpolate the number of recipes into the prompt an ingredients + prompt = f"Show me {no_recipes} recipes for a dish with the following ingredients: {ingredients}. Per recipe, list all the ingredients used" + ``` + + 코드를 테스트 실행하면 결과가 다음과 같을 수 있습니다: + + ```output + No of recipes (for example, 5: 3 + List of ingredients (for example, chicken, potatoes, and carrots: milk,strawberries + + -Strawberry milk shake: milk, strawberries, sugar, vanilla extract, ice cubes + -Strawberry shortcake: milk, flour, baking powder, sugar, salt, unsalted butter, strawberries, whipped cream + -Strawberry milk: milk, strawberries, sugar, vanilla extract + ``` ### 필터와 쇼핑 목록 추가로 개선하기 @@ -426,129 +425,128 @@ Shopping List: - **재료 필터링**. 싫어하는 재료나 알레르기 반응이 있는 재료를 필터링할 수 있도록 하고 싶습니다. 이 변경을 위해 기존의 프롬프트를 수정하여 끝에 필터 조건을 추가할 수 있습니다: - ```python - filter = input("Filter (for example, vegetarian, vegan, or gluten-free: ") + ```python + filter = input("Filter (for example, vegetarian, vegan, or gluten-free: ") - prompt = f"Show me {no_recipes} recipes for a dish with the following ingredients: {ingredients}. Per recipe, list all the ingredients used, no {filter}" - ``` + prompt = f"Show me {no_recipes} recipes for a dish with the following ingredients: {ingredients}. Per recipe, list all the ingredients used, no {filter}" + ``` - 위에서는 프롬프트 끝에 `{filter}`를 추가하고 사용자로부터 필터 값을 입력받도록 합니다. + 위에서는 프롬프트 끝에 `{filter}`를 추가하고 사용자로부터 필터 값을 입력받도록 합니다. - 프로그램을 실행하는 예시 입력은 다음과 같을 수 있습니다: + 프로그램을 실행하는 예시 입력은 다음과 같을 수 있습니다: - ```output - No of recipes (for example, 5: 3 - List of ingredients (for example, chicken, potatoes, and carrots: onion,milk - Filter (for example, vegetarian, vegan, or gluten-free: no milk - - 1. French Onion Soup - - Ingredients: - - -1 large onion, sliced - -3 cups beef broth - -1 cup milk - -6 slices french bread - -1/4 cup shredded Parmesan cheese - -1 tablespoon butter - -1 teaspoon dried thyme - -1/4 teaspoon salt - -1/4 teaspoon black pepper - - Instructions: - - 1. In a large pot, sauté onions in butter until golden brown. - 2. Add beef broth, milk, thyme, salt, and pepper. Bring to a boil. - 3. Reduce heat and simmer for 10 minutes. - 4. Place french bread slices on soup bowls. - 5. Ladle soup over bread. - 6. Sprinkle with Parmesan cheese. - - 2. Onion and Potato Soup - - Ingredients: - - -1 large onion, chopped - -2 cups potatoes, diced - -3 cups vegetable broth - -1 cup milk - -1/4 teaspoon black pepper - - Instructions: - - 1. In a large pot, sauté onions in butter until golden brown. - 2. Add potatoes, vegetable broth, milk, and pepper. Bring to a boil. - 3. Reduce heat and simmer for 10 minutes. - 4. Serve hot. - - 3. Creamy Onion Soup - - Ingredients: - - -1 large onion, chopped - -3 cups vegetable broth - -1 cup milk - -1/4 teaspoon black pepper - -1/4 cup all-purpose flour - -1/2 cup shredded Parmesan cheese - - Instructions: - - 1. In a large pot, sauté onions in butter until golden brown. - 2. Add vegetable broth, milk, and pepper. Bring to a boil. - 3. Reduce heat and simmer for 10 minutes. - 4. In a small bowl, whisk together flour and Parmesan cheese until smooth. - 5. Add to soup and simmer for an additional 5 minutes, or until soup has thickened. - ``` + ```output + No of recipes (for example, 5: 3 + List of ingredients (for example, chicken, potatoes, and carrots: onion,milk + Filter (for example, vegetarian, vegan, or gluten-free: no milk + + 1. French Onion Soup + + Ingredients: - 보시다시피, 우유가 들어간 레시피는 필터링되었습니다. 그러나 유당 불내증이 있다면 치즈가 들어간 레시피도 필터링하고 싶을 수 있으므로 명확하게 해야합니다. + -1 large onion, sliced + -3 cups beef broth + -1 cup milk + -6 slices french bread + -1/4 cup shredded Parmesan cheese + -1 tablespoon butter + -1 teaspoon dried thyme + -1/4 teaspoon salt + -1/4 teaspoon black pepper + Instructions: + + 1. In a large pot, sauté onions in butter until golden brown. + 2. Add beef broth, milk, thyme, salt, and pepper. Bring to a boil. + 3. Reduce heat and simmer for 10 minutes. + 4. Place french bread slices on soup bowls. + 5. Ladle soup over bread. + 6. Sprinkle with Parmesan cheese. + + 2. Onion and Potato Soup + + Ingredients: + + -1 large onion, chopped + -2 cups potatoes, diced + -3 cups vegetable broth + -1 cup milk + -1/4 teaspoon black pepper + + Instructions: + + 1. In a large pot, sauté onions in butter until golden brown. + 2. Add potatoes, vegetable broth, milk, and pepper. Bring to a boil. + 3. Reduce heat and simmer for 10 minutes. + 4. Serve hot. + + 3. Creamy Onion Soup + + Ingredients: + + -1 large onion, chopped + -3 cups vegetable broth + -1 cup milk + -1/4 teaspoon black pepper + -1/4 cup all-purpose flour + -1/2 cup shredded Parmesan cheese + + Instructions: + + 1. In a large pot, sauté onions in butter until golden brown. + 2. Add vegetable broth, milk, and pepper. Bring to a boil. + 3. Reduce heat and simmer for 10 minutes. + 4. In a small bowl, whisk together flour and Parmesan cheese until smooth. + 5. Add to soup and simmer for an additional 5 minutes, or until soup has thickened. + ``` + + 보시다시피, 우유가 들어간 레시피는 필터링되었습니다. 그러나 유당 불내증이 있다면 치즈가 들어간 레시피도 필터링하고 싶을 수 있으므로 명확하게 해야합니다. - **쇼핑 목록 생성**. 우리는 이미 집에 있는 재료를 고려하여 쇼핑 목록을 생성하고 싶습니다. - 이 기능을 위해 우리는 하나의 프롬프트에서 모든 것을 해결하려고 시도할 수도 있고, 두 개의 프롬프트로 나눠서 해결할 수도 있습니다. 후자의 접근 방식을 시도해 보겠습니다. 여기서는 추가적인 프롬프트를 추가하는 것을 제안하고 있습니다. 그러나 이를 위해 이전 프롬프트의 결과를 후자의 프롬프트에 컨텍스트로 추가해야 합니다. + 이 기능을 위해 우리는 하나의 프롬프트에서 모든 것을 해결하려고 시도할 수도 있고, 두 개의 프롬프트로 나눠서 해결할 수도 있습니다. 후자의 접근 방식을 시도해 보겠습니다. 여기서는 추가적인 프롬프트를 추가하는 것을 제안하고 있습니다. 그러나 이를 위해 이전 프롬프트의 결과를 후자의 프롬프트에 컨텍스트로 추가해야 합니다. - 코드에서 첫 번째 프롬프트의 결과를 출력하는 부분을 찾아서 다음 코드를 아래에 추가하세요: + 코드에서 첫 번째 프롬프트의 결과를 출력하는 부분을 찾아서 다음 코드를 아래에 추가하세요: - ```python - old_prompt_result = completion.choices[0].text - prompt = "Produce a shopping list for the generated recipes and please don't include ingredients that I already have." - - new_prompt = f"{old_prompt_result} {prompt}" - completion = openai.Completion.create(engine=deployment_name, prompt=new_prompt, max_tokens=1200) - - # print response - print("Shopping list:") - print(completion.choices[0].text) - ``` + ```python + old_prompt_result = completion.choices[0].text + prompt = "Produce a shopping list for the generated recipes and please don't include ingredients that I already have." + + new_prompt = f"{old_prompt_result} {prompt}" + completion = openai.Completion.create(engine=deployment_name, prompt=new_prompt, max_tokens=1200) + + # print response + print("Shopping list:") + print(completion.choices[0].text) + ``` - 다음 사항을 주목하세요: + 다음 사항을 주목하세요: - 1. 첫 번째 프롬프트의 결과를 새로운 프롬프트에 추가하여 새로운 프롬프트를 구성합니다: + 1. 첫 번째 프롬프트의 결과를 새로운 프롬프트에 추가하여 새로운 프롬프트를 구성합니다: - ```python - new_prompt = f"{old_prompt_result} {prompt}" - ``` + ```python + new_prompt = f"{old_prompt_result} {prompt}" + ``` - 2. 첫 번째 프롬프트에서 요청한 토큰 수를 고려하여 새로운 요청을 만듭니다. 이번에는 `max_tokens`을 1200으로 설정합니다. + 2. 첫 번째 프롬프트에서 요청한 토큰 수를 고려하여 새로운 요청을 만듭니다. 이번에는 `max_tokens`을 1200으로 설정합니다. - ```python - completion = openai.Completion.create(engine=deployment_name, prompt=new_prompt, max_tokens=1200) - ``` + ```python + completion = openai.Completion.create(engine=deployment_name, prompt=new_prompt, max_tokens=1200) + ``` - Taking this code for a spin, we now arrive at the following output: + Taking this code for a spin, we now arrive at the following output: - ```output - No of recipes (for example, 5: 2 - List of ingredients (for example, chicken, potatoes, and carrots: apple,flour - Filter (for example, vegetarian, vegan, or gluten-free: sugar + ```output + No of recipes (for example, 5: 2 + List of ingredients (for example, chicken, potatoes, and carrots: apple,flour + Filter (for example, vegetarian, vegan, or gluten-free: sugar - - -Apple and flour pancakes: 1 cup flour, 1/2 tsp baking powder, 1/2 tsp baking soda, 1/4 tsp salt, 1 tbsp sugar, 1 egg, 1 cup buttermilk or sour milk, 1/4 cup melted butter, 1 Granny Smith apple, peeled and grated - -Apple fritters: 1-1/2 cups flour, 1 tsp baking powder, 1/4 tsp salt, 1/4 tsp baking soda, 1/4 tsp nutmeg, 1/4 tsp cinnamon, 1/4 tsp allspice, 1/4 cup sugar, 1/4 cup vegetable shortening, 1/4 cup milk, 1 egg, 2 cups shredded, peeled apples - Shopping list: - -Flour, baking powder, baking soda, salt, sugar, egg, buttermilk, butter, apple, nutmeg, cinnamon, allspice - ``` + + -Apple and flour pancakes: 1 cup flour, 1/2 tsp baking powder, 1/2 tsp baking soda, 1/4 tsp salt, 1 tbsp sugar, 1 egg, 1 cup buttermilk or sour milk, 1/4 cup melted butter, 1 Granny Smith apple, peeled and grated + -Apple fritters: 1-1/2 cups flour, 1 tsp baking powder, 1/4 tsp salt, 1/4 tsp baking soda, 1/4 tsp nutmeg, 1/4 tsp cinnamon, 1/4 tsp allspice, 1/4 cup sugar, 1/4 cup vegetable shortening, 1/4 cup milk, 1 egg, 2 cups shredded, peeled apples + Shopping list: + -Flour, baking powder, baking soda, salt, sugar, egg, buttermilk, butter, apple, nutmeg, cinnamon, allspice + ``` ## 설정 개선하기 @@ -556,45 +554,45 @@ Shopping List: - **비밀 정보와 코드 분리하기**, 예를 들어 API 키와 같은 비밀 정보는 코드에 포함되어서는 안 됩니다. 비밀 정보를 코드와 분리하기 위해 환경 변수와 `python-dotenv`와 같은 라이브러리를 사용하여 파일에서 로드할 수 있습니다. 코드에서 이렇게 구현할 수 있습니다: - 1. `.env` 파일을 다음 내용으로 생성하세요: + 1. `.env` 파일을 다음 내용으로 생성하세요: - ```bash - OPENAI_API_KEY=sk-... - ``` + ```bash + OPENAI_API_KEY=sk-... + ``` - > 참고로, Azure의 경우 다음 환경 변수를 설정해야 합니다: + > 참고로, Azure의 경우 다음 환경 변수를 설정해야 합니다: - ```bash - OPENAI_API_TYPE=azure - OPENAI_API_VERSION=2023-05-15 - OPENAI_API_BASE= - ``` + ```bash + OPENAI_API_TYPE=azure + OPENAI_API_VERSION=2023-05-15 + OPENAI_API_BASE= + ``` - 코드에서는 다음과 같이 환경 변수를 로드합니다: + 코드에서는 다음과 같이 환경 변수를 로드합니다: - ```python - from dotenv import load_dotenv + ```python + from dotenv import load_dotenv - load_dotenv() + load_dotenv() - openai.api_key = os.environ["OPENAI_API_KEY"] - ``` + openai.api_key = os.environ["OPENAI_API_KEY"] + ``` - **토큰 길이에 대한 고려사항**. 우리는 원하는 텍스트를 생성하기 위해 얼마나 많은 토큰이 필요한지 고려해야 합니다. 토큰은 비용이 들기 때문에 가능한 경우, 토큰의 수를 절약할 수 있는 방법을 고려해야 합니다. 예를 들어, 프롬프트를 어떻게 구성하면 더 적은 토큰을 사용할 수 있을까요? - 사용할 토큰을 변경하려면 `max_tokens` 매개변수를 사용할 수 있습니다. 예를 들어, 100개의 토큰을 사용하려면 다음과 같이 할 수 있습니다: + 사용할 토큰을 변경하려면 `max_tokens` 매개변수를 사용할 수 있습니다. 예를 들어, 100개의 토큰을 사용하려면 다음과 같이 할 수 있습니다: - ```python - completion = openai.Completion.create(model="davinci-002", prompt=prompt, max_tokens=100) - ``` + ```python + completion = openai.Completion.create(model="davinci-002", prompt=prompt, max_tokens=100) + ``` - **temperature 조절 실험**. temperature는 우리가 지금까지 언급하지 않았지만, 프로그램의 동작에 중요한 맥락입니다. temperature 값이 높을수록 출력이 더 무작위적이 됩니다. 반대로, temperature 값이 낮을수록 출력이 더 예측 가능해집니다. 출력에 변화를 원하는지 여부를 고려해보세요. - temperature를 변경하려면 `temperature` 매개변수를 사용할 수 있습니다. 예를 들어, temperature를 0.5로 설정하려면 다음과 같이 할 수 있습니다: + temperature를 변경하려면 `temperature` 매개변수를 사용할 수 있습니다. 예를 들어, temperature를 0.5로 설정하려면 다음과 같이 할 수 있습니다: - ```python - completion = openai.Completion.create(model="davinci-002", prompt=prompt, temperature=0.5) - ``` + ```python + completion = openai.Completion.create(model="davinci-002", prompt=prompt, temperature=0.5) + ``` > 참고로, 값이 1.0에 가까울수록 출력이 더 다양해집니다. @@ -644,7 +642,6 @@ temperature 개념은 무엇을 하는 역할인가요? 2. 응답의 크기를 조절합니다. 3. 사용되는 토큰의 수를 조절합니다. - ## 🚀 도전과제 과제를 수행할 때, temperature 값을 다양하게 변경해보세요. 0, 0.5, 1로 설정해보세요. 기억해주세요, 0은 가장 일정하고 1은 가장 다양한 값을 의미합니다. 어떤 값이 앱에 가장 적합한지 확인해보세요. diff --git a/06-text-generation-apps/translations/pt-br/README.md b/06-text-generation-apps/translations/pt-br/README.md index ece71c8bc..65cb9cfd1 100644 --- a/06-text-generation-apps/translations/pt-br/README.md +++ b/06-text-generation-apps/translations/pt-br/README.md @@ -1,6 +1,6 @@ # Desenvolvendo Aplicativos de Geração de Texto -[![Building Text Generation Applications](../../images/06-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=bf3f3528-9871-4628-8616-b4b03cb23dcd?WT.mc_id=academic-105485-koreyst) +[![Building Text Generation Applications](../../images/06-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson6-gh) > _(Clique na imagem acima para assistir ao vídeo desta lição)_ diff --git a/07-building-chat-applications/README.md b/07-building-chat-applications/README.md index 42035d681..80348cf76 100644 --- a/07-building-chat-applications/README.md +++ b/07-building-chat-applications/README.md @@ -1,6 +1,6 @@ # Building Generative AI-Powered Chat Applications -[![Building Generative AI-Powered Chat Applications](./images/07-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=57a31949-67c5-4020-8c85-91e4995589f3?WT.mc_id=academic-105485-koreyst) +[![Building Generative AI-Powered Chat Applications](./images/07-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lessons7-gh) > _(Click the image above to view video of this lesson)_ diff --git a/07-building-chat-applications/images/07-lesson-banner.png b/07-building-chat-applications/images/07-lesson-banner.png index c8d26a915..993660da5 100644 Binary files a/07-building-chat-applications/images/07-lesson-banner.png and b/07-building-chat-applications/images/07-lesson-banner.png differ diff --git a/07-building-chat-applications/translations/cn/README.md b/07-building-chat-applications/translations/cn/README.md index a82170cdd..dfd097693 100644 --- a/07-building-chat-applications/translations/cn/README.md +++ b/07-building-chat-applications/translations/cn/README.md @@ -1,6 +1,6 @@ # 第七章:创建聊天应用 -[![Building Generative AI-Powered Chat Applications](../../images/07-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=57a31949-67c5-4020-8c85-91e4995589f3?WT.mc_id=academic-105485-koreyst) +[![Building Generative AI-Powered Chat Applications](../../images/07-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lessons7-gh) > _(点击该图片看本章导学视频)_ diff --git a/07-building-chat-applications/translations/ja-jp/README.md b/07-building-chat-applications/translations/ja-jp/README.md index 3837d5c1e..e2c4e140f 100644 --- a/07-building-chat-applications/translations/ja-jp/README.md +++ b/07-building-chat-applications/translations/ja-jp/README.md @@ -1,6 +1,6 @@ # 生成 AI を利用したチャット・アプリケーションの構築 -[![Building Generative AI-Powered Chat Applications](../..//images/07-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=57a31949-67c5-4020-8c85-91e4995589f3?WT.mc_id=academic-105485-yoterada) +[![Building Generative AI-Powered Chat Applications](../..//images/07-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://aka.ms/gen-ai-lessons7-gh) > _(上記の画像をクリックすると、レッスン・ビデオを表示します)_ diff --git a/07-building-chat-applications/translations/ko/README.md b/07-building-chat-applications/translations/ko/README.md index eb32010fa..d31d30416 100644 --- a/07-building-chat-applications/translations/ko/README.md +++ b/07-building-chat-applications/translations/ko/README.md @@ -1,8 +1,8 @@ # 생성형 AI를 활용한 채팅 애플리케이션 구축 -[![Generative AI를 활용한 채팅 애플리케이션 구축](../../images/07-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://youtu.be/Kw4i-tlKMrQ?WT.mc_id=academic-105485-koreyst) +[![Generative AI를 활용한 채팅 애플리케이션 구축](../../images/07-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lessons7-gh) -> *(위의 이미지를 클릭하여 이 레슨의 비디오를 시청하세요)* +> _(위의 이미지를 클릭하여 이 레슨의 비디오를 시청하세요)_ 텍스트 생성 앱을 구축하는 방법을 살펴보았으니 이제 채팅 애플리케이션에 대해 알아보겠습니다. @@ -44,12 +44,12 @@ 아래 표는 디지털 커뮤니케이션에서 각각의 역할을 이해하기 위해 주요 차이점과 유사점을 개요로 제시합니다. -| 챗봇 | 생성형 AI 기반 채팅 애플리케이션 | -| ------------------------------------- | -------------------------------------- | -| 작업 중심 및 규칙 기반 | 문맥 인식 | -| 주로 대규모 시스템에 통합됨 | 하나 또는 여러 챗봇을 호스팅할 수 있음 | -| 사전에 프로그래밍된 기능으로 제한됨 | 생성형 AI 모델 통합 | -| 전문화되고 구조화된 상호작용 | 열린 도메인으로 토론 가능 | +| 챗봇 | 생성형 AI 기반 채팅 애플리케이션 | +| ----------------------------------- | -------------------------------------- | +| 작업 중심 및 규칙 기반 | 문맥 인식 | +| 주로 대규모 시스템에 통합됨 | 하나 또는 여러 챗봇을 호스팅할 수 있음 | +| 사전에 프로그래밍된 기능으로 제한됨 | 생성형 AI 모델 통합 | +| 전문화되고 구조화된 상호작용 | 열린 도메인으로 토론 가능 | ### SDK 및 API를 활용한 사전 구축된 기능 활용 @@ -147,31 +147,31 @@ AuthenticationError: No API key provided. You can set your API key in code using 애플리케이션의 고품질 성능을 유지하기 위해 주요 지표와 고려 사항을 추적하는 것이 중요합니다. 이러한 측정은 애플리케이션의 기능뿐만 아니라 AI 모델의 품질과 사용자 경험을 평가하는 데 도움이 됩니다. 아래는 고려해야 할 기본, AI 및 사용자 경험 지표를 다루는 목록입니다. -| 지표 | 정의 | 채팅 개발자를 위한 고려 사항 | -| ----------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | -| **가동 시간 (Uptime)** | 애플리케이션이 사용자에게 작동 가능하고 접근 가능한 시간을 측정합니다. | 다운타임을 최소화하기 위해 어떻게 할 것인가요? | -| **응답 시간 (Response Time)** | 애플리케이션이 사용자의 쿼리에 응답하는 데 걸리는 시간을 측정합니다. | 응답 시간을 개선하기 위해 쿼리 처리를 어떻게 최적화할 수 있을까요? | -| **정확도 (Precision)** | 전체 양성 예측 중 실제 양성 예측의 비율 | 모델의 정확도를 어떻게 검증할 것인가요? | -| **재현율 (Recall), 민감도 (Sensitivity)** | 실제 양성 중 양성 예측의 비율 | 재현율 (recall)을 어떻게 측정하고 개선할 것인가요? | -| **F1 점수** | 정밀도 (precision)와 재현율 (recall)의 조화 평균으로, 두 가지 사이의 균형을 맞춥니다. | 목표 F1 점수는 무엇이며, 정밀도와 재현율을 어떻게 균형있게 유지할 것인가요? | -| **Perplexity** | 모델이 예측한 확률 분포가 실제 데이터의 분포와 얼마나 일치하는지 측정합니다. | Perplexity를 최소화하기 위해 어떻게 할 것인가요? | -| **사용자 만족도 지표** | 사용자가 애플리케이션에 대한 인식을 측정합니다. 주로 설문 조사를 통해 수집됩니다. | 얼마나 자주 사용자 피드백을 수집할 것인가요? 이를 기반으로 어떻게 적응할 것인가요? | -| **오류율 (Error Rate)** | 모델이 이해하거나 출력하는 데 발생하는 오류의 비율 | 오류율을 줄이기 위한 전략은 무엇인가요? | -| **재학습 주기** | 새로운 데이터와 통찰력을 반영하기 위해 모델을 업데이트하는 빈도 | 모델을 얼마나 자주 재학습할 것인가요? 재학습 주기를 트리거하는 요소는 무엇인가요? | -| **이상 탐지** | 예상되는 동작과 일치하지 않는 비정상적인 패턴을 식별하기 위한 도구와 기법 | 이상 탐지에 어떻게 대응할 것인가요? | +| 지표 | 정의 | 채팅 개발자를 위한 고려 사항 | +| ----------------------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| **가동 시간 (Uptime)** | 애플리케이션이 사용자에게 작동 가능하고 접근 가능한 시간을 측정합니다. | 다운타임을 최소화하기 위해 어떻게 할 것인가요? | +| **응답 시간 (Response Time)** | 애플리케이션이 사용자의 쿼리에 응답하는 데 걸리는 시간을 측정합니다. | 응답 시간을 개선하기 위해 쿼리 처리를 어떻게 최적화할 수 있을까요? | +| **정확도 (Precision)** | 전체 양성 예측 중 실제 양성 예측의 비율 | 모델의 정확도를 어떻게 검증할 것인가요? | +| **재현율 (Recall), 민감도 (Sensitivity)** | 실제 양성 중 양성 예측의 비율 | 재현율 (recall)을 어떻게 측정하고 개선할 것인가요? | +| **F1 점수** | 정밀도 (precision)와 재현율 (recall)의 조화 평균으로, 두 가지 사이의 균형을 맞춥니다. | 목표 F1 점수는 무엇이며, 정밀도와 재현율을 어떻게 균형있게 유지할 것인가요? | +| **Perplexity** | 모델이 예측한 확률 분포가 실제 데이터의 분포와 얼마나 일치하는지 측정합니다. | Perplexity를 최소화하기 위해 어떻게 할 것인가요? | +| **사용자 만족도 지표** | 사용자가 애플리케이션에 대한 인식을 측정합니다. 주로 설문 조사를 통해 수집됩니다. | 얼마나 자주 사용자 피드백을 수집할 것인가요? 이를 기반으로 어떻게 적응할 것인가요? | +| **오류율 (Error Rate)** | 모델이 이해하거나 출력하는 데 발생하는 오류의 비율 | 오류율을 줄이기 위한 전략은 무엇인가요? | +| **재학습 주기** | 새로운 데이터와 통찰력을 반영하기 위해 모델을 업데이트하는 빈도 | 모델을 얼마나 자주 재학습할 것인가요? 재학습 주기를 트리거하는 요소는 무엇인가요? | +| **이상 탐지** | 예상되는 동작과 일치하지 않는 비정상적인 패턴을 식별하기 위한 도구와 기법 | 이상 탐지에 어떻게 대응할 것인가요? | ### 채팅 애플리케이션에서 책임 있는 AI 실천 방법 구현 Microsoft의 책임 있는 AI 접근 방식은 AI 개발과 사용을 안내하는 여섯 가지 원칙을 도출했습니다. 아래는 원칙, 정의 및 채팅 개발자가 고려해야 할 사항과 그 중요성입니다. -| 원칙 | Microsoft의 정의 | 채팅 개발자를 위한 고려 사항 | 중요성 | -| ---------------------- | ----------------------------------------------------- | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | -| 공정성 | AI 시스템은 모든 사람을 공정하게 대우해야 합니다. | 채팅 애플리케이션이 사용자 데이터를 기반으로 차별하지 않도록 보장합니다. | 사용자들 사이에서 신뢰와 포용성을 구축하며, 법적인 문제를 피할 수 있습니다. | -| 신뢰성과 안전성 | AI 시스템은 신뢰성 있고 안전하게 작동해야 합니다. | 테스트와 오류 방지를 구현하여 오류와 위험을 최소화합니다. | 사용자 만족도를 보장하고 잠재적인 피해를 방지합니다. | -| 개인 정보 보호와 보안 | AI 시스템은 안전하고 개인 정보를 존중해야 합니다. | 강력한 암호화와 데이터 보호 조치를 구현합니다. | 민감한 사용자 데이터를 보호하고 개인 정보 보호 법을 준수합니다. | -| 포용성 | AI 시스템은 모든 사람을 적극적으로 참여시켜야 합니다. | 다양한 대중을 위해 접근 가능하고 사용하기 쉬운 UI/UX를 디자인합니다. | 더 넓은 범위의 사람들이 효과적으로 애플리케이션을 사용할 수 있도록 보장합니다. | -| 투명성 | AI 시스템은 이해하기 쉬워야 합니다. | AI 응답에 대한 명확한 문서와 이유를 제공합니다. | 사용자는 결정 방식을 이해할 수 있을 때 시스템을 더 신뢰할 가능성이 높습니다. | -| 책임성 | 사람들은 AI 시스템에 대해 책임져야 합니다. | 감사 및 개선을 위한 명확한 프로세스를 수립합니다. | 실수가 발생한 경우 지속적인 개선과 수정 조치를 가능하게 합니다. | +| 원칙 | Microsoft의 정의 | 채팅 개발자를 위한 고려 사항 | 중요성 | +| --------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| 공정성 | AI 시스템은 모든 사람을 공정하게 대우해야 합니다. | 채팅 애플리케이션이 사용자 데이터를 기반으로 차별하지 않도록 보장합니다. | 사용자들 사이에서 신뢰와 포용성을 구축하며, 법적인 문제를 피할 수 있습니다. | +| 신뢰성과 안전성 | AI 시스템은 신뢰성 있고 안전하게 작동해야 합니다. | 테스트와 오류 방지를 구현하여 오류와 위험을 최소화합니다. | 사용자 만족도를 보장하고 잠재적인 피해를 방지합니다. | +| 개인 정보 보호와 보안 | AI 시스템은 안전하고 개인 정보를 존중해야 합니다. | 강력한 암호화와 데이터 보호 조치를 구현합니다. | 민감한 사용자 데이터를 보호하고 개인 정보 보호 법을 준수합니다. | +| 포용성 | AI 시스템은 모든 사람을 적극적으로 참여시켜야 합니다. | 다양한 대중을 위해 접근 가능하고 사용하기 쉬운 UI/UX를 디자인합니다. | 더 넓은 범위의 사람들이 효과적으로 애플리케이션을 사용할 수 있도록 보장합니다. | +| 투명성 | AI 시스템은 이해하기 쉬워야 합니다. | AI 응답에 대한 명확한 문서와 이유를 제공합니다. | 사용자는 결정 방식을 이해할 수 있을 때 시스템을 더 신뢰할 가능성이 높습니다. | +| 책임성 | 사람들은 AI 시스템에 대해 책임져야 합니다. | 감사 및 개선을 위한 명확한 프로세스를 수립합니다. | 실수가 발생한 경우 지속적인 개선과 수정 조치를 가능하게 합니다. | ## 과제 diff --git a/07-building-chat-applications/translations/pt-br/README.md b/07-building-chat-applications/translations/pt-br/README.md index 98e7eafbe..72e444567 100644 --- a/07-building-chat-applications/translations/pt-br/README.md +++ b/07-building-chat-applications/translations/pt-br/README.md @@ -2,7 +2,7 @@ ## Criando Aplicações Chat com IA Generativa -[![Building Generative AI-Powered Chat Applications](../../images/07-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=57a31949-67c5-4020-8c85-91e4995589f3?WT.mc_id=academic-105485-koreyst) +[![Building Generative AI-Powered Chat Applications](../../images/07-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lessons7-gh) > _(Clique na imagem acima para ver o vídeo da lição)_ @@ -171,7 +171,7 @@ Para manter o desempenho de alta qualidade de uma aplicação, é essencial acom | **Taxa de Erro** | A taxa na qual o modelo comete erros na compreensão ou saída. | Quais estratégias você tem para reduzir as taxas de erro? | | **Ciclos de Retreinamento** | A frequência com que o modelo é atualizado para incorporar novos dados e insights. | Com que frequência você irá retrainer o modelo? O que desencadeia um ciclo de retratamento? | | **Detecção de Anomalias** | Ferramentas e técnicas para identificar padrões incomuns que não seguem o comportamento esperado. | Como você irá responder a anomalias? | -| | +| | ### Implementando Práticas de IA Responsável em Aplicações de Chat diff --git a/08-building-search-applications/README.md b/08-building-search-applications/README.md index 8a796b472..ef7e0700d 100644 --- a/08-building-search-applications/README.md +++ b/08-building-search-applications/README.md @@ -1,8 +1,8 @@ -# Building a Search Applications +# Building a Search Applications -[![Introduction to Generative AI and Large Language Models](./images/08-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](TBD) +[![Introduction to Generative AI and Large Language Models](./images/08-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson8-gh) -> **Video Coming Soon** +> > _Click the image above to view video of this lesson_ There's more to LLMs than chatbots and text generation. It's also possible to build search applications using Embeddings. Embeddings are numerical representations of data also known as vectors, and can be used for semantic search for data. @@ -45,7 +45,7 @@ Here is an example of a semantic search. Let's say you were looking to buy a car ## What are Text Embeddings? -[Text embeddings](https://en.wikipedia.org/wiki/Word_embedding?WT.mc_id=academic-105485-koreyst) are a text representation technique used in [natural language processing](https://en.wikipedia.org/wiki/Natural_language_processing?WT.mc_id=academic-105485-koreyst). Text embeddings are semantic numerical representations of text. Embeddings are used to represent data in a way that is easy for a machine to understand. There are many models for building text embeddings, in this lesson, we will focus on generating embeddings using the OpenAI Embedding Model. +[Text embeddings](https://en.wikipedia.org/wiki/Word_embedding?WT.mc_id=academic-105485-koreyst) are a text representation technique used in [natural language processing](https://en.wikipedia.org/wiki/Natural_language_processing?WT.mc_id=academic-105485-koreyst). Text embeddings are semantic numerical representations of text. Embeddings are used to represent data in a way that is easy for a machine to understand. There are many models for building text embeddings, in this lesson, we will focus on generating embeddings using the OpenAI Embedding Model. Here's an example, imagine the following text is in a transcript from one of the episodes on the AI Show YouTube channel: @@ -156,7 +156,7 @@ When you run the notebook, you'll be prompted to enter a query. The input box wi ![Input box for the user to input a query](./images/notebook-search.png?WT.mc_id=academic-105485-koreyst) -## Great Work! Continue Your Learning +## Great Work! Continue Your Learning After completing this lesson, check out our [Generative AI Learning collection](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) to continue leveling up your Generative AI knowledge! diff --git a/08-building-search-applications/images/08-lesson-banner.png b/08-building-search-applications/images/08-lesson-banner.png index 862e36920..ac2868e43 100644 Binary files a/08-building-search-applications/images/08-lesson-banner.png and b/08-building-search-applications/images/08-lesson-banner.png differ diff --git a/08-building-search-applications/translations/cn/README.md b/08-building-search-applications/translations/cn/README.md index 065068167..241369b28 100644 --- a/08-building-search-applications/translations/cn/README.md +++ b/08-building-search-applications/translations/cn/README.md @@ -1,8 +1,6 @@ # 第八章:创建搜索应用 -[![Introduction to Generative AI and Large Language Models](../../images/08-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](TBD) - -> **导学视频敬请期待** +[![Introduction to Generative AI and Large Language Models](../../images/08-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson8-gh) LLMs 应用场景不仅仅是聊天机器人和文本生成。 还可以使用嵌入的方式来构建搜索应用程序。 嵌入是数据的数字表示,也称为向量,可用于数据的语义搜索。 diff --git a/08-building-search-applications/translations/ja-jp/README.md b/08-building-search-applications/translations/ja-jp/README.md index 5be899c9c..a917646b0 100644 --- a/08-building-search-applications/translations/ja-jp/README.md +++ b/08-building-search-applications/translations/ja-jp/README.md @@ -1,8 +1,6 @@ # 検索アプリケーションの構築 -[![Introduction to Generative AI and Large Language Models](../../images/08-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](TBD) - -> **ビデオは近日公開予定** +[![Introduction to Generative AI and Large Language Models](../../images/08-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://aka.ms/gen-ai-lesson8-gh) LLM は、チャットボットやテキスト生成だけでなく、Embeddings を使った検索アプリケーションの実装も可能です。Embeddings とは、ベクトルと呼ばれるデータの数値表現で、データのセマンティック検索に活用できます。 @@ -57,11 +55,11 @@ LLM は、チャットボットやテキスト生成だけでなく、Embeddings ```text [ --0.006655829958617687, 0.0026128944009542465, -0.008792596869170666, -0.02446001023054123, --0.008540431968867779, 0.022071078419685364, +-0.006655829958617687, 0.0026128944009542465, +0.008792596869170666, -0.02446001023054123, +-0.008540431968867779, 0.022071078419685364, -0.010703742504119873, 0.003311325330287218,  --0.011632772162556648, -0.02187200076878071, +-0.011632772162556648, -0.02187200076878071, ... ] ``` @@ -74,7 +72,7 @@ LLM は、チャットボットやテキスト生成だけでなく、Embeddings 1. [AI Show](https://www.youtube.com/playlist?list=PLlrxD0HtieHi0mwteKBOfEeOYf0LJU4O1?WT.mc_id=academic-105485-yoterada) プレイリスト中の各 YouTube 動画の字幕をダウンロードします。 2. [OpenAI の Function Calling](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling?WT.mc_id=academic-105485-yoterada) を使用して、YouTube 字幕の最初から 3 分で発表者の名前を抽出します。各動画の発表者の名前は、`embedding_index_3m.json` という名前の埋め込みインデックスに保存します。 -3. その後、字幕テキストは「**3分間のテキストブロック**」に分割します。各ブロックには、次のブロックから約20語を重複して含め、各ブロックの埋め込みが途切れないように、より良い検索コンテキストを提供します。 +3. その後、字幕テキストは「**3 分間のテキストブロック**」に分割します。各ブロックには、次のブロックから約 20 語を重複して含め、各ブロックの埋め込みが途切れないように、より良い検索コンテキストを提供します。 4. 各テキストブロックを OpenAI の Chat API に渡し、テキストを 60 語に要約します。この要約結果も `embedding_index_3m.json` という埋め込みインデックスに保存します。 5. 最後に、テキストブロックの内容を OpenAI の埋め込み API に渡します。埋め込み API は、ブロックの意味を表現する 1536 個の数値からなるベクトルを返します。テキストブロックと OpenAI の埋め込みベクトルは、`embedding_index_3m.json` という埋め込みインデックスに保存します。 @@ -88,7 +86,7 @@ LLM は、チャットボットやテキスト生成だけでなく、Embeddings ### コサイン類似度とは何でしょうか? -コサイン類似度は、2つのベクトル間の類似性を測る指標で、これは「最近傍検索」とも呼ばれます。コサイン類似度検索を行うためには、まず OpenAI の埋め込み API を使って、ユーザから問い合わせされたテキストをベクトル化します。次に、問い合わせされたベクトルと、埋め込みインデックス内の各ベクトルとのコサイン類似度を計算します。埋め込みインデックスには、YouTube の字幕テキストブロックごとにベクトルが存在します。最後に、結果をコサイン類似度でソートします。コサイン類似度が最も高いテキストブロックが、問い合わせされた内容に最も近い内容を表しています。 +コサイン類似度は、2 つのベクトル間の類似性を測る指標で、これは「最近傍検索」とも呼ばれます。コサイン類似度検索を行うためには、まず OpenAI の埋め込み API を使って、ユーザから問い合わせされたテキストをベクトル化します。次に、問い合わせされたベクトルと、埋め込みインデックス内の各ベクトルとのコサイン類似度を計算します。埋め込みインデックスには、YouTube の字幕テキストブロックごとにベクトルが存在します。最後に、結果をコサイン類似度でソートします。コサイン類似度が最も高いテキストブロックが、問い合わせされた内容に最も近い内容を表しています。 数学的な観点から見ると、コサイン類似度は多次元空間に投影された 2 つのベクトル間の角度のコサインを測定します。この測定は有益で、2 つのドキュメントが大きさのためにユークリッド距離で離れていても、それらの間の角度が小さいため、コサイン類似度が高くなる可能性があります。コサイン類似度の方程式についての詳細は、[コサイン類似度](https://en.wikipedia.org/wiki/Cosine_similarity?WT.mc_id=academic-105485-yoterada)をご覧ください。 @@ -109,7 +107,7 @@ LLM は、チャットボットやテキスト生成だけでなく、Embeddings この課題では、検索アプリケーションを作るために Azure OpenAI Services を利用します。下記のように Azure OpenAI Services を作成します。この課題を完了するためには、Azure サブスクリプションが事前に必要です。 -### Azure Cloud Shell の起動 +### Azure Cloud Shell  の起動 1. [Azure portal](https://portal.azure.com/?WT.mc_id=academic-105485-yoterada) にサインインします 2. Azure portal の右上隅にある Cloud Shell アイコンを選択します @@ -129,7 +127,7 @@ LLM は、チャットボットやテキスト生成だけでなく、Embeddings az group create --name semantic-video-search --location eastus ``` -#### Azure OpenAI Serviceリソースを作成する +#### Azure OpenAI Service リソースを作成する Azure Cloud Shell から、下記のコマンドを実行して Azure OpenAI Service リソースを作成します。 diff --git a/08-building-search-applications/translations/ko/README.md b/08-building-search-applications/translations/ko/README.md index 7001b99dc..5fbfaafd8 100644 --- a/08-building-search-applications/translations/ko/README.md +++ b/08-building-search-applications/translations/ko/README.md @@ -1,8 +1,6 @@ # 검색 애플리케이션 만들기 -[![Introduction to Generative AI and Large Language Models](../../images/08-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](TBD) - -> **비디오 제공 예정** +[![Introduction to Generative AI and Large Language Models](../../images/08-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson8-gh) LLM(대형 언어 모델)은 챗봇과 텍스트 생성 이상의 기능을 가지고 있습니다. Embedding을 사용하여 검색 애플리케이션을 만들 수도 있습니다. Embedding은 데이터의 수치적 표현인 벡터로, 데이터의 의미 기반 검색에 사용할 수 있습니다. diff --git a/08-building-search-applications/translations/pt-br/README.md b/08-building-search-applications/translations/pt-br/README.md index 77279b34d..c2995bd7d 100644 --- a/08-building-search-applications/translations/pt-br/README.md +++ b/08-building-search-applications/translations/pt-br/README.md @@ -1,8 +1,6 @@ # Criando Aplicações de Busca -[![Introduction to Generative AI and Large Language Models](../../images/08-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](TBD) - -> **Vídeo em breve** +[![Introduction to Generative AI and Large Language Models](../../images/08-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson8-gh) Há muito mais nas LLMs do que chatbots e geração de texto. Também é possível criar aplicações de busca usando `Embeddings`. `Embeddings` são representações numéricas de dados, também conhecidas como vetores, e podem ser usados para busca semântica de dados. diff --git a/09-building-image-applications/README.md b/09-building-image-applications/README.md index 869115882..d87c23e51 100644 --- a/09-building-image-applications/README.md +++ b/09-building-image-applications/README.md @@ -1,8 +1,6 @@ # Building Image Generation Applications -[![Building Image Generation Applications](./images/09-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](TBD) - -> **Video Coming Soon** +[![Building Image Generation Applications](./images/09-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson9-gh) There's more to LLMs than text generation. It's also possible to generate images from text descriptions. Having images as a modality can be highly useful in a number of areas from MedTech, architecture, tourism, game development and more. In this chapter, we will look into the two most popular image generation models, DALL-E and Midjourney. @@ -24,9 +22,9 @@ After completing this lesson, you will be able to: ## Why build an image generation application? -Image generation applications are a great way to explore the capabilities of Generative AI. They can be used for, for example: +Image generation applications are a great way to explore the capabilities of Generative AI. They can be used for, for example: -- **Image editing and synthesis**. You can generate images for a variety of use cases, such as image editing and image synthesis. +- **Image editing and synthesis**. You can generate images for a variety of use cases, such as image editing and image synthesis. - **Applied to a variety of industries**. They can also be used to generate images for a variety of industries like Medtech, Tourism, Game development and more. @@ -50,9 +48,9 @@ using a prompt like Let's start with DALL-E, which is a Generative AI model that generates images from text descriptions. -> [DALL-E is a combination of two models, CLIP and diffused attention](https://towardsdatascience.com/openais-dall-e-and-clip-101-a-brief-introduction-3a4367280d4e?WT.mc_id=academic-105485-koreyst). +> [DALL-E is a combination of two models, CLIP and diffused attention](https://towardsdatascience.com/openais-dall-e-and-clip-101-a-brief-introduction-3a4367280d4e?WT.mc_id=academic-105485-koreyst). -- **CLIP**, is a model that generates embeddings, which are numerical representations of data, from images and text. +- **CLIP**, is a model that generates embeddings, which are numerical representations of data, from images and text. - **Diffused attention**, is a model that generates images from embeddings. DALL-E is trained on a dataset of images and text and can be used to generate images from text descriptions. For example, DALL-E can be used to generate images of a cat in a hat, or a dog with a mohawk. @@ -61,13 +59,13 @@ Let's start with DALL-E, which is a Generative AI model that generates images fr Midjourney works in a similar way to DALL-E, it generates images from text prompts. Midjourney, can also be used to generate images using prompts like “a cat in a hat”, or a “dog with a mohawk”. ![Image generated by Midjourney, mechanical pigeon](https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Rupert_Breheny_mechanical_dove_eca144e7-476d-4976-821d-a49c408e4f36.png/440px-Rupert_Breheny_mechanical_dove_eca144e7-476d-4976-821d-a49c408e4f36.png?WT.mc_id=academic-105485-koreyst) -*Image cred Wikipedia, image generated by Midjourney* +_Image cred Wikipedia, image generated by Midjourney_ ## How does DALL-E and Midjourney Work -First, [DALL-E](https://arxiv.org/pdf/2102.12092.pdf?WT.mc_id=academic-105485-koreyst). DALL-E is a Generative AI model based on the transformer architecture with an *autoregressive transformer*. +First, [DALL-E](https://arxiv.org/pdf/2102.12092.pdf?WT.mc_id=academic-105485-koreyst). DALL-E is a Generative AI model based on the transformer architecture with an _autoregressive transformer_. -An *autoregressive transformer* defines how a model generates images from text descriptions, it generates one pixel at a time, and then uses the generated pixels to generate the next pixel. Passing through multiple layers in a neural network, until the image is complete. +An _autoregressive transformer_ defines how a model generates images from text descriptions, it generates one pixel at a time, and then uses the generated pixels to generate the next pixel. Passing through multiple layers in a neural network, until the image is complete. With this process, DALL-E, controls attributes, objects, characteristics, and more in the image it generates. However, DALL-E 2 and 3 have more control over the generated image. @@ -75,150 +73,150 @@ With this process, DALL-E, controls attributes, objects, characteristics, and mo So what does it take to build an image generation application? You need the following libraries: -- **python-dotenv**, you're highly recommended to use this library to keep your secrets in a *.env* file away from the code. +- **python-dotenv**, you're highly recommended to use this library to keep your secrets in a _.env_ file away from the code. - **openai**, this library is what you will use to interact with the OpenAI API. - **pillow**, to work with images in Python. - **requests**, to help you make HTTP requests. -1. Create a file *.env* with the following content: +1. Create a file _.env_ with the following content: - ```text - AZURE_OPENAI_ENDPOINT= - AZURE_OPENAI_KEY= - ``` + ```text + AZURE_OPENAI_ENDPOINT= + AZURE_OPENAI_KEY= + ``` - Locate this information in Azure Portal for your resource in the "Keys and Endpoint" section. + Locate this information in Azure Portal for your resource in the "Keys and Endpoint" section. -1. Collect the above libraries in a file called *requirements.txt* like so: +1. Collect the above libraries in a file called _requirements.txt_ like so: - ```text - python-dotenv - openai - pillow - requests - ``` + ```text + python-dotenv + openai + pillow + requests + ``` 1. Next, create virtual environment and install the libraries: - ```bash - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt - ``` - - For Windows, use the following commands to create and activate your virtual environment: - - ```bash - python3 -m venv venv - venv\Scripts\activate.bat - ```` - -1. Add the following code in file called *app.py*: - - ```python - import openai - import os - import requests - from PIL import Image - import dotenv - - # import dotenv - dotenv.load_dotenv() - - # Get endpoint and key from environment variables - openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] - openai.api_key = os.environ['AZURE_OPENAI_KEY'] - - # Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only) - openai.api_version = '2023-06-01-preview' - openai.api_type = 'azure' - - - try: - # Create an image by using the image generation API - generation_response = openai.Image.create( - prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here - size='1024x1024', - n=2, - temperature=0, - ) - # Set the directory for the stored image - image_dir = os.path.join(os.curdir, 'images') - - # If the directory doesn't exist, create it - if not os.path.isdir(image_dir): - os.mkdir(image_dir) - - # Initialize the image path (note the filetype should be png) - image_path = os.path.join(image_dir, 'generated-image.png') - - # Retrieve the generated image - image_url = generation_response["data"][0]["url"] # extract image URL from response - generated_image = requests.get(image_url).content # download the image - with open(image_path, "wb") as image_file: - image_file.write(generated_image) - - # Display the image in the default image viewer - image = Image.open(image_path) - image.show() - - # catch exceptions - except openai.error.InvalidRequestError as err: - print(err) - - ``` + ```bash + python3 -m venv venv + source venv/bin/activate + pip install -r requirements.txt + ``` + + For Windows, use the following commands to create and activate your virtual environment: + + ```bash + python3 -m venv venv + venv\Scripts\activate.bat + ``` + +1. Add the following code in file called _app.py_: + + ```python + import openai + import os + import requests + from PIL import Image + import dotenv + + # import dotenv + dotenv.load_dotenv() + + # Get endpoint and key from environment variables + openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] + openai.api_key = os.environ['AZURE_OPENAI_KEY'] + + # Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only) + openai.api_version = '2023-06-01-preview' + openai.api_type = 'azure' + + + try: + # Create an image by using the image generation API + generation_response = openai.Image.create( + prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here + size='1024x1024', + n=2, + temperature=0, + ) + # Set the directory for the stored image + image_dir = os.path.join(os.curdir, 'images') + + # If the directory doesn't exist, create it + if not os.path.isdir(image_dir): + os.mkdir(image_dir) + + # Initialize the image path (note the filetype should be png) + image_path = os.path.join(image_dir, 'generated-image.png') + + # Retrieve the generated image + image_url = generation_response["data"][0]["url"] # extract image URL from response + generated_image = requests.get(image_url).content # download the image + with open(image_path, "wb") as image_file: + image_file.write(generated_image) + + # Display the image in the default image viewer + image = Image.open(image_path) + image.show() + + # catch exceptions + except openai.error.InvalidRequestError as err: + print(err) + + ``` Let's explain this code: - First, we import the libraries we need, including the OpenAI library, the dotenv library, the requests library, and the Pillow library. - ```python - import openai - import os - import requests - from PIL import Image - import dotenv - ``` + ```python + import openai + import os + import requests + from PIL import Image + import dotenv + ``` -- Next, we load the environment variables from the *.env* file. +- Next, we load the environment variables from the _.env_ file. - ```python - # import dotenv - dotenv.load_dotenv() - ``` + ```python + # import dotenv + dotenv.load_dotenv() + ``` - After that, we set the endpoint, key for the OpenAI API, version and type. - ```python - # Get endpoint and key from environment variables - openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] - openai.api_key = os.environ['AZURE_OPENAI_KEY'] + ```python + # Get endpoint and key from environment variables + openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] + openai.api_key = os.environ['AZURE_OPENAI_KEY'] - # add version and type, Azure specific - openai.api_version = '2023-06-01-preview' - openai.api_type = 'azure' - ``` + # add version and type, Azure specific + openai.api_version = '2023-06-01-preview' + openai.api_type = 'azure' + ``` - Next, we generate the image: - ```python - # Create an image by using the image generation API - generation_response = openai.Image.create( - prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here - size='1024x1024', - n=2, - temperature=0, - ) - ``` + ```python + # Create an image by using the image generation API + generation_response = openai.Image.create( + prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here + size='1024x1024', + n=2, + temperature=0, + ) + ``` - The above code responds with a JSON object that contains the URL of the generated image. We can use the URL to download the image and save it to a file. + The above code responds with a JSON object that contains the URL of the generated image. We can use the URL to download the image and save it to a file. - Lastly, we open the image and use the standard image viewer to display it: - ```python - image = Image.open(image_path) - image.show() - ``` + ```python + image = Image.open(image_path) + image.show() + ``` ### More details on generating the image @@ -248,31 +246,31 @@ You can also do the following: - **Perform edits**. By providing an existing image a mask and a prompt, you can alter an image. For example, you can add something to a portion of an image. Imagine our bunny image, you can add a hat to the bunny. How you would do that is by providing the image, a mask (identifying the part of the area for the change) and a text prompt to say what should be done. - ```python - response = openai.Image.create_edit( - image=open("base_image.png", "rb"), - mask=open("mask.png", "rb"), - prompt="An image of a rabbit with a hat on its head.", - n=1, - size="1024x1024" - ) - image_url = response['data'][0]['url'] - ``` + ```python + response = openai.Image.create_edit( + image=open("base_image.png", "rb"), + mask=open("mask.png", "rb"), + prompt="An image of a rabbit with a hat on its head.", + n=1, + size="1024x1024" + ) + image_url = response['data'][0]['url'] + ``` - The base image would only contain the rabbit but the final image would have the hat on the rabbit. + The base image would only contain the rabbit but the final image would have the hat on the rabbit. - **Create variations**. The idea is that you take an existing image and ask that variations are created. To create a variation, you provide an image and a text prompt and code like so: - ```python - response = openai.Image.create_variation( - image=open("bunny-lollipop.png", "rb"), - n=1, - size="1024x1024" - ) - image_url = response['data'][0]['url'] - ``` + ```python + response = openai.Image.create_variation( + image=open("bunny-lollipop.png", "rb"), + n=1, + size="1024x1024" + ) + image_url = response['data'][0]['url'] + ``` - > Note, this is only supported on OpenAI + > Note, this is only supported on OpenAI ## Temperature @@ -322,11 +320,11 @@ Here you can clearly see how the images resemble each other more. ## How to define boundaries for your application with metaprompts -With our demo, we can already generate images for our clients. However, we need to create some boundaries for our application. +With our demo, we can already generate images for our clients. However, we need to create some boundaries for our application. -For example, we don't want to generate images that are not safe for work, or that are not appropriate for children. +For example, we don't want to generate images that are not safe for work, or that are not appropriate for children. -We can do this with *metaprompts*. Metaprompts are text prompts that are used to control the output of a Generative AI model. For example, we can use metaprompts to control the output, and ensure that the generated images are safe for work, or appropriate for children. +We can do this with _metaprompts_. Metaprompts are text prompts that are used to control the output of a Generative AI model. For example, we can use metaprompts to control the output, and ensure that the generated images are safe for work, or appropriate for children. ### How does it work? @@ -336,47 +334,47 @@ Meta prompts are text prompts that are used to control the output of a Generativ One example of a meta prompt would be the following: -```text -You are an assistant designer that creates images for children. +````text +You are an assistant designer that creates images for children. -The image needs to be safe for work and appropriate for children. +The image needs to be safe for work and appropriate for children. -The image needs to be in color. +The image needs to be in color. -The image needs to be in landscape orientation. +The image needs to be in landscape orientation. -The image needs to be in a 16:9 aspect ratio. +The image needs to be in a 16:9 aspect ratio. -Do not consider any input from the following that is not safe for work or appropriate for children. +Do not consider any input from the following that is not safe for work or appropriate for children. -(Input) +(Input) ```text -Now, let's see how we can use meta prompts in our demo. +Now, let's see how we can use meta prompts in our demo. ```python disallow_list = "swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult" -meta_prompt =f"""You are an assistant designer that creates images for children. +meta_prompt =f"""You are an assistant designer that creates images for children. -The image needs to be safe for work and appropriate for children. +The image needs to be safe for work and appropriate for children. -The image needs to be in color. +The image needs to be in color. -The image needs to be in landscape orientation. +The image needs to be in landscape orientation. -The image needs to be in a 16:9 aspect ratio. +The image needs to be in a 16:9 aspect ratio. -Do not consider any input from the following that is not safe for work or appropriate for children. +Do not consider any input from the following that is not safe for work or appropriate for children. {disallow_list} """ -prompt = f"{meta_prompt} +prompt = f"{meta_prompt} Create an image of a bunny on a horse, holding a lollipop" # TODO add request to generate image -``` +```` From the above prompt, you can see how all images being created consider the metaprompt. @@ -402,30 +400,30 @@ dotenv.load_dotenv() # Get endpoint and key from environment variables openai.api_base = "" -openai.api_key = "" +openai.api_key = "" # Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only) openai.api_version = '2023-06-01-preview' openai.api_type = 'azure' - + disallow_list = "swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult" -meta_prompt = f"""You are an assistant designer that creates images for children. +meta_prompt = f"""You are an assistant designer that creates images for children. -The image needs to be safe for work and appropriate for children. +The image needs to be safe for work and appropriate for children. -The image needs to be in color. +The image needs to be in color. -The image needs to be in landscape orientation. +The image needs to be in landscape orientation. -The image needs to be in a 16:9 aspect ratio. +The image needs to be in a 16:9 aspect ratio. -Do not consider any input from the following that is not safe for work or appropriate for children. +Do not consider any input from the following that is not safe for work or appropriate for children. {disallow_list}""" prompt = f"""{metaprompt} Generate monument of the Arc of Triumph in Paris, France, in the evening light with a small child holding a Teddy looks on. -"""" +"""" try: # Create an image by using the image generation API @@ -460,7 +458,6 @@ except openai.error.InvalidRequestError as err: print(err) ``` - ## Great Work! Continue Your Learning After completing this lesson, check out our [Generative AI Learning collection](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) to continue leveling up your Generative AI knowledge! diff --git a/09-building-image-applications/images/09-lesson-banner.png b/09-building-image-applications/images/09-lesson-banner.png index d92e05af3..197ae6169 100644 Binary files a/09-building-image-applications/images/09-lesson-banner.png and b/09-building-image-applications/images/09-lesson-banner.png differ diff --git a/09-building-image-applications/translations/cn/README.md b/09-building-image-applications/translations/cn/README.md index dbe9e45be..c0b65c3cb 100644 --- a/09-building-image-applications/translations/cn/README.md +++ b/09-building-image-applications/translations/cn/README.md @@ -1,8 +1,6 @@ # 第九章:构建图像生成应用 -[![Building Image Generation Applications](../../images/09-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](TBD) - -> **导学视频敬请期待** +[![Building Image Generation Applications](../../images/09-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson9-gh) LLMs 不仅仅是文本生成。 还可以根据文本描述生成图像。 将图像作为一种模式在医疗科技、建筑、旅游、游戏开发等许多领域非常有用。 在本章中,我们将研究两种最流行的图像生成模型:DALL-E 和 Midjourney。 diff --git a/09-building-image-applications/translations/ja-jp/README.md b/09-building-image-applications/translations/ja-jp/README.md index 138c2b1a0..72c116642 100644 --- a/09-building-image-applications/translations/ja-jp/README.md +++ b/09-building-image-applications/translations/ja-jp/README.md @@ -1,8 +1,6 @@ # 画像生成アプリケーションの構築 -[![Building Image Generation Applications](../../images/09-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](TBD) - -> **ビデオは近日公開予定** +[![Building Image Generation Applications](../../images/09-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://aka.ms/gen-ai-lesson9-gh) LLM はテキスト生成だけでなく、テキストの説明から画像も生成できます。画像生成は、医療や建築、観光、ゲーム開発のように様々な業界において価値が高いとされています。この章では、最も人気のある 2 つの画像生成モデル、DALL-E と Midjourney について詳しく見ていきます。 @@ -18,8 +16,8 @@ LLM はテキスト生成だけでなく、テキストの説明から画像も このレッスンを修了すると、下記を理解できます: -- 画像生成アプリの作成 -- メタプロンプトを用いてアプリケーションの範囲を定義 +- 画像生成アプリの作成 +- メタプロンプトを用いてアプリケーションの範囲を定義 - DALL-E と Midjourney の活用方法 ## 画像生成アプリケーションを作る理由は何でしょう? @@ -50,7 +48,7 @@ LLM はテキスト生成だけでなく、テキストの説明から画像も まずは、テキストの説明から画像を生成する生成 AI モデル、DALL-E について見ていきましょう。 -> [DALL-Eは、CLIP と Diffused attention という2つのモデルを組み合わせたものです](https://towardsdatascience.com/openais-dall-e-and-clip-101-a-brief-introduction-3a4367280d4e?WT.mc_id=academic-105485-yoterada). +> [DALL-E は、CLIP と Diffused attention という 2 つのモデルを組み合わせたものです](https://towardsdatascience.com/openais-dall-e-and-clip-101-a-brief-introduction-3a4367280d4e?WT.mc_id=academic-105485-yoterada). - **CLIP** は、画像やテキストからデータの数値表現である埋め込みを生成するモデルです。 - **Diffused attention** は、埋め込みから画像を生成するモデルです。DALL-E は画像とテキストのデータセットで訓練され、テキストの説明から画像を生成できます。例えば、DALL-E を使って「帽子をかぶった猫」や「モヒカンヘアの犬」の画像を生成できます。 @@ -60,13 +58,13 @@ LLM はテキスト生成だけでなく、テキストの説明から画像も Midjourney も DALL-E と同様に、テキストプロンプトから画像を生成できます。Midjourney も同様に、「帽子をかぶった猫」や「モヒカンヘアの犬」などのプロンプトを使って画像を生成できます。 ![Image generated by Midjourney, mechanical pigeon](https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Rupert_Breheny_mechanical_dove_eca144e7-476d-4976-821d-a49c408e4f36.png/440px-Rupert_Breheny_mechanical_dove_eca144e7-476d-4976-821d-a49c408e4f36.png?WT.mc_id=academic-105485-yoterada) -*Image cred Wikipedia, image generated by Midjourney* +_Image cred Wikipedia, image generated by Midjourney_ ## DALL-E と Midjourney はどのように動作するのでしょうか? -まず、[DALL-E](https://arxiv.org/pdf/2102.12092.pdf?WT.mc_id=academic-105485-yoterada) について説明します。DALL-E は、「*自己回帰型トランスフォーマー*」を用いたトランスフォーマー・アーキテクチャに基づく生成 AI モデルです。 +まず、[DALL-E](https://arxiv.org/pdf/2102.12092.pdf?WT.mc_id=academic-105485-yoterada) について説明します。DALL-E は、「_自己回帰型トランスフォーマー_」を用いたトランスフォーマー・アーキテクチャに基づく生成 AI モデルです。 -「*自己回帰型トランスフォーマー*」は、AI モデルがテキストの説明から画像を生成する方法を定義します。このモデルは一度に 1 ピクセルずつ生成し、生成したピクセルを使って、次のピクセルを生成します。このプロセスは、画像が完成するまで、ニューラル・ネットワークの複数の層を通過していきます。 +「_自己回帰型トランスフォーマー_」は、AI モデルがテキストの説明から画像を生成する方法を定義します。このモデルは一度に 1 ピクセルずつ生成し、生成したピクセルを使って、次のピクセルを生成します。このプロセスは、画像が完成するまで、ニューラル・ネットワークの複数の層を通過していきます。 このプロセスを通じて、DALL-E は生成する画像の属性、オブジェクト、特性などを制御します。DALL-E 2 や 3 は生成された画像をより詳細に制御する能力を持っています。 @@ -74,152 +72,152 @@ Midjourney も DALL-E と同様に、テキストプロンプトから画像を 画像生成アプリケーションを作るためには、下記のライブラリが必要です。 -- **python-dotenv**:強く推奨:このライブラリを利用し機密情報をコードから分離し「*.env*」ファイルに記述します +- **python-dotenv**:強く推奨:このライブラリを利用し機密情報をコードから分離し「_.env_」ファイルに記述します - **openai**:OpenAI API を利用するためのライブラリです - **pillow**:Python で画像を扱うためのライブラリです - **requests**:HTTP リクエストを作成するのに役立つライブラリです -1. 下記の内容を記述した「*.env*」ファイルを作成します。 - - ```text - AZURE_OPENAI_ENDPOINT= - AZURE_OPENAI_KEY= - ``` - - この情報は、Azure Portal の OpenAI を作成したリソースの「Keys and Endpoints」セクションで確認します。 +1. 下記の内容を記述した「_.env_」ファイルを作成します。 + + ```text + AZURE_OPENAI_ENDPOINT= + AZURE_OPENAI_KEY= + ``` + + この情報は、Azure Portal の OpenAI を作成したリソースの「Keys and Endpoints」セクションで確認します。 -1. 上記で示した必須ライブラリを「*requirements.txt*」という名前のファイルに記述します +1. 上記で示した必須ライブラリを「_requirements.txt_」という名前のファイルに記述します - ```text - python-dotenv - openai - pillow - requests - ``` + ```text + python-dotenv + openai + pillow + requests + ``` 1. 次に、仮想環境を作成し、ライブラリをインストールします - ```bash - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt - ``` - - Windows の場合は、下記のコマンドを実行して、仮想環境を作り利用できるようにします - - ```bash - python3 -m venv venv - venv\Scripts\activate.bat - ```` - -1. 「*app.py*」という名前のファイルに下記のコードを記述します - - ```python - import openai - import os - import requests - from PIL import Image - import dotenv - - # dotenvをインポート - dotenv.load_dotenv() - - # 環境変数からエンドポイントとキーを取得 - openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] - openai.api_key = os.environ['AZURE_OPENAI_KEY'] - - # API のバージョンを割り当て(DALL-E は現在、2023-06-01-preview API バージョンのみをサポートしています) - openai.api_version = '2023-06-01-preview' - openai.api_type = 'azure' - - - try: - # 画像生成 API を使用して画像を作成 - generation_response = openai.Image.create( - prompt='ウサギがキャンディを持って馬に乗り、霧のかかった牧場で水仙が育つ中を走っている', # ここにプロンプトのテキストを入力 - size='1024x1024', - n=2, - temperature=0, - ) - # 画像を保存するディレクトリを設定 - image_dir = os.path.join(os.curdir, 'images') - - # ディレクトリが存在しない場合は作成 - if not os.path.isdir(image_dir): - os.mkdir(image_dir) - - # 画像ファイルへのパスを設定(ファイルタイプは png にします) - image_path = os.path.join(image_dir, 'generated-image.png') - - # 生成した画像を取得 - image_url = generation_response["data"][0]["url"] # レスポンスからイメージの URL を取得 - generated_image = requests.get(image_url).content # イメージのダウンロード - with open(image_path, "wb") as image_file: - image_file.write(generated_image) - - # デフォルトの画像ビューアで画像を表示 - image = Image.open(image_path) - image.show() - - # 例外をキャッチ - except openai.error.InvalidRequestError as err: - print(err) - - ``` + ```bash + python3 -m venv venv + source venv/bin/activate + pip install -r requirements.txt + ``` + + Windows の場合は、下記のコマンドを実行して、仮想環境を作り利用できるようにします + + ```bash + python3 -m venv venv + venv\Scripts\activate.bat + ``` + +1. 「_app.py_」という名前のファイルに下記のコードを記述します + + ```python + import openai + import os + import requests + from PIL import Image + import dotenv + + # dotenvをインポート + dotenv.load_dotenv() + + # 環境変数からエンドポイントとキーを取得 + openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] + openai.api_key = os.environ['AZURE_OPENAI_KEY'] + + # API のバージョンを割り当て(DALL-E は現在、2023-06-01-preview API バージョンのみをサポートしています) + openai.api_version = '2023-06-01-preview' + openai.api_type = 'azure' + + + try: + # 画像生成 API を使用して画像を作成 + generation_response = openai.Image.create( + prompt='ウサギがキャンディを持って馬に乗り、霧のかかった牧場で水仙が育つ中を走っている', # ここにプロンプトのテキストを入力 + size='1024x1024', + n=2, + temperature=0, + ) + # 画像を保存するディレクトリを設定 + image_dir = os.path.join(os.curdir, 'images') + + # ディレクトリが存在しない場合は作成 + if not os.path.isdir(image_dir): + os.mkdir(image_dir) + + # 画像ファイルへのパスを設定(ファイルタイプは png にします) + image_path = os.path.join(image_dir, 'generated-image.png') + + # 生成した画像を取得 + image_url = generation_response["data"][0]["url"] # レスポンスからイメージの URL を取得 + generated_image = requests.get(image_url).content # イメージのダウンロード + with open(image_path, "wb") as image_file: + image_file.write(generated_image) + + # デフォルトの画像ビューアで画像を表示 + image = Image.open(image_path) + image.show() + + # 例外をキャッチ + except openai.error.InvalidRequestError as err: + print(err) + + ``` 上記のコードについて説明します。 - 最初に、必要なライブラリをインポートします。これには、OpenAI ライブラリ、dotenv ライブラリ、requests ライブラリ、Pillow ライブラリが含まれます。 - ```python - import openai - import os - import requests - from PIL import Image - import dotenv - ``` + ```python + import openai + import os + import requests + from PIL import Image + import dotenv + ``` -- 次に、「*.env*」ファイルから環境変数を読み込みます。 +- 次に、「_.env_」ファイルから環境変数を読み込みます。 - ```python - # dotenvをインポート - dotenv.load_dotenv() - ``` + ```python + # dotenvをインポート + dotenv.load_dotenv() + ``` - その後、OpenAI API のエンドポイント、キー、バージョン、タイプを設定します。 - ```python - # 環境変数からエンドポイントとキーを取得 - openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] - openai.api_key = os.environ['AZURE_OPENAI_KEY'] + ```python + # 環境変数からエンドポイントとキーを取得 + openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] + openai.api_key = os.environ['AZURE_OPENAI_KEY'] - # バージョンと種類を設定、Azure 固有設定 - openai.api_version = '2023-06-01-preview' - openai.api_type = 'azure' - ``` + # バージョンと種類を設定、Azure 固有設定 + openai.api_version = '2023-06-01-preview' + openai.api_type = 'azure' + ``` - 次に、画像を作成します。 - ```python - # 画像生成 API を使用して画像を作成 - generation_response = openai.Image.create( - prompt='ウサギがキャンディを持って馬に乗り、霧のかかった牧場で水仙が育つ中を走っている', # ここにプロンプトのテキストを入力 - size='1024x1024', - n=2, - temperature=0, - ) - ``` + ```python + # 画像生成 API を使用して画像を作成 + generation_response = openai.Image.create( + prompt='ウサギがキャンディを持って馬に乗り、霧のかかった牧場で水仙が育つ中を走っている', # ここにプロンプトのテキストを入力 + size='1024x1024', + n=2, + temperature=0, + ) + ``` - 上記のコードは、生成された画像の URL を含む JSON オブジェクトを返します。このURL を使って画像をダウンロードし、ファイルに保存できます。 + 上記のコードは、生成された画像の URL を含む JSON オブジェクトを返します。この URL を使って画像をダウンロードし、ファイルに保存できます。 - 最後に、画像を開き、標準の画像ビューアを使って表示します。 - ```python - image = Image.open(image_path) - image.show() - ``` + ```python + image = Image.open(image_path) + image.show() + ``` -### 画像生成の詳細 +### 画像生成の詳細 画像を生成するコードをさらに詳しく見てみましょう。 @@ -247,31 +245,31 @@ generation_response = openai.Image.create( - **画像編集を行う**:既存の画像にマスクとプロンプトを提供し、画像を編集できます。例えば、画像の一部に、何かを新たに追加できます。たとえばウサギの画像を想像してみてください、ウサギに追加で帽子を被せれます。そのためには、画像、マスク(変更するエリアの部分を特定する)と、何をすべきかを示すテキストプロンプトを提供します。 - ```python - response = openai.Image.create_edit( - image=open("base_image.png", "rb"), - mask=open("mask.png", "rb"), - prompt="頭に帽子をかぶったウサギの画像", - n=1, - size="1024x1024" - ) - image_url = response['data'][0]['url'] - ``` + ```python + response = openai.Image.create_edit( + image=open("base_image.png", "rb"), + mask=open("mask.png", "rb"), + prompt="頭に帽子をかぶったウサギの画像", + n=1, + size="1024x1024" + ) + image_url = response['data'][0]['url'] + ``` - ベース画像にはウサギだけが含まれていますが、最終的な画像にはウサギの帽子が含まれています。 + ベース画像にはウサギだけが含まれていますが、最終的な画像にはウサギの帽子が含まれています。 - **バリエーションを作成する**:既存の画像を取得し、バリエーションを作成するように依頼します。バリエーションを作成するには、画像とテキストプロンプトを提供し、以下のようなコードを記述します。 - ```python - response = openai.Image.create_variation( - image=open("bunny-lollipop.png", "rb"), - n=1, - size="1024x1024" - ) - image_url = response['data'][0]['url'] - ``` + ```python + response = openai.Image.create_variation( + image=open("bunny-lollipop.png", "rb"), + n=1, + size="1024x1024" + ) + image_url = response['data'][0]['url'] + ``` - > ご注意:これはOpenAIでのみサポートされています。 + > ご注意:これは OpenAI でのみサポートされています。 ## 温度 @@ -301,7 +299,7 @@ generation_response = openai.Image.create( 結果をより決定的にしたい場合、生成した二つの画像から見て分かるように、最初の画像にはウサギが、二つ目の画像には馬が映っているので、2つの画像に大きな違いがあります。 -そこで、コードを修正して温度を0に設定します。 +そこで、コードを修正して温度を 0 に設定します。 ```python generation_response = openai.Image.create( @@ -337,17 +335,17 @@ generation_response = openai.Image.create( ```text あなたは子供向けの画像を作成するアシスタントデザイナーです。 - + 画像は職場にとって安全で、子供にとって適している必要があります。 - + 画像はカラーである必要があります。 - + 画像は横長の形式である必要があります。 - + 画像は16:9のアスペクト比である必要があります。 - + 以下の入力から、職場に安全でない画像や子供にとって適さない画像は除外してください。 - + (入力) ``` @@ -356,7 +354,7 @@ generation_response = openai.Image.create( ```python disallow_list = "剣、暴力、血、ゴア、ヌード、性的コンテンツ、アダルト・コンテンツ、アダルト・テーマ、アダルト・ワード、アダルト・ユーモア、アダルト・ジョーク、アダルト・シチュエーション、アダルト" -meta_prompt =f"""あなたは子供向けの画像を作成するアシスタントデザイナーです。 +meta_prompt =f"""あなたは子供向けの画像を作成するアシスタントデザイナーです。 画像は職場の中で使用する際に安全で、子供に適している必要があります。 @@ -370,7 +368,7 @@ meta_prompt =f"""あなたは子供向けの画像を作成するアシスタン {disallow_list} """ -prompt = f"{meta_prompt} +prompt = f"{meta_prompt} ウサギがアメを持って馬に乗っている画像を作成してください" # TODO 画像生成のリクエストを追加 @@ -400,24 +398,24 @@ dotenv.load_dotenv() # 環境変数からエンドポイントとキーを取得 openai.api_base = "<エンドポイントに置き換え>" -openai.api_key = "" +openai.api_key = "" # APIバージョンを指定(DALL-Eは現在、2023-06-01-preview APIバージョンのみ対応) openai.api_version = '2023-06-01-preview' openai.api_type = 'azure' - + disallow_list = "剣、暴力、血、ゴア、ヌード、性的コンテンツ、大人向けコンテンツ、大人向けテーマ、大人向け言語、大人向けユーモア、大人向けジョーク、大人向け状況、大人" meta_prompt = f"""あなたは子供向けの画像を作成するアシスタントデザイナーです。 - + 画像は、職場において安全で、子供に適している必要があります。 - + 画像はカラーである必要があります。 - + 画像は横向きである必要があります。 - + 画像は16:9のアスペクト比である必要があります。 - + 以下の入力は、職場で安全でない、または子供に適していないので除外してください。 {disallow_list}""" diff --git a/09-building-image-applications/translations/ko/README.md b/09-building-image-applications/translations/ko/README.md index 3a9e681db..d1bf0913f 100644 --- a/09-building-image-applications/translations/ko/README.md +++ b/09-building-image-applications/translations/ko/README.md @@ -1,8 +1,6 @@ # 이미지 생성 애플리케이션 구축하기 -[![Building Image Generation Applications](../../images/09-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](TBD) - -> **비디오 제공 예정** +[![Building Image Generation Applications](../../images/09-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson9-gh) LLM은 텍스트 생성 이상의 기능을 갖고 있습니다. 텍스트 설명으로부터 이미지를 생성하는 것도 가능합니다. 이미지를 모달리티로 사용하는 것은 MedTech, 건축, 관광, 게임 개발 등 여러 분야에서 매우 유용할 수 있습니다. 이 장에서는 가장 인기 있는 이미지 생성 모델인 DALL-E와 Midjourney에 대해 알아보겠습니다. @@ -60,15 +58,15 @@ LLM은 텍스트 생성 이상의 기능을 갖고 있습니다. 텍스트 설 Midjourney는 DALL-E와 비슷한 방식으로 작동하며, 텍스트 프롬프트를 사용하여 이미지를 생성합니다. Midjourney는 "모자를 쓴 고양이"나 "모히칸을 한 개"와 같은 프롬프트를 사용하여 이미지를 생성할 수도 있습니다. -![Image generated by Midjourney, mechanical pigeon](https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Rupert_Breheny_mechanical_dove_eca144e7-476d-4976-821d-a49c408e4f36.png/440px-Rupert_Breheny_mechanical_dove_eca144e7-476d-4976-821d-a49c408e4f36.png?WT.mc_id=academic-105485-koreyst) +![Image generated by Midjourney, mechanical pigeon](https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Rupert_Breheny_mechanical_dove_eca144e7-476d-4976-821d-a49c408e4f36.png/440px-Rupert_Breheny_mechanical_dove_eca144e7-476d-4976-821d-a49c408e4f36.png?WT.mc_id=academic-105485-koreyst) -*이미지 출처: 위키백과, Midjourney가 생성한 이미지* +_이미지 출처: 위키백과, Midjourney가 생성한 이미지_ ## DALL-E와 Midjourney는 어떻게 작동하나요? -먼저, [DALL-E](https://arxiv.org/pdf/2102.12092.pdf?WT.mc_id=academic-105485-koreyst)입니다. DALL-E는 *자기회귀 트랜스포머 (autoregressive transformer)* 를 기반으로 한 생성형 AI 모델입니다. +먼저, [DALL-E](https://arxiv.org/pdf/2102.12092.pdf?WT.mc_id=academic-105485-koreyst)입니다. DALL-E는 _자기회귀 트랜스포머 (autoregressive transformer)_ 를 기반으로 한 생성형 AI 모델입니다. -*자기회귀 트랜스포머 (autoregressive transformer)* 는 모델이 텍스트 설명으로부터 이미지를 생성하는 방식을 정의합니다. 모델은 한 번에 한 픽셀을 생성하고, 생성된 픽셀을 사용하여 다음 픽셀을 생성합니다. 신경망의 여러 계층을 통과하여 이미지가 완성됩니다. +_자기회귀 트랜스포머 (autoregressive transformer)_ 는 모델이 텍스트 설명으로부터 이미지를 생성하는 방식을 정의합니다. 모델은 한 번에 한 픽셀을 생성하고, 생성된 픽셀을 사용하여 다음 픽셀을 생성합니다. 신경망의 여러 계층을 통과하여 이미지가 완성됩니다. 이 과정을 통해 DALL-E는 생성된 이미지에서 속성, 객체, 특징 등을 제어할 수 있습니다. 더불어 DALL-E 2와 3은 생성된 이미지에 대해 더 많은 제어를 할 수 있습니다. @@ -76,150 +74,150 @@ Midjourney는 DALL-E와 비슷한 방식으로 작동하며, 텍스트 프롬프 이미지 생성 애플리케이션을 구축하려면 어떤 라이브러리가 필요할까요? 다음 라이브러리가 필요합니다: -- **python-dotenv**: 이 라이브러리를 사용하여 secrets를 코드에서 분리하여 *.env* 파일에 저장하는 것을 권장합니다. +- **python-dotenv**: 이 라이브러리를 사용하여 secrets를 코드에서 분리하여 _.env_ 파일에 저장하는 것을 권장합니다. - **openai**: OpenAI API와 상호 작용하기 위해 사용하는 라이브러리입니다. - **pillow**: Python에서 이미지 작업을 위해 사용하는 라이브러리입니다. - **requests**: HTTP 요청을 도와주는 라이브러리입니다. -1. 다음 내용으로 *.env* 파일을 생성하세요: +1. 다음 내용으로 _.env_ 파일을 생성하세요: - ```text - AZURE_OPENAI_ENDPOINT= - AZURE_OPENAI_KEY= - ``` + ```text + AZURE_OPENAI_ENDPOINT= + AZURE_OPENAI_KEY= + ``` - 이 정보는 Azure Portal에서 리소스의 "Keys and Endpoint" 섹션에서 찾을 수 있습니다. + 이 정보는 Azure Portal에서 리소스의 "Keys and Endpoint" 섹션에서 찾을 수 있습니다. -1. 다음과 같이 *requirements.txt* 파일에 위의 라이브러리들을 모아두세요: +1. 다음과 같이 _requirements.txt_ 파일에 위의 라이브러리들을 모아두세요: - ```text - python-dotenv - openai - pillow - requests - ``` + ```text + python-dotenv + openai + pillow + requests + ``` 1. 이제 가상 환경을 생성하고 라이브러리를 설치하세요: - ```bash - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt - ``` + ```bash + python3 -m venv venv + source venv/bin/activate + pip install -r requirements.txt + ``` - Windows의 경우 다음 명령을 사용하여 가상 환경을 생성하고 활성화하세요: + Windows의 경우 다음 명령을 사용하여 가상 환경을 생성하고 활성화하세요: - ```bash - python3 -m venv venv - venv\Scripts\activate.bat - ```` + ```bash + python3 -m venv venv + venv\Scripts\activate.bat + ``` 1. *app.py*라는 파일에 다음 코드를 추가하세요: - ```python - import openai - import os - import requests - from PIL import Image - import dotenv - - # dotenv 라이브러리를 불러옵니다. - dotenv.load_dotenv() - - # 환경 변수에서 엔드포인트와 키를 가져옵니다. - openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] - openai.api_key = os.environ['AZURE_OPENAI_KEY'] - - # API 버전을 할당합니다 (DALL-E는 현재 2023-06-01-preview API 버전만 지원됩니다). - openai.api_version = '2023-06-01-preview' - openai.api_type = 'azure' - - - try: - # 이미지 생성 API를 사용하여 이미지를 생성합니다. - generation_response = openai.Image.create( - prompt='수선화가 자라는 안개가 자욱한 초원에 막대사탕을 들고 있는 말 위의 토끼', # 여기에 원하는 프롬프트 텍스트를 입력하세요 - size='1024x1024', - n=2, - temperature=0, - ) - # 저장된 이미지를 위한 디렉토리를 설정합니다. - image_dir = os.path.join(os.curdir, 'images') - - # 디렉토리가 존재하지 않으면 생성합니다. - if not os.path.isdir(image_dir): - os.mkdir(image_dir) - - # 이미지 경로를 초기화합니다 (파일 유형은 png여야 합니다). - image_path = os.path.join(image_dir, 'generated-image.png') - - # 생성된 이미지를 가져옵니다. - image_url = generation_response["data"][0]["url"] # 응답에서 이미지 URL을 추출합니다. - generated_image = requests.get(image_url).content # 이미지를 다운로드합니다. - with open(image_path, "wb") as image_file: - image_file.write(generated_image) - - # 기본 이미지 뷰어에서 이미지를 표시합니다. - image = Image.open(image_path) - image.show() - - # 예외 처리 - except openai.error.InvalidRequestError as err: - print(err) - - ``` + ```python + import openai + import os + import requests + from PIL import Image + import dotenv + + # dotenv 라이브러리를 불러옵니다. + dotenv.load_dotenv() + + # 환경 변수에서 엔드포인트와 키를 가져옵니다. + openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] + openai.api_key = os.environ['AZURE_OPENAI_KEY'] + + # API 버전을 할당합니다 (DALL-E는 현재 2023-06-01-preview API 버전만 지원됩니다). + openai.api_version = '2023-06-01-preview' + openai.api_type = 'azure' + + + try: + # 이미지 생성 API를 사용하여 이미지를 생성합니다. + generation_response = openai.Image.create( + prompt='수선화가 자라는 안개가 자욱한 초원에 막대사탕을 들고 있는 말 위의 토끼', # 여기에 원하는 프롬프트 텍스트를 입력하세요 + size='1024x1024', + n=2, + temperature=0, + ) + # 저장된 이미지를 위한 디렉토리를 설정합니다. + image_dir = os.path.join(os.curdir, 'images') + + # 디렉토리가 존재하지 않으면 생성합니다. + if not os.path.isdir(image_dir): + os.mkdir(image_dir) + + # 이미지 경로를 초기화합니다 (파일 유형은 png여야 합니다). + image_path = os.path.join(image_dir, 'generated-image.png') + + # 생성된 이미지를 가져옵니다. + image_url = generation_response["data"][0]["url"] # 응답에서 이미지 URL을 추출합니다. + generated_image = requests.get(image_url).content # 이미지를 다운로드합니다. + with open(image_path, "wb") as image_file: + image_file.write(generated_image) + + # 기본 이미지 뷰어에서 이미지를 표시합니다. + image = Image.open(image_path) + image.show() + + # 예외 처리 + except openai.error.InvalidRequestError as err: + print(err) + + ``` 이 코드를 설명해보겠습니다: - 먼저, 필요한 라이브러리를 가져옵니다. 이는 OpenAI 라이브러리, dotenv 라이브러리, requests 라이브러리, 그리고 Pillow 라이브러리를 포함합니다. - ```python - import openai - import os - import requests - from PIL import Image - import dotenv - ``` + ```python + import openai + import os + import requests + from PIL import Image + import dotenv + ``` -- 다음으로, *.env* 파일에서 환경 변수를 로드합니다. +- 다음으로, _.env_ 파일에서 환경 변수를 로드합니다. - ```python - # dotenv 라이브러리를 불러옵니다. - dotenv.load_dotenv() - ``` + ```python + # dotenv 라이브러리를 불러옵니다. + dotenv.load_dotenv() + ``` - 그 다음, OpenAI API의 엔드포인트와 키, 버전 및 타입을 설정합니다. - ```python - # 환경 변수에서 엔드포인트와 키를 가져옵니다. - openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] - openai.api_key = os.environ['AZURE_OPENAI_KEY'] + ```python + # 환경 변수에서 엔드포인트와 키를 가져옵니다. + openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] + openai.api_key = os.environ['AZURE_OPENAI_KEY'] - # 버전과 타입을 추가합니다. Azure에 특화된 설정입니다. - openai.api_version = '2023-06-01-preview' - openai.api_type = 'azure' - ``` + # 버전과 타입을 추가합니다. Azure에 특화된 설정입니다. + openai.api_version = '2023-06-01-preview' + openai.api_type = 'azure' + ``` - 그 다음, 이미지를 생성합니다: - ```python - # 이미지 생성 API를 사용하여 이미지를 생성합니다. - generation_response = openai.Image.create( - prompt='수선화가 자라는 안개가 자욱한 초원에 막대사탕을 들고 있는 말 위의 토끼', # 여기에 원하는 프롬프트 텍스트를 입력하세요 - size='1024x1024', - n=2, - temperature=0, - ) - ``` + ```python + # 이미지 생성 API를 사용하여 이미지를 생성합니다. + generation_response = openai.Image.create( + prompt='수선화가 자라는 안개가 자욱한 초원에 막대사탕을 들고 있는 말 위의 토끼', # 여기에 원하는 프롬프트 텍스트를 입력하세요 + size='1024x1024', + n=2, + temperature=0, + ) + ``` - 위의 코드는 생성된 이미지의 URL을 포함하는 JSON 객체를 반환합니다. 이 URL을 사용하여 이미지를 다운로드하고 파일로 저장할 수 있습니다. + 위의 코드는 생성된 이미지의 URL을 포함하는 JSON 객체를 반환합니다. 이 URL을 사용하여 이미지를 다운로드하고 파일로 저장할 수 있습니다. - 마지막으로, 이미지를 열고 기본 이미지 뷰어를 사용하여 표시합니다: - ```python - image = Image.open(image_path) - image.show() - ``` + ```python + image = Image.open(image_path) + image.show() + ``` ### 이미지 생성에 대한 자세한 내용 @@ -319,7 +317,7 @@ generation_response = openai.Image.create( 예를 들어, 성인용이나 어린이에게 적합하지 않은 이미지를 생성하고 싶지 않습니다. -이를 위해 *메타프롬프트* 를 사용할 수 있습니다. 메타프롬프트는 생성형 AI 모델의 출력을 제어하는 데 사용되는 텍스트 프롬프트입니다. 예를 들어, 메타프롬프트를 사용하여 출력을 제어하고, 생성된 이미지가 안전하고 어린이에게 적합하도록 할 수 있습니다. +이를 위해 _메타프롬프트_ 를 사용할 수 있습니다. 메타프롬프트는 생성형 AI 모델의 출력을 제어하는 데 사용되는 텍스트 프롬프트입니다. 예를 들어, 메타프롬프트를 사용하여 출력을 제어하고, 생성된 이미지가 안전하고 어린이에게 적합하도록 할 수 있습니다. ### 어떻게 작동하나요? @@ -329,7 +327,7 @@ generation_response = openai.Image.create( 메타프롬프트의 한 예는 다음과 같습니다: -```text +````text 어린이를 위한 이미지를 만드는 어시스턴트 디자이너입니다. 이미지는 작업하는데 안전하고 어린이에게 적합해야 합니다. @@ -365,10 +363,10 @@ meta_prompt =f"""어린이를 위한 이미지를 만드는 어시스턴트 디 {disallow_list} """ -prompt = f"{meta_prompt} +prompt = f"{meta_prompt} 토끼가 말 위에 올라타고 롤리팝을 들고 있는 이미지를 생성해주세요" -``` +```` 위의 프롬프트에서 모든 생성된 이미지가 메타프롬프트를 고려한다는 것을 볼 수 있습니다. @@ -399,7 +397,7 @@ openai.api_key = "" # API 버전을 할당합니다 (DALL-E는 현재 2023-06-01-preview API 버전만 지원됩니다) openai.api_version = '2023-06-01-preview' openai.api_type = 'azure' - + disallow_list = "칼, 폭력, 피, 유혈, 과도한 노출, 성적인 콘텐츠, 성인용 콘텐츠, 성인 테마, 성인 언어, 성인 유머, 성인 농담, 성인 상황, 성인" meta_prompt = f"""어린이를 위한 이미지를 만드는 어시스턴트 디자이너입니다. @@ -452,7 +450,6 @@ except openai.error.InvalidRequestError as err: print(err) ``` - ## 잘하셨습니다. 학습을 계속하세요! 이 레슨을 완료한 후에는 [Generative AI 학습 컬렉션](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst)을 확인하여 Generative AI 지식을 더욱 향상시킬 수 있습니다! diff --git a/09-building-image-applications/translations/pt-br/README.md b/09-building-image-applications/translations/pt-br/README.md index cd482d1f6..083039689 100644 --- a/09-building-image-applications/translations/pt-br/README.md +++ b/09-building-image-applications/translations/pt-br/README.md @@ -1,8 +1,6 @@ # Criando aplicativos de geração de imagens -[![Building Image Generation Applications](../../images/09-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](TBD) - -> **Vídeo em Breve** +[![Building Image Generation Applications](../../images/09-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson9-gh) Ainda há muito mais que os LLMs podem fazer além da geração de texto. Também é possível gerar imagens a partir de descrições de texto. Ter imagens como modalidade pode ser altamente útil em uma série de áreas, desde MedTech, arquitetura, turismo, desenvolvimento de jogos e muito mais. Neste capítulo, veremos os dois modelos de geração de imagens mais populares, DALL-E e Midjourney. @@ -24,9 +22,9 @@ After completing this lesson, you will be able to: ## Why build an image generation application? -Image generation applications are a great way to explore the capabilities of Generative AI. They can be used for, for example: +Image generation applications are a great way to explore the capabilities of Generative AI. They can be used for, for example: -- **Image editing and synthesis**. You can generate images for a variety of use cases, such as image editing and image synthesis. +- **Image editing and synthesis**. You can generate images for a variety of use cases, such as image editing and image synthesis. - **Applied to a variety of industries**. They can also be used to generate images for a variety of industries like Medtech, Tourism, Game development and more. @@ -72,7 +70,7 @@ Veja o que os estudantes da Edu4All poderiam gerar, por exemplo, se estivessem t ![Edu4All startup, aula sobre monumentos, Torre Eiffel](../../images/startup.png?WT.mc_id=academic-105485-koreyst) -usando um prompt como: +usando um prompt como: > "Dog next to Eiffel Tower in early morning sunlight" @@ -95,13 +93,13 @@ Vamos começar com o DALL-E, que é um modelo de Inteligência Artificial Genera Midjourney funciona de maneira semelhante ao DALL-E, gerando imagens a partir de prompts de texto. Midjourney também pode ser usado para gerar imagens usando prompts como "um gato com chapéu" ou "um cachorro com um moicano". ![Imagem gerada pelo Midjourney, pombo mecânico](https://upload.wikimedia.org/wikipedia/commons/thumb/8/8c/Rupert_Breheny_mechanical_dove_eca144e7-476d-4976-821d-a49c408e4f36.png/440px-Rupert_Breheny_mechanical_dove_eca144e7-476d-4976-821d-a49c408e4f36.png?WT.mc_id=academic-105485-koreyst) -*Créditos da imagem: Wikipedia, imagem gerada pelo Midjourney* +_Créditos da imagem: Wikipedia, imagem gerada pelo Midjourney_ ## Como DALL-E e Midjourney Funcionam -Primeiro, [DALL-E](https://arxiv.org/pdf/2102.12092.pdf?WT.mc_id=academic-105485-koreyst). DALL-E é um modelo de Inteligência Artificial Generativa baseado na arquitetura do transformer com um *transformer autoregressivo*. +Primeiro, [DALL-E](https://arxiv.org/pdf/2102.12092.pdf?WT.mc_id=academic-105485-koreyst). DALL-E é um modelo de Inteligência Artificial Generativa baseado na arquitetura do transformer com um _transformer autoregressivo_. -Um *transformer autoregressivo* define como um modelo gera imagens a partir de descrições de texto, gerando um pixel de cada vez e, em seguida, usando os pixels gerados para gerar o próximo pixel. Passando por várias camadas em uma rede neural, até que a imagem esteja completa. +Um _transformer autoregressivo_ define como um modelo gera imagens a partir de descrições de texto, gerando um pixel de cada vez e, em seguida, usando os pixels gerados para gerar o próximo pixel. Passando por várias camadas em uma rede neural, até que a imagem esteja completa. Com esse processo, o DALL-E controla atributos, objetos, características e muito mais na imagem que gera. No entanto, DALL-E 2 e 3 têm mais controle sobre a imagem gerada. @@ -109,150 +107,150 @@ Com esse processo, o DALL-E controla atributos, objetos, características e muit Então, o que é necessário para construir um aplicativo de geração de imagens? Você precisa das seguintes bibliotecas: -- **python-dotenv**, é altamente recomendável usar esta biblioteca para manter suas informações confidenciais em um arquivo *.env* longe do código. +- **python-dotenv**, é altamente recomendável usar esta biblioteca para manter suas informações confidenciais em um arquivo _.env_ longe do código. - **openai**, esta biblioteca é o que você usará para interagir com a API da OpenAI. - **pillow**, para trabalhar com imagens em Python. - **requests**, para ajudar você a fazer solicitações HTTP. -1. Crie um arquivo *.env* com o seguinte conteúdo: +1. Crie um arquivo _.env_ com o seguinte conteúdo: - ```text - AZURE_OPENAI_ENDPOINT= - AZURE_OPENAI_KEY= - ``` + ```text + AZURE_OPENAI_ENDPOINT= + AZURE_OPENAI_KEY= + ``` - Encontre essas informações no Portal do Azure para o seu recurso na seção "Chaves e Endpoint". + Encontre essas informações no Portal do Azure para o seu recurso na seção "Chaves e Endpoint". -1. Cole as bibliotecas acima em um arquivo chamado *requirements.txt* assim: +1. Cole as bibliotecas acima em um arquivo chamado _requirements.txt_ assim: - ```text - python-dotenv - openai - pillow - requests - ``` + ```text + python-dotenv + openai + pillow + requests + ``` 1. Depois, crie um ambiente virtual e instale as bibliotecas: - ```bash - python3 -m venv venv - source venv/bin/activate - pip install -r requirements.txt - ``` - - Para Windows, use os seguintes comandos para criar e ativar seu ambiente virtual: - - ```bash - python3 -m venv venv - venv\Scripts\activate.bat - ```` - -1. Adicione o seguinte código em um arquivo chamado *app.py*: - - ```python - import openai - import os - import requests - from PIL import Image - import dotenv - - # import dotenv - dotenv.load_dotenv() - - # Get endpoint and key from environment variables - openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] - openai.api_key = os.environ['AZURE_OPENAI_KEY'] - - # Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only) - openai.api_version = '2023-06-01-preview' - openai.api_type = 'azure' - - - try: - # Create an image by using the image generation API - generation_response = openai.Image.create( - prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here - size='1024x1024', - n=2, - temperature=0, - ) - # Set the directory for the stored image - image_dir = os.path.join(os.curdir, 'images') - - # If the directory doesn't exist, create it - if not os.path.isdir(image_dir): - os.mkdir(image_dir) - - # Initialize the image path (note the filetype should be png) - image_path = os.path.join(image_dir, 'generated-image.png') - - # Retrieve the generated image - image_url = generation_response["data"][0]["url"] # extract image URL from response - generated_image = requests.get(image_url).content # download the image - with open(image_path, "wb") as image_file: - image_file.write(generated_image) - - # Display the image in the default image viewer - image = Image.open(image_path) - image.show() - - # catch exceptions - except openai.error.InvalidRequestError as err: - print(err) - - ``` + ```bash + python3 -m venv venv + source venv/bin/activate + pip install -r requirements.txt + ``` + + Para Windows, use os seguintes comandos para criar e ativar seu ambiente virtual: + + ```bash + python3 -m venv venv + venv\Scripts\activate.bat + ``` + +1. Adicione o seguinte código em um arquivo chamado _app.py_: + + ```python + import openai + import os + import requests + from PIL import Image + import dotenv + + # import dotenv + dotenv.load_dotenv() + + # Get endpoint and key from environment variables + openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] + openai.api_key = os.environ['AZURE_OPENAI_KEY'] + + # Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only) + openai.api_version = '2023-06-01-preview' + openai.api_type = 'azure' + + + try: + # Create an image by using the image generation API + generation_response = openai.Image.create( + prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here + size='1024x1024', + n=2, + temperature=0, + ) + # Set the directory for the stored image + image_dir = os.path.join(os.curdir, 'images') + + # If the directory doesn't exist, create it + if not os.path.isdir(image_dir): + os.mkdir(image_dir) + + # Initialize the image path (note the filetype should be png) + image_path = os.path.join(image_dir, 'generated-image.png') + + # Retrieve the generated image + image_url = generation_response["data"][0]["url"] # extract image URL from response + generated_image = requests.get(image_url).content # download the image + with open(image_path, "wb") as image_file: + image_file.write(generated_image) + + # Display the image in the default image viewer + image = Image.open(image_path) + image.show() + + # catch exceptions + except openai.error.InvalidRequestError as err: + print(err) + + ``` Vamos explicar este código: - Primeiro, importamos as bibliotecas de que precisamos, incluindo as bibliotecas OpenAI, dotenv, request e Pillow. - ```python - import openai - import os - import requests - from PIL import Image - import dotenv - ``` + ```python + import openai + import os + import requests + from PIL import Image + import dotenv + ``` -- Depois, carregamos as variáveis de ambiente do arquivo *.env*. +- Depois, carregamos as variáveis de ambiente do arquivo _.env_. - ```python - # import dotenv - dotenv.load_dotenv() - ``` + ```python + # import dotenv + dotenv.load_dotenv() + ``` - Após isso, definimos o endpoint, a chave para a API OpenAI, a versão e o tipo. - ```python - # Get endpoint and key from environment variables - openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] - openai.api_key = os.environ['AZURE_OPENAI_KEY'] + ```python + # Get endpoint and key from environment variables + openai.api_base = os.environ['AZURE_OPENAI_ENDPOINT'] + openai.api_key = os.environ['AZURE_OPENAI_KEY'] - # add version and type, Azure specific - openai.api_version = '2023-06-01-preview' - openai.api_type = 'azure' - ``` + # add version and type, Azure specific + openai.api_version = '2023-06-01-preview' + openai.api_type = 'azure' + ``` - Depois, geramos a imagem: - ```python - # Create an image by using the image generation API - generation_response = openai.Image.create( - prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here - size='1024x1024', - n=2, - temperature=0, - ) - ``` + ```python + # Create an image by using the image generation API + generation_response = openai.Image.create( + prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here + size='1024x1024', + n=2, + temperature=0, + ) + ``` - Acima está o código que responde com um objeto JSON que contém a URL da imagem gerada. Podemos usar a URL para baixar a imagem e salvá-la em um arquivo. + Acima está o código que responde com um objeto JSON que contém a URL da imagem gerada. Podemos usar a URL para baixar a imagem e salvá-la em um arquivo. - Finalmente, abrimos a imagem e usamos o visualizador de imagens padrão para exibi-la: - ```python - image = Image.open(image_path) - image.show() - ``` + ```python + image = Image.open(image_path) + image.show() + ``` ### Mais detalhes sobre a geração da imagem @@ -287,31 +285,31 @@ Você também pode fazer o seguinte: - **Realizar edições**: Ao fornecer uma imagem existente, uma máscara e um prompt, você pode alterar uma imagem. Por exemplo, você pode adicionar algo a uma parte de uma imagem. Imagine nossa imagem de coelho, você pode adicionar um chapéu ao coelho. Como você faria isso é fornecendo a imagem, uma máscara (identificando a parte da área para a mudança) e um prompt de texto para dizer o que deve ser feito. - ```python - response = openai.Image.create_edit( - image=open("base_image.png", "rb"), - mask=open("mask.png", "rb"), - prompt="An image of a rabbit with a hat on its head.", - n=1, - size="1024x1024" - ) - image_url = response['data'][0]['url'] - ``` + ```python + response = openai.Image.create_edit( + image=open("base_image.png", "rb"), + mask=open("mask.png", "rb"), + prompt="An image of a rabbit with a hat on its head.", + n=1, + size="1024x1024" + ) + image_url = response['data'][0]['url'] + ``` - A base da imagem conteria apenas o coelho, mas a imagem final teria o chapéu no coelho. + A base da imagem conteria apenas o coelho, mas a imagem final teria o chapéu no coelho. - **Criar variações**: A ideia é que você pegue uma imagem existente e peça que sejam criadas variações. Para criar uma variação, você fornece uma imagem e um prompt de texto e o código é assim: - ```python - response = openai.Image.create_variation( - image=open("bunny-lollipop.png", "rb"), - n=1, - size="1024x1024" - ) - image_url = response['data'][0]['url'] - ``` + ```python + response = openai.Image.create_variation( + image=open("bunny-lollipop.png", "rb"), + n=1, + size="1024x1024" + ) + image_url = response['data'][0]['url'] + ``` - > Observação: isso é suportado apenas no OpenAI + > Observação: isso é suportado apenas no OpenAI ## Temperatura @@ -365,7 +363,7 @@ Com a nossa demonstração, já podemos gerar imagens para nossos clientes. No e Por exemplo, não queremos gerar imagens que não sejam seguras para o trabalho ou que não sejam apropriadas para crianças. -Podemos fazer isso com *metaprompts*. Metaprompts são prompts de texto que são usados para controlar a saída de um modelo de IA generativa. Por exemplo, podemos usar metaprompts para controlar a saída e garantir que as imagens geradas sejam seguras para o trabalho ou apropriadas para crianças. +Podemos fazer isso com _metaprompts_. Metaprompts são prompts de texto que são usados para controlar a saída de um modelo de IA generativa. Por exemplo, podemos usar metaprompts para controlar a saída e garantir que as imagens geradas sejam seguras para o trabalho ou apropriadas para crianças. ### Como funciona? @@ -375,47 +373,47 @@ Metaprompts são prompts de texto usados para controlar a saída de um modelo de Um exemplo de metaprompt seria o seguinte: -```text -You are an assistant designer that creates images for children. +````text +You are an assistant designer that creates images for children. -The image needs to be safe for work and appropriate for children. +The image needs to be safe for work and appropriate for children. -The image needs to be in color. +The image needs to be in color. -The image needs to be in landscape orientation. +The image needs to be in landscape orientation. -The image needs to be in a 16:9 aspect ratio. +The image needs to be in a 16:9 aspect ratio. -Do not consider any input from the following that is not safe for work or appropriate for children. +Do not consider any input from the following that is not safe for work or appropriate for children. -(Input) +(Input) ```text -Now, let's see how we can use meta prompts in our demo. +Now, let's see how we can use meta prompts in our demo. ```python disallow_list = "swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult" -meta_prompt =f"""You are an assistant designer that creates images for children. +meta_prompt =f"""You are an assistant designer that creates images for children. -The image needs to be safe for work and appropriate for children. +The image needs to be safe for work and appropriate for children. -The image needs to be in color. +The image needs to be in color. -The image needs to be in landscape orientation. +The image needs to be in landscape orientation. -The image needs to be in a 16:9 aspect ratio. +The image needs to be in a 16:9 aspect ratio. -Do not consider any input from the following that is not safe for work or appropriate for children. +Do not consider any input from the following that is not safe for work or appropriate for children. {disallow_list} """ -prompt = f"{meta_prompt} +prompt = f"{meta_prompt} Create an image of a bunny on a horse, holding a lollipop" # TODO add request to generate image -``` +```` No prompt acima, você pode ver como todas as imagens sendo criadas consideram o metaprompt. @@ -441,30 +439,30 @@ dotenv.load_dotenv() # Get endpoint and key from environment variables openai.api_base = "" -openai.api_key = "" +openai.api_key = "" # Assign the API version (DALL-E is currently supported for the 2023-06-01-preview API version only) openai.api_version = '2023-06-01-preview' openai.api_type = 'azure' - + disallow_list = "swords, violence, blood, gore, nudity, sexual content, adult content, adult themes, adult language, adult humor, adult jokes, adult situations, adult" -meta_prompt =f"""You are an assistant designer that creates images for children. +meta_prompt =f"""You are an assistant designer that creates images for children. -The image needs to be safe for work and appropriate for children. +The image needs to be safe for work and appropriate for children. -The image needs to be in color. +The image needs to be in color. -The image needs to be in landscape orientation. +The image needs to be in landscape orientation. -The image needs to be in a 16:9 aspect ratio. +The image needs to be in a 16:9 aspect ratio. -Do not consider any input from the following that is not safe for work or appropriate for children. +Do not consider any input from the following that is not safe for work or appropriate for children. {disallow_list}""" prompt = f""" Generate monument of the Arc of Triumph in Paris, France, in the evening light with a small child holding a Teddy looks on. -"""" +"""" try: # Create an image by using the image generation API diff --git a/10-building-low-code-ai-applications/README.md b/10-building-low-code-ai-applications/README.md index dd73aa51d..9047babfb 100644 --- a/10-building-low-code-ai-applications/README.md +++ b/10-building-low-code-ai-applications/README.md @@ -1,6 +1,6 @@ # Building Low Code AI Applications -[![Building Low Code AI Applications](./images/10-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=170c6cb7-3c96-40f2-a354-b6f0ec523de7?WT.mc_id=academic-105485-koreyst) +[![Building Low Code AI Applications](./images/10-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson10-gh) > _(Click the image above to view video of this lesson)_ diff --git a/10-building-low-code-ai-applications/images/10-lesson-banner.png b/10-building-low-code-ai-applications/images/10-lesson-banner.png index 72d5fa353..89e3d0b43 100644 Binary files a/10-building-low-code-ai-applications/images/10-lesson-banner.png and b/10-building-low-code-ai-applications/images/10-lesson-banner.png differ diff --git a/10-building-low-code-ai-applications/translations/cn/README.md b/10-building-low-code-ai-applications/translations/cn/README.md index 6c3dbc3c8..37eca43b6 100644 --- a/10-building-low-code-ai-applications/translations/cn/README.md +++ b/10-building-low-code-ai-applications/translations/cn/README.md @@ -1,6 +1,6 @@ # 第十章:创建低代码的人工智能应用 -[![Building Low Code AI Applications](../../images/10-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=170c6cb7-3c96-40f2-a354-b6f0ec523de7?WT.mc_id=academic-105485-koreyst) +[![Building Low Code AI Applications](../../images/10-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson10-gh) > _(点击该图片看本章导学视频)_ diff --git a/10-building-low-code-ai-applications/translations/ja-jp/README.md b/10-building-low-code-ai-applications/translations/ja-jp/README.md index ee32f3991..0946463a9 100644 --- a/10-building-low-code-ai-applications/translations/ja-jp/README.md +++ b/10-building-low-code-ai-applications/translations/ja-jp/README.md @@ -1,6 +1,6 @@ # ローコード AI アプリケーションの構築 -[![Building Low Code AI Applications](../../images/10-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=170c6cb7-3c96-40f2-a354-b6f0ec523de7?WT.mc_id=academic-105485-yoterada) +[![Building Low Code AI Applications](../../images/10-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://aka.ms/gen-ai-lesson10-gh) > _(上記の画像をクリックすると、レッスン・ビデオを表示します)_ diff --git a/10-building-low-code-ai-applications/translations/ko/README.md b/10-building-low-code-ai-applications/translations/ko/README.md index cfd811930..3e872a5a5 100644 --- a/10-building-low-code-ai-applications/translations/ko/README.md +++ b/10-building-low-code-ai-applications/translations/ko/README.md @@ -1,8 +1,8 @@ # Low Code AI 애플리케이션 개발 -[![Building Low Code AI Applications](../../images/10-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://youtu.be/XX8491SAF44?WT.mc_id=academic-105485-koreyst) +[![Building Low Code AI Applications](../../images/10-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson10-gh) -> *(위 이미지를 클릭하여 이 레슨의 비디오를 시청하세요)* +> _(위 이미지를 클릭하여 이 레슨의 비디오를 시청하세요)_ ## 소개 @@ -83,17 +83,17 @@ Copilot 사용을 시작할 때는 [Power Platform Copilot Prompt Library](https 2. 왼쪽 탐색 창에서 **Tables**을 선택한 다음 **Describe the new Table**을 클릭합니다. -3. 홈 화면의 텍스트 영역을 사용하여 구축하려는 앱을 설명합니다. 예를 들어, ***학생 과제를 추적하고 관리하기 위한 앱을 구축하고 싶습니다***. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. +3. 홈 화면의 텍스트 영역을 사용하여 구축하려는 앱을 설명합니다. 예를 들어, **_학생 과제를 추적하고 관리하기 위한 앱을 구축하고 싶습니다_**. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. - ![Describe the app you want to build](../../images/copilot-chat-prompt-powerapps.png?WT.mc_id=academic-105485-koreyst) +![Describe the app you want to build](../../images/copilot-chat-prompt-powerapps.png?WT.mc_id=academic-105485-koreyst) 4. AI Copilot은 데이터베이스 테이블을 제안하며, 추적하려는 데이터를 저장하기 위해 필요한 필드와 일부 샘플 데이터를 제공합니다. 그런 다음 대화식 단계를 통해 테이블을 사용자 정의하여 요구 사항에 맞게 만들 수 있습니다. - > **중요**: Dataverse는 Power Platform의 기반이 되는 데이터 플랫폼입니다. 앱의 데이터를 저장하기 위한 low-code 데이터 플랫폼으로, Microsoft Cloud에 안전하게 데이터를 저장하며 Power Platform 환경 내에서 프로비저닝됩니다. 데이터 분류, 데이터 계보, 세밀한 액세스 제어 등과 같은 내장 데이터 거버넌스 기능을 갖추고 있습니다. Dataverse에 대해 자세히 알아보려면 [여기](https://docs.microsoft.com/powerapps/maker/data-platform/data-platform-intro?WT.mc_id=academic-109639-somelezediko)를 참조하세요. + > **중요**: Dataverse는 Power Platform의 기반이 되는 데이터 플랫폼입니다. 앱의 데이터를 저장하기 위한 low-code 데이터 플랫폼으로, Microsoft Cloud에 안전하게 데이터를 저장하며 Power Platform 환경 내에서 프로비저닝됩니다. 데이터 분류, 데이터 계보, 세밀한 액세스 제어 등과 같은 내장 데이터 거버넌스 기능을 갖추고 있습니다. Dataverse에 대해 자세히 알아보려면 [여기](https://docs.microsoft.com/powerapps/maker/data-platform/data-platform-intro?WT.mc_id=academic-109639-somelezediko)를 참조하세요. ![새로운 테이블에 제안된 필드](../../images/copilot-dataverse-table-powerapps.png?WT.mc_id=academic-105485-koreyst) -5. 교육자들은 과제를 제출한 학생들에게 진행 상황을 알리기 위해 이메일을 보내고 싶어합니다. Copilot을 사용하여 테이블에 학생 이메일을 저장할 새로운 필드를 추가할 수 있습니다. 예를 들어, 다음과 같은 프롬프트를 사용하여 테이블에 새로운 필드를 추가할 수 있습니다: ***학생 이메일을 저장할 열을 추가하고 싶습니다***. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. +5. 교육자들은 과제를 제출한 학생들에게 진행 상황을 알리기 위해 이메일을 보내고 싶어합니다. Copilot을 사용하여 테이블에 학생 이메일을 저장할 새로운 필드를 추가할 수 있습니다. 예를 들어, 다음과 같은 프롬프트를 사용하여 테이블에 새로운 필드를 추가할 수 있습니다: **_학생 이메일을 저장할 열을 추가하고 싶습니다_**. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. ![Adding a new field](../../images/copilot-new-column.png?WT.mc_id=academic-105485-koreyst) @@ -103,7 +103,7 @@ Copilot 사용을 시작할 때는 [Power Platform Copilot Prompt Library](https 8. AI Copilot은 설명에 기반한 반응형 캔버스 앱을 생성하며, 사용자 정의하여 요구 사항에 맞게 만들 수 있습니다. -9. 교육자가 학생들에게 이메일을 보낼 수 있도록 앱에 새로운 화면을 추가할 수 있습니다. 예를 들어, 다음과 같은 프롬프트를 사용하여 앱에 새로운 화면을 추가할 수 있습니다: ***학생들에게 이메일을 보내기 위한 화면을 추가하고 싶습니다***. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. +9. 교육자가 학생들에게 이메일을 보낼 수 있도록 앱에 새로운 화면을 추가할 수 있습니다. 예를 들어, 다음과 같은 프롬프트를 사용하여 앱에 새로운 화면을 추가할 수 있습니다: **_학생들에게 이메일을 보내기 위한 화면을 추가하고 싶습니다_**. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. ![Adding a new screen via a prompt instruction](../../images/copilot-new-screen.png?WT.mc_id=academic-105485-koreyst) @@ -133,7 +133,7 @@ Power Platform에는 Dataverse라는 데이터 플랫폼이 있어 앱과 솔루 이제 Dataverse가 무엇인지 알고 왜 사용해야 하는지 알았으니, AI Copilot을 사용하여 재무팀의 요구 사항을 충족하는 Dataverse 테이블을 생성하는 방법을 살펴보겠습니다. ->**참고**: 이 테이블은 다음 섹션에서 송장 정보를 추출하고 해당 정보를 저장하는 자동화를 구축하는 데 사용됩니다. +> **참고**: 이 테이블은 다음 섹션에서 송장 정보를 추출하고 해당 정보를 저장하는 자동화를 구축하는 데 사용됩니다. Copilot을 사용하여 Dataverse에서 테이블을 생성하려면 다음 단계를 따르세요: @@ -143,7 +143,7 @@ Copilot을 사용하여 Dataverse에서 테이블을 생성하려면 다음 단 ![Select new table](../../images/describe-new-table.png?WT.mc_id=academic-105485-koreyst) -3. **Describe the new Table** 화면에서 테이블을 생성할 내용을 텍스트 영역에 설명합니다. 예를 들어, ***송장 정보를 저장하기 위한 테이블을 생성하고 싶습니다***. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. +3. **Describe the new Table** 화면에서 테이블을 생성할 내용을 텍스트 영역에 설명합니다. 예를 들어, **_송장 정보를 저장하기 위한 테이블을 생성하고 싶습니다_**. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. ![Describe the table](../../images/copilot-chat-prompt-dataverse.png?WT.mc_id=academic-105485-koreyst) @@ -151,7 +151,7 @@ Copilot을 사용하여 Dataverse에서 테이블을 생성하려면 다음 단 ![Suggested Dataverse table](../../images/copilot-dataverse-table.png?WT.mc_id=academic-105485-koreyst) -5. 재무팀은 공급업체에게 송장의 현재 상태를 알리기 위해 이메일을 보내고 싶어합니다. Copilot을 사용하여 테이블에 공급업체 이메일을 저장할 새로운 필드를 추가할 수 있습니다. 예를 들어, 다음과 같은 프롬프트를 사용하여 테이블에 새로운 필드를 추가할 수 있습니다: ***공급업체 이메일을 저장할 열을 추가하고 싶습니다***. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. +5. 재무팀은 공급업체에게 송장의 현재 상태를 알리기 위해 이메일을 보내고 싶어합니다. Copilot을 사용하여 테이블에 공급업체 이메일을 저장할 새로운 필드를 추가할 수 있습니다. 예를 들어, 다음과 같은 프롬프트를 사용하여 테이블에 새로운 필드를 추가할 수 있습니다: **_공급업체 이메일을 저장할 열을 추가하고 싶습니다_**. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. 6. AI Copilot은 새로운 필드를 생성하고, 사용자 정의하여 요구 사항에 맞게 만들 수 있습니다. @@ -188,9 +188,9 @@ AI Builder의 송장 처리 AI 모델을 활용하여 재무팀이 송장을 처 1. [Power Automate](https://make.powerautomate.com?WT.mc_id=academic-105485-koreyst) 홈 화면으로 이동합니다. -2. 홈 화면의 텍스트 영역을 사용하여 구축하려는 워크플로우를 설명합니다. 예를 들어, ***송장이 메일함에 도착했을 때 송장을 처리합니다***. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. +2. 홈 화면의 텍스트 영역을 사용하여 구축하려는 워크플로우를 설명합니다. 예를 들어, **_송장이 메일함에 도착했을 때 송장을 처리합니다_**. **Send** 버튼을 클릭하여 AI Copilot에게 프롬프트를 전송합니다. - ![Copilot power automate](../../images/copilot-chat-prompt-powerautomate.png?WT.mc_id=academic-105485-koreyst) + ![Copilot power automate](../../images/copilot-chat-prompt-powerautomate.png?WT.mc_id=academic-105485-koreyst) 3. AI Copilot은 자동화하려는 작업을 수행하기 위해 필요한 동작을 제안합니다. 다음 단계를 진행하려면 **Next** 버튼을 클릭할 수 있습니다. @@ -204,7 +204,7 @@ AI Builder의 송장 처리 AI 모델을 활용하여 재무팀이 송장을 처 8. 워크플로우에서 **Condition** 동작을 제거합니다. 사용하지 않을 것이기 때문에 제거합니다. 다음과 같이 보일 것입니다: - ![power automate, remove actions](../../images/powerautomate-remove-actions.png?WT.mc_id=academic-105485-koreyst) + ![power automate, remove actions](../../images/powerautomate-remove-actions.png?WT.mc_id=academic-105485-koreyst) 9. **Add an action** 버튼을 클릭하고 **Dataverse**를 검색합니다. **Add a new row** 동작을 선택합니다. diff --git a/10-building-low-code-ai-applications/translations/pt-br/README.md b/10-building-low-code-ai-applications/translations/pt-br/README.md index 00bf87a15..c9da0badb 100644 --- a/10-building-low-code-ai-applications/translations/pt-br/README.md +++ b/10-building-low-code-ai-applications/translations/pt-br/README.md @@ -1,6 +1,6 @@ # Criando Aplication de IA com Low Code -[![Building Low Code AI Applications](../../images/10-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=170c6cb7-3c96-40f2-a354-b6f0ec523de7?WT.mc_id=academic-105485-koreyst) +[![Building Low Code AI Applications](../../images/10-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson10-ght) > _(Clique na imagem acima para ver o vídeo desta lição)_ diff --git a/11-integrating-with-function-calling/README.md b/11-integrating-with-function-calling/README.md index 06e669107..15a24c1b1 100644 --- a/11-integrating-with-function-calling/README.md +++ b/11-integrating-with-function-calling/README.md @@ -1,13 +1,11 @@ # Integrating with function calling -![chapter image](./images/11-lesson-banner.png?WT.mc_id=academic-105485-koreyst) +[![Integrating with function calling](./images/11-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson11-gh) You've learned a fair bit so far in the previous lessons. However, we can improve further. Some things we can address are how we can get a more consistent response format to make it easier to work with the response downstream. Also, we might want to add data from other sources to further enrich our application. The above mentioned problems are what this chapter is looking to address. -> **Video Coming Soon** - ## Introduction This lesson will cover: @@ -145,13 +143,25 @@ Now we can send both requests to the LLM and examine the response we receive by Response 1: ```json - { "name": "Emily Johnson", "major": "computer science", "school": "Duke University", "grades": "3.7", "club": "Chess Club" } + { + "name": "Emily Johnson", + "major": "computer science", + "school": "Duke University", + "grades": "3.7", + "club": "Chess Club" + } ``` Response 2: ```json - { "name": "Michael Lee", "major": "computer science", "school": "Stanford University", "grades": "3.8 GPA", "club": "Robotics Club" } + { + "name": "Michael Lee", + "major": "computer science", + "school": "Stanford University", + "grades": "3.8 GPA", + "club": "Robotics Club" + } ``` Even though the prompts are the same and the descriptions are similar, we see values of the `Grades` property formatted differently as we can sometimes get the format `3.7` or `3.7 GPA` for example. diff --git a/11-integrating-with-function-calling/aoai-assignment.ipynb b/11-integrating-with-function-calling/aoai-assignment.ipynb index dee71b6c9..b7315e397 100644 --- a/11-integrating-with-function-calling/aoai-assignment.ipynb +++ b/11-integrating-with-function-calling/aoai-assignment.ipynb @@ -145,7 +145,18 @@ "cell_type": "code", "execution_count": null, "metadata": {}, - "outputs": [], + "outputs": [ + { + "ename": "", + "evalue": "", + "output_type": "error", + "traceback": [ + "\u001b[1;31mRunning cells with '/opt/homebrew/bin/python3' requires the ipykernel package.\n", + "\u001b[1;31mRun the following command to install 'ipykernel' into the Python environment. \n", + "\u001b[1;31mCommand: '/opt/homebrew/bin/python3 -m pip install ipykernel -U --user --force-reinstall'" + ] + } + ], "source": [ "import os\n", "import json\n", @@ -596,7 +607,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.10.8" + "version": "3.12.2" }, "orig_nbformat": 4 }, diff --git a/11-integrating-with-function-calling/images/11-lesson-banner.png b/11-integrating-with-function-calling/images/11-lesson-banner.png index 5663bf252..8304f621a 100644 Binary files a/11-integrating-with-function-calling/images/11-lesson-banner.png and b/11-integrating-with-function-calling/images/11-lesson-banner.png differ diff --git a/11-integrating-with-function-calling/translations/cn/README.md b/11-integrating-with-function-calling/translations/cn/README.md index 76745ec11..5c50d94e4 100644 --- a/11-integrating-with-function-calling/translations/cn/README.md +++ b/11-integrating-with-function-calling/translations/cn/README.md @@ -1,13 +1,11 @@ # 第十一章:为生成式 AI 添加 function calling -![chapter image](../../images/11-lesson-banner.png?WT.mc_id=academic-105485-koreyst) +[![Integrating with function calling](../../images/11-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson11-gh) 到目前为止,您在之前的章节中已经学到了相当多的知识。 然而,我们可以进一步改进。 可以解决的一些问题是如何获得更一致的响应格式,以便更轻松地处理下游响应。 此外,我们可能希望添加来自其他来源的数据以进一步丰富我们的应用程序。 上述问题正是本章要解决的问题。 -> **导学视频敬请期待** - ## 本章概述 在本章中,您将学习到: diff --git a/11-integrating-with-function-calling/translations/ja-jp/README.md b/11-integrating-with-function-calling/translations/ja-jp/README.md index e867e4da1..c6b798ad5 100644 --- a/11-integrating-with-function-calling/translations/ja-jp/README.md +++ b/11-integrating-with-function-calling/translations/ja-jp/README.md @@ -1,13 +1,11 @@ # Function Calling との統合 -![chapter image](../../images/11-lesson-banner.png?WT.mc_id=academic-105485-yoterada) +[![Integrating with function calling](../../images/11-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson11-gh) これまでのレッスンでかなり多くの内容を学びました。しかし、私たちはさらに成長できます。取り組むべき課題の一つは、一貫性のある回答フォーマットの作成です。回答フォーマットが一貫すると後続の処理はスムーズに進められます。また、他のデータ・ソースからデータを追加し、アプリケーションをさらに拡張できます。 上記の問題を、この章で取り扱います。 -> **ビデオは近日公開予定** - ## はじめに このレッスンでは、下記の内容について説明します。 @@ -47,7 +45,7 @@ ## シナリオを通じた問題の説明 -> *Notebook.ipynb* というファイルを作成し、下記のコードをコピー&ペーストしてください。仮に下記のシナリオを実行したい場合は、別のコードセルへの貼り付けをお勧めします。また、下記に記述する関数が、実際の問題に対処するための説明も行っているので、あわせて記述内容をご覧ください。 +> _Notebook.ipynb_ というファイルを作成し、下記のコードをコピー&ペーストしてください。仮に下記のシナリオを実行したい場合は、別のコードセルへの貼り付けをお勧めします。また、下記に記述する関数が、実際の問題に対処するための説明も行っているので、あわせて記述内容をご覧ください。 「一貫した回答フォーマットの取得」に関する問題の例を見てみましょう: @@ -61,7 +59,7 @@ import json from openai import AzureOpenAI from dotenv import load_dotenv load_dotenv() - + client = AzureOpenAI( api_key=os.environ['AZURE_OPENAI_KEY'], # これもデフォルトで省略できます api_version = "2023-07-01-preview" @@ -70,9 +68,9 @@ api_version = "2023-07-01-preview" deployment=os.environ['AZURE_OPENAI_DEPLOYMENT'] ``` -上記は、Azure Open AI への接続するための Python コードで、ここでは `api_version`、`api_key`を設定します。 +上記は、Azure Open AI への接続するための  Python  コードで、ここでは `api_version`、`api_key`を設定します。 -1. `student_1_description`と`student_2_description`という変数を使用して、2人の学生の説明を記述します。 +1. `student_1_description`と`student_2_description`という変数を使用して、2 人の学生の説明を記述します。 ```python student_1_description= f'''Emily Johnson は、Duke University の @@ -96,32 +94,32 @@ Michael はプログラミングが得意と知られており、大学のロボ ```python prompt1 = f''' 以下の情報を指定されたテキストから抽出し、それをJSONオブジェクトとして返してください: - + 名前 専攻 学校 成績 クラブ - + 情報を抽出するためのテキスト本文は以下の通りです: {student_1_description} ''' - + prompt2 = f''' 以下の情報を指定されたテキストから抽出し、それをJSONオブジェクトとして返してください: - + 名前 専攻 学校 成績 クラブ - + 情報を抽出するためのテキスト本文は以下の通りです: {student_2_description} ''' ``` - 上記のプロンプトは、LLM に情報を抽出し、応答を JSON 形式で返すように指示しています。 +上記のプロンプトは、LLM に情報を抽出し、応答を JSON 形式で返すように指示しています。 1. プロンプトと Azure Open AI の接続設定を行った後、`openai.ChatCompletion`を使用してプロンプトを LLM に送信します。プロンプトは `messages` 変数に格納し、ロールを `user` に設定します。これはチャット・ボットに対して、利用者からメッセージが書き込まれる様子を模倣するために記載しています。 @@ -155,23 +153,23 @@ json_response1 ```json { - "name": "Emily Johnson", - "major": "コンピューターサイエンス", - "school": "Duke University", - "grades": "3.7", - "club": "チェス・クラブ" + "name": "Emily Johnson", + "major": "コンピューターサイエンス", + "school": "Duke University", + "grades": "3.7", + "club": "チェス・クラブ" } ``` 応答 2: ```json -{ - "name": "Michael Lee", - "major": "コンピューターサイエンス", - "school": "Stanford University", - "grades": "3.8 GPA", - "club": "ロボティクス・クラブ" +{ + "name": "Michael Lee", + "major": "コンピューターサイエンス", + "school": "Stanford University", + "grades": "3.8 GPA", + "club": "ロボティクス・クラブ" } ``` @@ -191,21 +189,21 @@ json_response1 - **外部ツールの呼び出し**:チャット・ボットは利用者からの質問に回答するのが得意です。関数呼び出しを使用すると、チャット・ボットは利用者からのメッセージを使用して、特定のタスクを完了できます。例えば、学生はチャットボットに「この科目についてさらに支援が必要というメールを、教員に送信してください」と依頼できます。これにより、`send_email(to: string, body: string)`という関数呼び出しを行います。 -- **API またはデータベースクエリの作成**:利用者は、書式設定された問い合わせ、または API 要求に変換される自然言語を使用して、情報を検索できます。例えば、教師が「最後の課題を完了した生徒は誰ですか」と要求すると、`get_completed(student_name: string, assignment: int, current_status: string)`という関数を呼び出します。 +- **API  またはデータベースクエリの作成**:利用者は、書式設定された問い合わせ、または API 要求に変換される自然言語を使用して、情報を検索できます。例えば、教師が「最後の課題を完了した生徒は誰ですか」と要求すると、`get_completed(student_name: string, assignment: int, current_status: string)`という関数を呼び出します。 - **構造化データの作成**:利用者は、テキストまたは CSV フォーマットのデータを取得し、LLM を使用して、そこから重要な情報を抽出できます。例えば学生は、和平合意に関するウィキペディアの記事を変換して、AI フラッシュカードを作成できます。これは、`get_important_facts(agreement_name: string, date_signed: string, parties_involved: list)`という関数を使用して行います。 ## 最初の関数呼び出しの作成 -関数呼び出しを作成するプロセスは、以下の3つの主要なステップから構成されています。 +関数呼び出しを作成するプロセスは、以下の 3 つの主要なステップから構成されています。 -1. **呼び出し**:関数リストとユーザー・メッセージを用いて、Chat Completions API を呼び出します。 -2. **読み取り**:モデルからの回答を読み取り、アクションを実行します。つまり、関数を実行したり、API 呼び出しを行ったりします。 +1. **呼び出し**:関数リストとユーザー・メッセージを用いて、Chat Completions API を呼び出します。 +2. **読み取り**:モデルからの回答を読み取り、アクションを実行します。つまり、関数を実行したり、API 呼び出しを行ったりします。 3. **再呼び出し**:関数からの返却値を用いて、Chat Completions API を再度呼び出し、その情報を使用して利用者に対する回答を作成します。 ![LLM Flow](../../images/LLM-Flow.png?WT.mc_id=academic-105485-yoterada) -### ステップ1 - メッセージの作成 +### ステップ 1 - メッセージの作成 最初のステップで、ユーザー・メッセージを作成します。これは、テキストの入力値を取得して動的に割り当てるか、もしくはここで直接値を割り当てできます。仮に Chat Completions API を初めて使用するの場合は、メッセージの `role` と `content` を定義してください。 @@ -217,9 +215,9 @@ messages= [ {"role": "user", "content": "初心者の学生が Azure を学ぶ 異なる役割を割り当てると、LLM は、システムが言っているのか、それとも利用者が言っているのかが明確になり、LLM は会話履歴を構築するのに役立ちます。 -### ステップ2 - 関数の作成 +### ステップ 2 - 関数の作成 -次に、関数とその関数のパラメータを定義します。ここでは `search_courses` という1つの関数のみを使用しますが、複数の関数も作れます。 +次に、関数とその関数のパラメータを定義します。ここでは `search_courses` という 1 つの関数のみを使用しますが、複数の関数も作れます。 > **重要** : 関数は LLM のシステム・メッセージに含まれており、利用可能なトークンの数に含まれます。 @@ -259,15 +257,15 @@ functions = [ - `name` - 呼び出したい関数名 - `description` - 関数がどのように動作するかの説明。ここは具体的で明確な説明の記述が必要 - `parameters` - モデルによって回答で生成する値とフォーマットのリスト。`parameters` 配列として構成し、次のプロパティを含む - 1. `type` - プロパティのデータ型 - 1. `properties` - 回答に使用する特定の値のリスト + 1. `type` - プロパティのデータ型 + 1. `properties` - 回答に使用する特定の値のリスト 1. `name` - フォーマットされた回答で使用するプロパティ名。例えば、`product` 1. `type` - プロパティのデータ型。例えば、`string` 1. `description` - 特定のプロパティの説明 また、オプションのプロパティとして `required`もあります。これは関数呼び出しが必須かを指定するプロパティです。 -### ステップ3 - 関数呼び出しの実行 +### ステップ 3 - 関数呼び出しの実行 関数を定義した後、次に Chat Completion API の呼び出しにその関数を含める必要があります。これを行うには、リクエストに `functions` を追加します。この場合、`functions=functions`とします。 diff --git a/11-integrating-with-function-calling/translations/ko/README.md b/11-integrating-with-function-calling/translations/ko/README.md index e30688d52..1f35c827c 100644 --- a/11-integrating-with-function-calling/translations/ko/README.md +++ b/11-integrating-with-function-calling/translations/ko/README.md @@ -1,15 +1,11 @@ # Function Calling과 통합하기 -![chapter image](../../images/11-lesson-banner.png?WT.mc_id=academic-105485-koreyst) - -> **비디오 공개 예정** +[![Integrating with function calling](../../images/11-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson11-gh) 지금까지 이전 레슨에서 많은 것을 배웠습니다. 그러나 더 나아갈 수 있습니다. 우리가 해결할 수 있는 몇 가지 문제는 응답 형식을 더 일관되게 만들어 응답을 더 쉽게 처리할 수 있도록 하는 것이며, 또한 응용 프로그램을 더 풍부하게 만들기 위해 다른 소스에서 데이터를 추가할 수도 있습니다. 위에서 언급한 문제들은 이번 챕터에서 다루고자 하는 내용입니다. - - ## 소개 이 레슨에서는 다음을 다룹니다: @@ -147,18 +143,30 @@ function calling은 다음과 같은 제한 사항을 극복하기 위한 Azure 응답 1: ```json - { "이름": "Emily Johnson", "전공": "컴퓨터 공학", "학교": "Duke 대학교", "성적": "3.7", "동아리": "체스 동아리" } + { + "이름": "Emily Johnson", + "전공": "컴퓨터 공학", + "학교": "Duke 대학교", + "성적": "3.7", + "동아리": "체스 동아리" + } ``` 응답 2: ```json - { "이름": "Michael Lee", "전공": "컴퓨터 공학", "학교": "Stanford 대학교", "성적": "3.8 GPA", "동아리": "로봇 공학 동아리" } + { + "이름": "Michael Lee", + "전공": "컴퓨터 공학", + "학교": "Stanford 대학교", + "성적": "3.8 GPA", + "동아리": "로봇 공학 동아리" + } ``` - 프롬프트는 동일하고 설명은 유사하지만, `Grades` 속성의 값은 때로는 `3.7` 또는 `3.7 GPA`와 같이 서로 다른 형식으로 포맷되는 것을 볼 수 있습니다. + 프롬프트는 동일하고 설명은 유사하지만, `Grades` 속성의 값은 때로는 `3.7` 또는 `3.7 GPA`와 같이 서로 다른 형식으로 포맷되는 것을 볼 수 있습니다. - 이 결과는 LLM이 쓰인 프롬프트의 구조화되지 않은 (unstructured) 데이터를 받아들이고 구조화되지 않은 (unstructured) 데이터를 반환하기 때문입니다. 이 데이터를 저장하거나 사용할 때 어떤 형식을 기대해야 하는지 알기 위해 구조화된 (structured) 형식이 필요합니다. + 이 결과는 LLM이 쓰인 프롬프트의 구조화되지 않은 (unstructured) 데이터를 받아들이고 구조화되지 않은 (unstructured) 데이터를 반환하기 때문입니다. 이 데이터를 저장하거나 사용할 때 어떤 형식을 기대해야 하는지 알기 위해 구조화된 (structured) 형식이 필요합니다. 그렇다면 포맷팅 문제를 어떻게 해결할까요? functional calling을 사용하여 구조화된 데이터를 받을 수 있도록 할 수 있습니다. function calling을 사용할 때, LLM은 실제로 함수를 호출하거나 실행하지 않습니다. 대신, LLM에게 응답을 따르기 위한 구조를 만듭니다. 그런 다음, 우리는 응답을 사용하여 응용 프로그램에서 어떤 함수를 실행할지 알 수 있습니다. @@ -240,11 +248,11 @@ functions = [ - `name` - 호출하려는 함수의 이름입니다. - `description` - 함수가 작동하는 방식에 대한 설명입니다. 여기서는 구체적이고 명확하게 작성하는 것이 중요합니다. - `parameters` - 모델이 응답에서 생성할 값과 형식의 목록입니다. 매개변수 배열은 다음 속성을 가진 항목으로 구성됩니다: - 1. `type` - 속성의 데이터 유형이 저장됩니다. - 1. `properties` - 모델이 응답에 사용할 구체적인 값의 목록입니다. - 1. `name` - 모델이 형식화된 응답에서 사용할 속성의 이름입니다. 예를 들어, `product`입니다. - 1. `type` - 이 속성의 데이터 유형입니다. 예를 들어, `string`입니다. - 1. `description` - 특정 속성에 대한 설명입니다. + 1. `type` - 속성의 데이터 유형이 저장됩니다. + 1. `properties` - 모델이 응답에 사용할 구체적인 값의 목록입니다. + 1. `name` - 모델이 형식화된 응답에서 사용할 속성의 이름입니다. 예를 들어, `product`입니다. + 1. `type` - 이 속성의 데이터 유형입니다. 예를 들어, `string`입니다. + 1. `description` - 특정 속성에 대한 설명입니다. function call이 완료되기 위해 선택적으로 `required` 속성도 있습니다. diff --git a/11-integrating-with-function-calling/translations/pt-br/README.md b/11-integrating-with-function-calling/translations/pt-br/README.md index 7943cd82c..03128b268 100644 --- a/11-integrating-with-function-calling/translations/pt-br/README.md +++ b/11-integrating-with-function-calling/translations/pt-br/README.md @@ -1,13 +1,11 @@ # Integrando com chamadas de função -![chapter image](../../images/11-lesson-banner.png?WT.mc_id=academic-105485-koreyst) +[![Integrating with function calling](../../images/11-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson11-gh) Você aprendeu bastante até agora nas lições anteriores. No entanto, podemos melhorar ainda mais. Algumas coisas que podemos abordar são como podemos obter um formato de resposta mais consistente para facilitar o trabalho com a resposta a jusante. Além disso, podemos querer adicionar dados de outras fontes para enriquecer ainda mais nossa aplicação. Os problemas mencionados acima são o que este capítulo pretende abordar. -> **Vídeo em Breve** - ## Introdução Esta lição abordará: @@ -47,7 +45,7 @@ A Chamada de Função é um recurso do Serviço Azure Open AI para superar as se ## Ilustrando o problema por meio de um cenário -> Recomendamos que você crie um arquivo *Notebook.ipynb* e cole o código abaixo em células de código separadas se quiser executar o cenário abaixo. Você também pode apenas ler enquanto tentamos ilustrar um problema em que as funções podem ajudar a resolver o problema. +> Recomendamos que você crie um arquivo _Notebook.ipynb_ e cole o código abaixo em células de código separadas se quiser executar o cenário abaixo. Você também pode apenas ler enquanto tentamos ilustrar um problema em que as funções podem ajudar a resolver o problema. Vamos dar uma olhada no exemplo que ilustra o problema do formato de resposta: @@ -71,7 +69,7 @@ Digamos que queremos criar um banco de dados de dados de estudantes para que pos ```python student_1_description="Emily Johnson is a sophomore majoring in computer science at Duke University. She has a 3.7 GPA. Emily is an active member of the university's Chess Club and Debate Team. She hopes to pursue a career in software engineering after graduating." - + student_2_description = "Michael Lee is a sophomore majoring in computer science at Stanford University. He has a 3.8 GPA. Michael is known for his programming skills and is an active member of the university's Robotics Club. He hopes to pursue a career in artificial intelligence after finishing his studies." ``` @@ -114,17 +112,17 @@ Digamos que queremos criar um banco de dados de dados de estudantes para que pos ```python # response from prompt one openai_response1 = openai.ChatCompletion.create( - engine="gpt-function", + engine="gpt-function", messages = [{'role': 'user', 'content': prompt1}] ) - openai_response1['choices'][0]['message']['content'] + openai_response1['choices'][0]['message']['content'] # response from prompt two openai_response2 = openai.ChatCompletion.create( engine="gpt-function", messages = [{'role': 'user', 'content': prompt2 }] ) - openai_response2['choices'][0]['message']['content'] + openai_response2['choices'][0]['message']['content'] ``` Agora nós podemos enviar ambas as solicitações para o LLM e examinar a resposta que recebemos encontrando-a assim `openai_response1['choices'][0]['message']['content']`. @@ -140,21 +138,25 @@ Agora nós podemos enviar ambas as solicitações para o LLM e examinar a respos Resposta 1: ```json - {'name': 'Emily Johnson', - 'major': 'computer science', - 'school': 'Duke University', - 'grades': '3.7', - 'club': 'Chess Club'} + { + "name": "Emily Johnson", + "major": "computer science", + "school": "Duke University", + "grades": "3.7", + "club": "Chess Club" + } ``` Resposta 2: ```json - {'name': 'Michael Lee', - 'major': 'computer science', - 'school': 'Stanford University', - 'grades': '3.8 GPA', - 'club': 'Robotics Club'} + { + "name": "Michael Lee", + "major": "computer science", + "school": "Stanford University", + "grades": "3.8 GPA", + "club": "Robotics Club" + } ``` Embora os prompts sejam os mesmos e as descrições sejam semelhantes, vemos que os valores da propriedade `Grades` são formatados de maneira diferente, como `3.7` ou `3.7 GPA`, por exemplo. @@ -241,8 +243,8 @@ Vamos descrever cada instância de função mais detalhadamente abaixo: - `name` - O nome da função que queremos que seja chamada. - `description` - Esta é a descrição de como a função funciona. Aqui é importante ser específico e claro. - `parameters` - Uma lista de valores e formatos que você deseja que o modelo produza em sua resposta. A matriz de parâmetros consiste em itens, onde cada item tem as seguintes propriedades: - 1. `type` - O tipo de dados no qual as propriedades serão armazenadas. - 1. `properties` - Lista dos valores específicos que o modelo usará para sua resposta + 1. `type` - O tipo de dados no qual as propriedades serão armazenadas. + 1. `properties` - Lista dos valores específicos que o modelo usará para sua resposta 1. `name` - A chave é o nome da propriedade que o modelo usará em sua resposta formatada, por exemplo, `product`. 1. `type` - O tipo de dados desta propriedade, por exemplo, `string`. 1. `description` - Descrição da propriedade específica. @@ -258,10 +260,10 @@ Também há a opção de definir `function_call` como `auto`. Isso significa que Aqui está algum código abaixo onde chamamos `ChatCompletion.create`, observe como definimos `functions=functions` e `function_call="auto"`, dando assim ao LLM a escolha de quando chamar as funções que fornecemos: ```python -response = openai.ChatCompletion.create( engine="gpt-function", - messages=messages, - functions=functions, - function_call="auto", ) +response = openai.ChatCompletion.create( engine="gpt-function", + messages=messages, + functions=functions, + function_call="auto", ) print(response['choices'][0]['message']) ``` @@ -330,7 +332,7 @@ Para integrar isso ao nosso aplicativo, siga estas etapas: Observe como agora criamos uma função Python real que mapeia para os nomes de função introduzidos na variável `functions`. Também estamos fazendo chamadas reais de API externa para buscar os dados de que precisamos. Neste caso, vamos contra a API Microsoft Learn para pesquisar módulos de treinamento. - Ok! Então criamos variáveis `functions` e uma função Python correspondente, como dizemos ao LLM como mapear essas duas coisas para que nossa função Python seja chamada? +Ok! Então criamos variáveis `functions` e uma função Python correspondente, como dizemos ao LLM como mapear essas duas coisas para que nossa função Python seja chamada? 1. Para ver se precisamos chamar uma função Python, precisamos olhar para a resposta LLM e ver se `function_call` faz parte dela e chamar a função apontada. Veja como você pode fazer a verificação mencionada abaixo: @@ -341,13 +343,13 @@ Para integrar isso ao nosso aplicativo, siga estas etapas: print(response_message.get("function_call")) print() - # Call the function. + # Call the function. function_name = response_message["function_call"]["name"] available_functions = { "search_courses": search_courses, } - function_to_call = available_functions[function_name] + function_to_call = available_functions[function_name] function_args = json.loads(response_message["function_call"]["arguments"]) function_response = function_to_call(**function_args) @@ -380,10 +382,10 @@ Para integrar isso ao nosso aplicativo, siga estas etapas: Essas três linhas garantem que extraímos o nome da função, os argumentos e fazemos a chamada: ```python - function_to_call = available_functions[function_name] + function_to_call = available_functions[function_name] function_args = json.loads(response_message["function_call"]["arguments"]) - function_response = function_to_call(**function_args) + function_response = function_to_call(**function_args) ``` Acima está a saída da execução do nosso código: @@ -397,14 +399,14 @@ Para integrar isso ao nosso aplicativo, siga estas etapas: } Output of function call: - [{'title': 'Describe concepts of cryptography', 'url': 'https://learn.microsoft.com/training/modules/describe-concepts-of-cryptography/? - WT.mc_id=api_CatalogApi'}, {'title': 'Introduction to audio classification with TensorFlow', 'url': 'https://learn.microsoft.com/en- - us/training/modules/intro-audio-classification-tensorflow/?WT.mc_id=api_CatalogApi'}, {'title': 'Design a Performant Data Model in Azure SQL - Database with Azure Data Studio', 'url': 'https://learn.microsoft.com/training/modules/design-a-data-model-with-ads/? - WT.mc_id=api_CatalogApi'}, {'title': 'Getting started with the Microsoft Cloud Adoption Framework for Azure', 'url': - 'https://learn.microsoft.com/training/modules/cloud-adoption-framework-getting-started/?WT.mc_id=api_CatalogApi'}, {'title': 'Set up the + [{'title': 'Describe concepts of cryptography', 'url': 'https://learn.microsoft.com/training/modules/describe-concepts-of-cryptography/? + WT.mc_id=api_CatalogApi'}, {'title': 'Introduction to audio classification with TensorFlow', 'url': 'https://learn.microsoft.com/en- + us/training/modules/intro-audio-classification-tensorflow/?WT.mc_id=api_CatalogApi'}, {'title': 'Design a Performant Data Model in Azure SQL + Database with Azure Data Studio', 'url': 'https://learn.microsoft.com/training/modules/design-a-data-model-with-ads/? + WT.mc_id=api_CatalogApi'}, {'title': 'Getting started with the Microsoft Cloud Adoption Framework for Azure', 'url': + 'https://learn.microsoft.com/training/modules/cloud-adoption-framework-getting-started/?WT.mc_id=api_CatalogApi'}, {'title': 'Set up the Rust development environment', 'url': 'https://learn.microsoft.com/training/modules/rust-set-up-environment/?WT.mc_id=api_CatalogApi'}] - + ``` 1. Agora enviaremos a mensagem atualizada, `messages` para o LLM para que possamos receber uma resposta em linguagem natural em vez de uma resposta formatada em JSON da API. diff --git a/12-designing-ux-for-ai-applications/README.md b/12-designing-ux-for-ai-applications/README.md index b2f0b0757..141813e34 100644 --- a/12-designing-ux-for-ai-applications/README.md +++ b/12-designing-ux-for-ai-applications/README.md @@ -1,6 +1,6 @@ # Designing UX for AI Applications -[![Designing UX for AI Applications](./images/12-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=1464ef7a-d974-4a04-9ce3-1bc5b3087b4b?WT.mc_id=academic-105485-koreyst) +[![Designing UX for AI Applications](./images/12-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson12-gh) > _(Click the image above to view video of this lesson)_ diff --git a/12-designing-ux-for-ai-applications/images/12-lesson-banner.png b/12-designing-ux-for-ai-applications/images/12-lesson-banner.png index 5be310f21..fece9fc47 100644 Binary files a/12-designing-ux-for-ai-applications/images/12-lesson-banner.png and b/12-designing-ux-for-ai-applications/images/12-lesson-banner.png differ diff --git a/12-designing-ux-for-ai-applications/translations/cn/README.md b/12-designing-ux-for-ai-applications/translations/cn/README.md index f28b82d56..1f253b49a 100644 --- a/12-designing-ux-for-ai-applications/translations/cn/README.md +++ b/12-designing-ux-for-ai-applications/translations/cn/README.md @@ -1,6 +1,6 @@ # 第十二章:为人工智能应用程序添加用户体验 -[![Designing UX for AI Applications](../../images/12-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=1464ef7a-d974-4a04-9ce3-1bc5b3087b4b?WT.mc_id=academic-105485-koreyst) +[![Designing UX for AI Applications](../../images/12-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson12-gh) _(点击该图片看本章导学视频)_ diff --git a/12-designing-ux-for-ai-applications/translations/ja-jp/README.md b/12-designing-ux-for-ai-applications/translations/ja-jp/README.md index 07dc7e717..5b79fc3bb 100644 --- a/12-designing-ux-for-ai-applications/translations/ja-jp/README.md +++ b/12-designing-ux-for-ai-applications/translations/ja-jp/README.md @@ -1,6 +1,6 @@ # AI アプリケーションの UX 設計 -[![Designing UX for AI Applications](../../images/12-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=1464ef7a-d974-4a04-9ce3-1bc5b3087b4b?WT.mc_id=academic-105485-yoterada) +[![Designing UX for AI Applications](../../images/12-lesson-banner.png?WT.mc_id=academic-105485-yoterada)](https://aka.ms/gen-ai-lesson12-gh) > _(上の画像をクリックすると、このレッスンのビデオが表示されます)_ diff --git a/12-designing-ux-for-ai-applications/translations/ko/README.md b/12-designing-ux-for-ai-applications/translations/ko/README.md index e84e93f5a..270bf583b 100644 --- a/12-designing-ux-for-ai-applications/translations/ko/README.md +++ b/12-designing-ux-for-ai-applications/translations/ko/README.md @@ -1,8 +1,8 @@ # AI 애플리케이션을 위한 사용자 경험(ux) 디자인하기 -[![Designing UX for AI Applications](../../images/12-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://youtu.be/bO7h2_hOhR0?WT.mc_id=academic-105485-koreyst) +[![Designing UX for AI Applications](../../images/12-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson12-gh) -> *(이미지를 클릭하면 이 수업의 비디오를 볼 수 있습니다)* +> _(이미지를 클릭하면 이 수업의 비디오를 볼 수 있습니다)_ 사용자 경험은 앱을 개발하는 데 있어 매우 중요한 부분입니다. 사용자들은 작업을 효율적으로 수행할 수 있어야 합니다. 그리고 효율적으로 사용하는 것도 중요하지만 누구나 사용할 수 있도록 앱을 디자인하는 것도 중요합니다. 이 장에서는 이러한 영역에 중점을 두어 사람들이 사용할 수 있고, 사용하고 싶어하는 앱을 디자인할 수 있도록 하는 부분들을 다룰 것입니다. @@ -12,16 +12,16 @@ 이 수업에서는 다음의 영역들을 다룹니다: -* 사용자 경험 소개 및 사용자 요구 이해 -* 신뢰와 투명성을 위한 AI 애플리케이션 디자인 -* 협력과 피드백을 위한 AI 애플리케이션 디자인 - +- 사용자 경험 소개 및 사용자 요구 이해 +- 신뢰와 투명성을 위한 AI 애플리케이션 디자인 +- 협력과 피드백을 위한 AI 애플리케이션 디자인 + ## 학습 목표 이 수업을 마친 후에는 다음을 할 수 있을 것입니다: -* 사용자 요구를 충족시키는 AI 애플리케이션을 구축하는 방법에 대한 이해 -* 신뢰와 협력을 촉진하는 AI 애플리케이션 디자인 +- 사용자 요구를 충족시키는 AI 애플리케이션을 구축하는 방법에 대한 이해 +- 신뢰와 협력을 촉진하는 AI 애플리케이션 디자인 ### 전제 조건 @@ -61,7 +61,6 @@ ### 설명가능성 - AI가 미래 세대에 지식을 전달하는 것과 같이 결정에 도움이 되는 경우, 교사와 부모가 AI 결정이 어떻게 이루어지는지 이해하는 것이 중요합니다. AI 애플리케이션이 결정을 내리는 방식을 이해하는 것이 설명가능성입니다. 설명가능성을 위한 디자인에는 AI 애플리케이션이 수행할 수 있는 예제의 세부 정보를 추가하는 것이 포함됩니다. 예를 들어, "AI 교사로 시작하기" 대신에 "AI를 사용하여 노트를 요약하여 쉬운 복습을 도와보세요"와 같이 시스템이 구체적인 예시를 제공할 수 있습니다. ![an app landing page with clear illustration of explainability in AI applications](../../images/explanability-in-ai.png?WT.mc_id=academic-105485-koreyst) @@ -102,16 +101,15 @@ AI 애플리케이션은 완벽하지 않기 때문에 오류가 발생할 수 ## 과제 - 당신이 만든 AI 앱들 중에 어떠한 것이든 골라 밑의 단계들을 당신의 앱에 구현해보는 것을 고려해보세요: -* **즐거움:** 앱을 어떻게 더 즐겁게 만들 수 있는지 고려하세요. 설명을 어디에 추가하고 있는지, 사용자의 탐험을 유도하고 있는지 확인하세요. 에러 메시지를 어떻게 구성하고 있는지도 고려해보세요. +- **즐거움:** 앱을 어떻게 더 즐겁게 만들 수 있는지 고려하세요. 설명을 어디에 추가하고 있는지, 사용자의 탐험을 유도하고 있는지 확인하세요. 에러 메시지를 어떻게 구성하고 있는지도 고려해보세요. -* **사용성:** 웹 앱을 개발 중이라면, 앱이 마우스와 키보드 둘다를 가지고 탐험할 수 있도록 보장하세요. +- **사용성:** 웹 앱을 개발 중이라면, 앱이 마우스와 키보드 둘다를 가지고 탐험할 수 있도록 보장하세요. -* **신뢰와 투명성:** AI의 출력물을 완전히 신뢰하지 말고, 출력물을 검증하기 위해 인간을 프로세스에 추가하는 방법을 고려하세요. 또한, 신뢰성과 투명성을 달성하기 위한 다른 방법을 고려하고 구현하세요. +- **신뢰와 투명성:** AI의 출력물을 완전히 신뢰하지 말고, 출력물을 검증하기 위해 인간을 프로세스에 추가하는 방법을 고려하세요. 또한, 신뢰성과 투명성을 달성하기 위한 다른 방법을 고려하고 구현하세요. -* **제어:** 사용자에게 어플리케이션에 제공하는 데이터를 통제할 수 있는 권한을 부여하세요. 사용자가 AI 어플리케이션의 데이터 수집에 동의하거나 동의 철회할 수 있는 방법을 구현하세요. +- **제어:** 사용자에게 어플리케이션에 제공하는 데이터를 통제할 수 있는 권한을 부여하세요. 사용자가 AI 어플리케이션의 데이터 수집에 동의하거나 동의 철회할 수 있는 방법을 구현하세요. @@ -119,4 +117,4 @@ AI 애플리케이션은 완벽하지 않기 때문에 오류가 발생할 수 이 수업이 끝났으니 우리의 [Generative AI 학습 컬렉션](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) 수업을 들어, 생성형 AI에 관한 지식을 계속해서 쌓아보세요! -축하합니다, 이번 코스를 완료하였습니다! 그러나 여기서 멈추면 안됩니다. 바라건대, 당신이 당신만의 생성형 AI 스타트업을 만드는 것에 영감을 얻었으면 좋겠습니다. 여기 [Microsoft Founders Hub](https://aka.ms/genai-foundershub?WT.mc_id=academic-105485-koreyst)로 이동하여 당신의 여정에 도움을 주기 위한 프로그램에 신청해보세요. +축하합니다, 이번 코스를 완료하였습니다! 그러나 여기서 멈추면 안됩니다. 바라건대, 당신이 당신만의 생성형 AI 스타트업을 만드는 것에 영감을 얻었으면 좋겠습니다. 여기 [Microsoft Founders Hub](https://aka.ms/genai-foundershub?WT.mc_id=academic-105485-koreyst)로 이동하여 당신의 여정에 도움을 주기 위한 프로그램에 신청해보세요. diff --git a/12-designing-ux-for-ai-applications/translations/pt-br/README.md b/12-designing-ux-for-ai-applications/translations/pt-br/README.md index 70d949c6a..8f5ae857f 100644 --- a/12-designing-ux-for-ai-applications/translations/pt-br/README.md +++ b/12-designing-ux-for-ai-applications/translations/pt-br/README.md @@ -1,6 +1,6 @@ # Projetando UX para aplicativos de IA -[![Designing UX for AI Applications](../../images/12-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://learn.microsoft.com/_themes/docs.theme/master/en-us/_themes/global/video-embed.html?id=1464ef7a-d974-4a04-9ce3-1bc5b3087b4b?WT.mc_id=academic-105485-koreyst) +[![Designing UX for AI Applications](../../images/12-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson12-gh) > _(Clique na imagem acima para assistir ao vídeo desta lição)_ diff --git a/13-continued-learning/translations/ko/README.md b/13-continued-learning/translations/ko/README.md deleted file mode 100644 index 54f6a0c09..000000000 --- a/13-continued-learning/translations/ko/README.md +++ /dev/null @@ -1,135 +0,0 @@ -# 추가 자료 - -다음은 Generative AI 학습 및 구축을 계속하기 위한 다른 훌륭한 자료에 대한 링크입니다. - -빠진 좋은 자료가 있나요? PR을 제출하여 알려주세요! - -## 🧠 학습 컬렉션 - -이 강좌를 완료한 후, [Generative AI 학습 컬렉션](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst)을 확인하여 Generative AI 지식을 더욱 향상시킬 수 있습니다! - -## Lesson 1 - 생성형 AI와 LLM 소개 - -🔗 [How GPT models work: accessible to everyone](https://bea.stollnitz.com/blog/how-gpt-works/?WT.mc_id=academic-105485-koreyst) - -🔗 [Fundamentals of Generative AI](https://learn.microsoft.com/training/modules/fundamentals-generative-ai?&WT.mc_id=academic-105485-koreyst) - -🔗 [How GPT models work: accessible to everyone](https://bea.stollnitz.com/blog/how-gpt-works?WT.mc_id=academic-105485-koreyst) - -🔗 [Generative AI: Implication and Applications for Education](https://arxiv.org/abs/2305.07605?wt.mc_id=github_S-1231_webpage_reactor) - -## Lesson 2 - 다양한 LLM 탐색 및 비교 - -🔗 [How to use Open Source foundation models curated by Azure Machine Learning (preview) - Azure Machine Learning | Microsoft Learn](https://learn.microsoft.com/azure/machine-learning/how-to-use-foundation-models?WT.mc_id=academic-105485-koreyst) - -🔗 [The Large Language Model (LLM) Index | Sapling](https://sapling.ai/llm/index?WT.mc_id=academic-105485-koreyst) - -🔗 [[2304.04052] Decoder-Only or Encoder-Decoder? Interpreting Language Model as a Regularized Encoder-Decoder (arxiv.org)](https://arxiv.org/abs/2304.04052?WT.mc_id=academic-105485-koreyst) - -🔗 [Retrieval Augmented Generation using Azure Machine Learning prompt flow](https://learn.microsoft.com/azure/machine-learning/concept-retrieval-augmented-generation?WT.mc_id=academic-105485-koreyst) - -🔗 [Grounding LLMs](https://techcommunity.microsoft.com/t5/fasttrack-for-azure/grounding-llms/ba-p/3843857?wt.mc_id=github_S-1231_webpage_reactor) - -🔗 [The Large Language Model (LLM) Index | Sapling](https://sapling.ai/llm/index?wt.mc_id=github_S-1231_webpage_reactor ) - -🔗 [[2304.04052] Decoder-Only or Encoder-Decoder? Interpreting Language Model as a Regularized Encoder-Decoder (arxiv.org)](https://arxiv.org/abs/2304.04052?wt.mc_id=github_S-1231_webpage_reactor) - -## Lesson 3 - 생성형 AI의 책임 있는 사용 - -🔗 [Fundamentals of Responsible Generative AI](https://learn.microsoft.com/training/modules/responsible-generative-ai/?&WT.mc_id=academic-105485-koreyst) - -🔗 [Grounding LLMs](https://techcommunity.microsoft.com/t5/fasttrack-for-azure/grounding-llms/ba-p/3843857?WT.mc_id=academic-105485-koreyst) - -🔗 [Fundamentals of Responsible Generative AI](https://learn.microsoft.com/training/modules/responsible-generative-ai?WT.mc_id=academic-105485-koreyst) - -🔗 [Being Responsible with Generative AI](https://learn.microsoft.com/shows/ai-show/being-responsible-with-generative-ai?WT.mc_id=academic-105485-koreyst) - -🔗 [GPT-4 System Card](https://cdn.openai.com/papers/gpt-4-system-card.pdf?wt.mc_id=github_S-1231_webpage_reactor) - -## Lesson 4 - 프롬프트 엔지니어링 기본 원리 이해 - -🔗 [Getting Started with Azure OpenAI Services](https://learn.microsoft.com/training/modules/get-started-openai/?&WT.mc_id=academic-105485-koreyst) - -[Apply Prompt Engineering with Azure OpenAI services](https://learn.microsoft.com/training/modules/apply-prompt-engineering-azure-openai/?&WT.mc_id=academic-105485-koreyst) - -[Introduction to Prompt Engineering](https://learn.microsoft.com/azure/ai-services/openai/concepts/prompt-engineering?&WT.mc_id=academic-105485-koreyst) - -🔗 [Prompt Engineering Overview](https://learn.microsoft.com/semantic-kernel/prompt-engineering/?WT.mc_id=academic-105485-koreyst) - -🔗 [Azure OpenAI for Education Prompts](https://techcommunity.microsoft.com/t5/education-blog/azure-openai-for-education-prompts-ai-and-a-guide-from-ethan-and/ba-p/3938259?wt.mc_id=github_S-1231_webpage_reactor ) - -🔗 [Introduction to Prompt Engineering](https://learn.microsoft.com/azure/ai-services/openai/concepts/prompt-engineering?WT.mc_id=academic-105485-koreyst) - -🔗 [Prompt Engineering Overview](https://learn.microsoft.com/semantic-kernel/prompt-engineering?WT.mc_id=academic-105485-koreyst) - -🔗 [Azure OpenAI for Education Prompts](https://techcommunity.microsoft.com/t5/e1.ucation-blog/azure-openai-for-education-prompts-ai-and-a-guide-from-ethan-and/ba-p/3938259?WT.mc_id=academic-105485-koreyst) - -## Lesson 5 - 고급 프롬프트 생성 - -🔗 [Prompt Engineering Techniques](https://learn.microsoft.com/azure/ai-services/openai/concepts/advanced-prompt-engineering?WT.mc_id=academic-105485-koreyst) - -## Lesson 6 - 텍스트 생성 애플리케이션 구축 - -🔗 [Prompt Engineering Techniques](https://learn.microsoft.com/azure/ai-services/openai/concepts/advanced-prompt-engineering?pivots=programming-language-chat-completions&WT.mc_id=academic-105485-koreyst) - -## Lesson 7 - 채팅 애플리케이션 구축 - -🔗 [System message framework and template recommendations for Large Language Models (LLMs)](https://learn.microsoft.com/azure/ai-services/openai/concepts/system-message?WT.mc_id=academic-105485-koreyst) - -🔗 [Learn how to work with the GPT-35-Turbo and GPT-4 models](https://learn.microsoft.com/azure/ai-services/openai/how-to/chatgpt?&WT.mc_id=academic-105485-koreyst) - -🔗 [Fine-Tuning language models from human preferences](https://arxiv.org/pdf/1909.08593.pdf?wt.mc_id=github_S-1231_webpage_reactor) - -🔗 [Build natural language solutions with Azure OpenAI Services](https://learn.microsoft.com/training/modules/build-language-solution-azure-openai/?WT.mc_id=academic-105485-koreyst) - - -🔗 [OpenAI Fine-Tuning](https://platform.openai.com/docs/guides/fine-tuning/when-to-use-fine-tuning?wt.mc_id=github_S-1231_webpage_reactor ) - -## Lesson 8 -검색 애플리케이션 구축 - -🔗 [Azure Cognitive Search](https://learn.microsoft.com/training/modules/improve-search-results-vector-search?WT.mc_id=academic-105485-koreyst) - -🔗 [OpenAI Embedding API](https://platform.openai.com/docs/api-reference/embeddings?wt.mc_id=github_S-1231_webpage_reactor) - -🔗 [Cosine Similarity](https://en.wikipedia.org/wiki/Cosine_similarity?wt.mc_id=github_S-1231_webpage_reactor) - -## Lesson 9 - 이미지 생성 애플리케이션 구축 - -🔗 [Generate Images with Azure OpenAI Service](https://learn.microsoft.com/training/modules/generate-images-azure-openai?WT.mc_id=academic-105485-koreyst) - -🔗 [OpenAI's DALL-E and CLIP 101: A Brief Introduction](https://towardsdatascience.com/openais-dall-e-and-clip-101-a-brief-introduction-3a4367280d4e?wt.mc_id=github_S-1231_webpage_reactor) - -🔗 [OpenAI's CLIP paper](https://arxiv.org/pdf/2103.00020.pdf?wt.mc_id=github_S-1231_webpage_reactor) - -🔗 [OpenAI's DALL-E and CLIP 101: A Brief Introduction](https://towardsdatascience.com/openais-dall-e-and-clip-101-a-brief-introduction-3a4367280d4e?WT.mc_id=academic-105485-koreyst) - -🔗 [OpenAI's CLIP paper](https://arxiv.org/pdf/2103.00020.pdf?WT.mc_id=academic-105485-koreyst) - -## Lesson 10 - 로우 코드 AI 애플리케이션 구축 -🔗 [Create bots with Microsoft Copilot Studio](https://learn.microsoft.com/training/paths/work-power-virtual-agents/?&WT.mc_id=academic-105485-koreyst) - -🔗 [Add intelligence with AI Builder and GPT](https://learn.microsoft.com/training/modules/ai-builder-text-generation?&WT.mc_id=academic-105485-koreyst) - -🔗 [Get Started with AI Builder](https://learn.microsoft.com/training/modules/get-started-with-ai-builder?WT.mc_id=academic-105485-koreyst) - -🔗 [Detect Objects with AI Builder](https://learn.microsoft.com/training/modules/get-started-with-ai-builder-object-detection?WT.mc_id=academic-105485-koreyst) - -🔗 [Build a canvas app solution with Copilot in Power Apps](https://learn.microsoft.com/training/modules/build-canvas-app-real-estate-power-apps-copilot/?WT.mc_id=academic-105485-koreyst) - -🔗 [Power Platform Copilot Prompt Library](https://pnp.github.io/powerplatform-prompts/?wt.mc_id=github_S-1231_webpage_reactor&WT.mc_id=academic-109639-somelezediko) - -## Lesson 11- 외부 애플리케이션과의 function calling 통합 - -🔗 [OpenAI Functions Documentation](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling?WT.mc_id=academic-105485-koreyst) - -## Lesson 12 - AI 애플리케이션을 위한 UX 디자인 - -🔗 [Best practices for building collaborative UX with Human-AI partnership](https://learn.microsoft.com/community/content/best-practices-ai-ux?WT.mc_id=academic-105485-koreyst) - -🔗 [Designing Human-Centric AI Experiences: Applied UX Design for Artificial Intelligence by Akshay Kpre](https://www.linkedin.com/learning/ux-for-ai-design-practices-for-ai-developers?wt.mc_id=github_S-1231_webpage_reactor) - -🔗 [UX for AI: Design Practices for AI Developers](https://www.youtube.com/watch?wt.mc_id=github_S-1231_webpage_reactor&v=Lkbkd_hkDLY) - -🔗 [New skills in the age of AI by John Maeda](https://www.amazon.com/Designing-Human-Centric-Experiences-Artificial-Intelligence/dp/1484280873?wt.mc_id=github_S-1231_webpage_reactor) - -🔗 [Designing Human-Centric AI Experiences: Applied UX Design for Artificial Intelligence by Akshay Kpre](https://www.amazon.com/Designing-Human-Centric-Experiences-Artificial-Intelligence/dp/1484280873?WT.mc_id=academic-105485-koreyst) diff --git a/13-securing-ai-applications/README.md b/13-securing-ai-applications/README.md index 3a4c6c57c..bed256aa7 100644 --- a/13-securing-ai-applications/README.md +++ b/13-securing-ai-applications/README.md @@ -1,6 +1,6 @@ # Securing Your Generative AI Applications -[![Securing Your Generative AI Applications](./images/13-lesson-banner.jpg?WT.mc_id=academic-105485-koreyst)]() +[![Securing Your Generative AI Applications](./images/13-lesson-banner.jpg?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson13-gh) ## Introduction diff --git a/13-securing-ai-applications/images/13-lesson-banner.jpg b/13-securing-ai-applications/images/13-lesson-banner.jpg deleted file mode 100644 index cf49a0e18..000000000 Binary files a/13-securing-ai-applications/images/13-lesson-banner.jpg and /dev/null differ diff --git a/13-securing-ai-applications/images/13-lesson-banner.png b/13-securing-ai-applications/images/13-lesson-banner.png new file mode 100644 index 000000000..d4fb26738 Binary files /dev/null and b/13-securing-ai-applications/images/13-lesson-banner.png differ diff --git a/13-securing-ai-applications/translatioins/cn/README.md b/13-securing-ai-applications/translatioins/cn/README.md index d80fbc930..04d6cee48 100644 --- a/13-securing-ai-applications/translatioins/cn/README.md +++ b/13-securing-ai-applications/translatioins/cn/README.md @@ -1,40 +1,40 @@ -# 生成式AI初学者指南:第13章 - 保护AI应用 +# 生成式 AI 初学者指南:第 13 章 - 保护 AI 应用 -[![保护您的AI应用](../../images/13-lesson-banner.jpg?WT.mc_id=academic-105485-koreyst)]() +[![保护您的AI应用](../../images/13-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson13-gh) ## 引言 本课程包括: -- AI系统的安全问题。 -- AI系统面临的常见风险与威胁。 -- 保障AI系统安全的方法与策略。 +- AI 系统的安全问题。 +- AI 系统面临的常见风险与威胁。 +- 保障 AI 系统安全的方法与策略。 ## 学习目标 学习完本课程,你将能够: -- 理解AI系统面临的风险与威胁。 -- 掌握保护AI系统的常用方法与最佳实践。 +- 理解 AI 系统面临的风险与威胁。 +- 掌握保护 AI 系统的常用方法与最佳实践。 - 了解如何通过安全测试预防意外事件和维护用户信任。 -## 生成式AI中的安全是什么意思? +## 生成式 AI 中的安全是什么意思? -随着人工智能(AI)和机器学习(ML)技术越来越多地影响我们的生活,保护客户数据和AI系统本身变得尤为重要。AI/ML在决策支持方面的应用越来越广泛,一旦决策出错,可能会带来严重的后果。 +随着人工智能(AI)和机器学习(ML)技术越来越多地影响我们的生活,保护客户数据和 AI 系统本身变得尤为重要。AI/ML 在决策支持方面的应用越来越广泛,一旦决策出错,可能会带来严重的后果。 需要关注的关键点包括: -- **AI/ML的影响**:AI/ML对我们生活的深远影响使得保护它们变得非常重要。 -- **安全挑战**:我们需要重视AI/ML带来的影响,以防止AI产品遭受复杂攻击,无论是来自恶意用户还是有组织的团体。 +- **AI/ML 的影响**:AI/ML 对我们生活的深远影响使得保护它们变得非常重要。 +- **安全挑战**:我们需要重视 AI/ML 带来的影响,以防止 AI 产品遭受复杂攻击,无论是来自恶意用户还是有组织的团体。 - **战略性问题**:科技产业需要主动应对战略挑战,保证客户安全和数据安全。 此外,机器学习模型往往无法区分恶意输入和异常数据。大量训练数据来自于未经筛选、未经审查的公开数据集,任何第三方都可以贡献内容。攻击者可以轻松贡献数据而不必直接篡改数据集。随着时间的推移,如果数据格式正确,即便是低可信度的恶意数据也可能变成高可信度的数据。 因此,确保模型决策依赖的数据存储的完整性和安全至关重要。 -## 理解AI的威胁和风险 +## 理解 AI 的威胁和风险 -目前,数据污染是AI及相关系统面临的最大安全威胁。数据污染是指有意修改训练AI所用的数据,从而导致AI犯错。这种情况之所以发生,一方面是因为缺乏标准化的检测和缓解方法,另一方面是因为我们依赖于不可靠或未经筛选的公共数据集进行训练。跟踪数据的来源和血统,以维护数据完整性并防止训练过程出错,显得尤为重要。否则,就会出现“垃圾进,垃圾出”的情况,最终影响模型的性能。 +目前,数据污染是 AI 及相关系统面临的最大安全威胁。数据污染是指有意修改训练 AI 所用的数据,从而导致 AI 犯错。这种情况之所以发生,一方面是因为缺乏标准化的检测和缓解方法,另一方面是因为我们依赖于不可靠或未经筛选的公共数据集进行训练。跟踪数据的来源和血统,以维护数据完整性并防止训练过程出错,显得尤为重要。否则,就会出现“垃圾进,垃圾出”的情况,最终影响模型的性能。 数据污染对模型的影响示例包括: @@ -47,98 +47,98 @@ 4. **后门攻击**:攻击者在训练数据中插入隐藏模式(后门),使模型在触发时表现出恶意行为。.\ **示例**:通过训练含有后门的图像,使面部识别系统错误识别特定人物。 -MITRE公司创建了[ATLAS(Adversarial Threat Landscape for Artificial-Intelligence Systems)](https://atlas.mitre.org/?WT.mc_id=academic-105485-koreyst),一个记录对手在真实攻击AI系统中使用的策略和技术的知识库。 +MITRE 公司创建了[ATLAS(Adversarial Threat Landscape for Artificial-Intelligence Systems)](https://atlas.mitre.org/?WT.mc_id=academic-105485-koreyst),一个记录对手在真实攻击 AI 系统中使用的策略和技术的知识库。 -> 随着AI技术的融合,AI系统的漏洞数量增加,这超出了传统网络攻击的范畴。我们开发ATLAS的目的是提高对这些独特且不断演变的漏洞的认识,因为全球社区越来越多地将AI纳入各种系统中。ATLAS参照MITRE ATT&CK®框架建立,其策略、技术和程序(TTPs)与ATT&CK中的内容相辅相成。 +> 随着 AI 技术的融合,AI 系统的漏洞数量增加,这超出了传统网络攻击的范畴。我们开发 ATLAS 的目的是提高对这些独特且不断演变的漏洞的认识,因为全球社区越来越多地将 AI 纳入各种系统中。ATLAS 参照 MITRE ATT&CK® 框架建立,其策略、技术和程序(TTPs)与 ATT&CK 中的内容相辅相成。 -与MITRE ATT&CK®框架一样——该框架广泛用于传统网络安全,规划高级威胁模拟场景——ATLAS提供了一套易于搜索的TTPs,帮助我们更好地理解和准备防御新兴攻击。 +与 MITRE ATT&CK® 框架一样——该框架广泛用于传统网络安全,规划高级威胁模拟场景——ATLAS 提供了一套易于搜索的 TTPs,帮助我们更好地理解和准备防御新兴攻击。 Open Web Application Security Project (OWASP)还创建了一个“[前十大漏洞列表](https://llmtop10.com/?WT.mc_id=academic-105485-koreyst)”,列出了利用大型语言模型(LLMs)的应用程序中最关键的漏洞。列表强调了包括数据污染在内的威胁风险,以及其他风险,例如: - **提示注入**:通过精心设计的输入操纵大型语言模型(LLM),使其偏离预期行为的技术。 -- **供应链漏洞**:构成LLM应用程序的组件和软件可能被威胁,导致意外结果、引入偏见,甚至是基础设施漏洞。 -- **过度依赖**:LLMs容易出错,可能提供不准确或不安全的结果。在多个实例中,人们将结果视为准确无误,导致了意想不到的负面后果。 +- **供应链漏洞**:构成 LLM 应用程序的组件和软件可能被威胁,导致意外结果、引入偏见,甚至是基础设施漏洞。 +- **过度依赖**:LLMs 容易出错,可能提供不准确或不安全的结果。在多个实例中,人们将结果视为准确无误,导致了意想不到的负面后果。 -Microsoft Cloud Advocate Rod Trent撰写的免费电子书[必须学习的AI安全](https://github.com/rod-trent/OpenAISecurity/tree/main/Must_Learn/Book_Version?WT.mc_id=academic-105485-koreyst)深入探讨了这些和其他新兴AI威胁,并提供了广泛的指导,以应对这些挑战。 +Microsoft Cloud Advocate Rod Trent 撰写的免费电子书[必须学习的 AI 安全](https://github.com/rod-trent/OpenAISecurity/tree/main/Must_Learn/Book_Version?WT.mc_id=academic-105485-koreyst)深入探讨了这些和其他新兴 AI 威胁,并提供了广泛的指导,以应对这些挑战。 -## AI系统和大型语言模型的安全测试 +## AI 系统和大型语言模型的安全测试 -人工智能(AI)正在改变各种领域和行业,为社会带来新的可能性和好处。然而,AI也带来了数据隐私、偏见、缺乏可解释性和潜在滥用等重大挑战和风险。因此,确保AI系统的安全性和责任感至关重要,这意味着它们需要遵守道德和法律标准,并获得用户和利益相关者的信任。 +人工智能(AI)正在改变各种领域和行业,为社会带来新的可能性和好处。然而,AI 也带来了数据隐私、偏见、缺乏可解释性和潜在滥用等重大挑战和风险。因此,确保 AI 系统的安全性和责任感至关重要,这意味着它们需要遵守道德和法律标准,并获得用户和利益相关者的信任。 -安全测试是通过识别和利用它们的漏洞来评估AI系统或大型语言模型的安全性的过程。这项测试可以由开发者、用户或第三方审计员根据测试的目的和范围进行。AI系统和大型语言模型的一些常见安全测试方法包括: +安全测试是通过识别和利用它们的漏洞来评估 AI 系统或大型语言模型的安全性的过程。这项测试可以由开发者、用户或第三方审计员根据测试的目的和范围进行。AI 系统和大型语言模型的一些常见安全测试方法包括: -- **数据清洗**:从AI系统或大型语言模型的训练数据或输入中删除或匿名化敏感或私有信息的过程。数据清洗有助于防止数据泄露和恶意操作,通过减少机密或个人数据的暴露。 -- **对抗性测试**:生成并应用对抗性示例到AI系统或大型语言模型的输入或输出的过程,以评估其对对抗性攻击的鲁棒性和恢复力。对抗性测试有助于识别和缓解AI系统或大型语言模型可能被攻击者利用的漏洞和弱点。 -- **模型验证**:验证AI系统或大型语言模型的模型参数或架构的正确性和完整性的过程。模型验证有助于检测和防止模型盗用,确保模型受到保护和认证。 -- **输出验证**:验证AI系统或大型语言模型输出的质量和可靠性的过程。输出验证有助于检测和纠正恶意操作,确保输出是一致和准确的。 +- **数据清洗**:从 AI 系统或大型语言模型的训练数据或输入中删除或匿名化敏感或私有信息的过程。数据清洗有助于防止数据泄露和恶意操作,通过减少机密或个人数据的暴露。 +- **对抗性测试**:生成并应用对抗性示例到 AI 系统或大型语言模型的输入或输出的过程,以评估其对对抗性攻击的鲁棒性和恢复力。对抗性测试有助于识别和缓解 AI 系统或大型语言模型可能被攻击者利用的漏洞和弱点。 +- **模型验证**:验证 AI 系统或大型语言模型的模型参数或架构的正确性和完整性的过程。模型验证有助于检测和防止模型盗用,确保模型受到保护和认证。 +- **输出验证**:验证 AI 系统或大型语言模型输出的质量和可靠性的过程。输出验证有助于检测和纠正恶意操作,确保输出是一致和准确的。 -OpenAI作为AI系统的领先者,建立了一系列_安全评估_作为其红队网络计划的一部分,旨在测试AI系统的输出,希望为AI安全做出贡献。 +OpenAI 作为 AI 系统的领先者,建立了一系列*安全评估*作为其红队网络计划的一部分,旨在测试 AI 系统的输出,希望为 AI 安全做出贡献。 -> 评估可以从简单的问答测试到更复杂的模拟。以下是一些OpenAI开发的样本评估,用于从多个角度评估AI行为的具体示例: +> 评估可以从简单的问答测试到更复杂的模拟。以下是一些 OpenAI 开发的样本评估,用于从多个角度评估 AI 行为的具体示例: #### 说服(Persuasion) -- [MakeMeSay](https://github.com/openai/evals/tree/main/evals/elsuite/make_me_say/readme.md?WT.mc_id=academic-105485-koreyst):一个AI系统能多好地欺骗另一个AI系统说出一个秘密词? -- [MakeMePay](https://github.com/openai/evals/tree/main/evals/elsuite/make_me_pay/readme.md?WT.mc_id=academic-105485-koreyst):一个AI系统能多好地说服另一个AI系统捐款? -- [Ballot Proposal](https://github.com/openai/evals/tree/main/evals/elsuite/ballots/readme.md?WT.mc_id=academic-105485-koreyst):一个AI系统能多好地影响另一个AI系统对政治提案的支持? +- [MakeMeSay](https://github.com/openai/evals/tree/main/evals/elsuite/make_me_say/readme.md?WT.mc_id=academic-105485-koreyst):一个 AI 系统能多好地欺骗另一个 AI 系统说出一个秘密词? +- [MakeMePay](https://github.com/openai/evals/tree/main/evals/elsuite/make_me_pay/readme.md?WT.mc_id=academic-105485-koreyst):一个 AI 系统能多好地说服另一个 AI 系统捐款? +- [Ballot Proposal](https://github.com/openai/evals/tree/main/evals/elsuite/ballots/readme.md?WT.mc_id=academic-105485-koreyst):一个 AI 系统能多好地影响另一个 AI 系统对政治提案的支持? #### 隐写术(隐藏信息) -- [Steganography](https://github.com/openai/evals/tree/main/evals/elsuite/steganography/readme.md?WT.mc_id=academic-105485-koreyst):一个AI系统能多好地传递秘密消息而不被另一个AI系统发现? -- [Text Compression](https://github.com/openai/evals/tree/main/evals/elsuite/text_compression/readme.md?WT.mc_id=academic-105485-koreyst):一个AI系统在压缩和解压消息方面的表现如何,以便隐藏秘密消息? -- [Schelling Point](https://github.com/openai/evals/blob/main/evals/elsuite/schelling_point/README.md?WT.mc_id=academic-105485-koreyst):一个AI系统在没有直接通信的情况下与另一个AI系统协调的能力如何? +- [Steganography](https://github.com/openai/evals/tree/main/evals/elsuite/steganography/readme.md?WT.mc_id=academic-105485-koreyst):一个 AI 系统能多好地传递秘密消息而不被另一个 AI 系统发现? +- [Text Compression](https://github.com/openai/evals/tree/main/evals/elsuite/text_compression/readme.md?WT.mc_id=academic-105485-koreyst):一个 AI 系统在压缩和解压消息方面的表现如何,以便隐藏秘密消息? +- [Schelling Point](https://github.com/openai/evals/blob/main/evals/elsuite/schelling_point/README.md?WT.mc_id=academic-105485-koreyst):一个 AI 系统在没有直接通信的情况下与另一个 AI 系统协调的能力如何? -### AI安全 +### AI 安全 -我们的目标是保护AI系统免受恶意攻击、滥用或意外后果的影响。这包括采取措施确保AI系统的安全、可靠性和可信度,例如: +我们的目标是保护 AI 系统免受恶意攻击、滥用或意外后果的影响。这包括采取措施确保 AI 系统的安全、可靠性和可信度,例如: -- 保护用于训练和运行AI模型的数据和算法 -- 防止未经授权的访问、操纵或破坏AI系统 -- 检测和缓解AI系统中的偏见、歧视或道德问题 -- 确保AI决策和行动的问责性、透明度和可解释性 -- 使AI系统的目标和价值与人类和社会的目标和价值一致 +- 保护用于训练和运行 AI 模型的数据和算法 +- 防止未经授权的访问、操纵或破坏 AI 系统 +- 检测和缓解 AI 系统中的偏见、歧视或道德问题 +- 确保 AI 决策和行动的问责性、透明度和可解释性 +- 使 AI 系统的目标和价值与人类和社会的目标和价值一致 -AI安全对于确保AI系统和数据的完整性、可用性和机密性至关重要。AI安全的挑战和机遇包括: +AI 安全对于确保 AI 系统和数据的完整性、可用性和机密性至关重要。AI 安全的挑战和机遇包括: -- 机遇:将AI纳入网络安全策略,因为它可以在识别威胁和提高响应时间方面发挥关键作用。AI可以帮助自动化和增强检测和缓解网络攻击的能力,如网络钓鱼、恶意软件或勒索软件。 -- 挑战:对手也可以使用AI发起复杂的攻击,如生成假或误导性内容、冒充用户或利用AI系统中的漏洞。因此,AI开发者有独特的责任设计出对滥用具有韧性和抵抗力的系统。 +- 机遇:将 AI 纳入网络安全策略,因为它可以在识别威胁和提高响应时间方面发挥关键作用。AI 可以帮助自动化和增强检测和缓解网络攻击的能力,如网络钓鱼、恶意软件或勒索软件。 +- 挑战:对手也可以使用 AI 发起复杂的攻击,如生成假或误导性内容、冒充用户或利用 AI 系统中的漏洞。因此,AI 开发者有独特的责任设计出对滥用具有韧性和抵抗力的系统。 ### 数据保护 -LLMs可能对它们使用的数据的隐私和安全构成风险。例如,LLMs可能会记住并泄露其训练数据中的敏感信息,如个人姓名、地址、密码或信用卡号码。它们还可能被恶意行为者操纵或攻击,这些人想要利用它们的漏洞或偏见。因此,了解这些风险并采取适当措施保护LLMs使用的数据很重要。您可以采取几个步骤来保护与LLMs一起使用的数据。这些步骤包括: +LLMs 可能对它们使用的数据的隐私和安全构成风险。例如,LLMs 可能会记住并泄露其训练数据中的敏感信息,如个人姓名、地址、密码或信用卡号码。它们还可能被恶意行为者操纵或攻击,这些人想要利用它们的漏洞或偏见。因此,了解这些风险并采取适当措施保护 LLMs 使用的数据很重要。您可以采取几个步骤来保护与 LLMs 一起使用的数据。这些步骤包括: -- **限制他们与LLMs共享的数据的数量和类型**:只共享对预期目的必要和相关的数据,并避免共享任何敏感、机密或个人的数据。用户还应该匿名化或加密他们与LLMs共享的数据,例如通过删除或掩盖任何识别信息,或使用安全的通信渠道。 -- **验证LLMs生成的数据**:始终检查LLMs生成的输出的准确性和质量,以确保它们不包含任何不需要或不适当的信息。 -- **报告和警告任何数据泄露或事件**:警惕LLMs产生的任何可疑或异常的活动或行为,例如生成不相关、不准确、冒犯性或有害的文本。这可能是数据泄露或安全事件的迹象。 +- **限制他们与 LLMs 共享的数据的数量和类型**:只共享对预期目的必要和相关的数据,并避免共享任何敏感、机密或个人的数据。用户还应该匿名化或加密他们与 LLMs 共享的数据,例如通过删除或掩盖任何识别信息,或使用安全的通信渠道。 +- **验证 LLMs 生成的数据**:始终检查 LLMs 生成的输出的准确性和质量,以确保它们不包含任何不需要或不适当的信息。 +- **报告和警告任何数据泄露或事件**:警惕 LLMs 产生的任何可疑或异常的活动或行为,例如生成不相关、不准确、冒犯性或有害的文本。这可能是数据泄露或安全事件的迹象。 -数据安全、治理和合规对于任何希望在多云环境中利用数据和AI的力量的组织至关重要。保护和治理您的所有数据是一项复杂和多方面的任务。您需要在多个云中的不同位置保护和治理不同类型的数据(结构化、非结构化和由AI生成的数据),并需要考虑现有和未来的数据安全、治理和AI法规。为了保护您的数据,您需要采取一些最佳实践和预防措施,例如: +数据安全、治理和合规对于任何希望在多云环境中利用数据和 AI 的力量的组织至关重要。保护和治理您的所有数据是一项复杂和多方面的任务。您需要在多个云中的不同位置保护和治理不同类型的数据(结构化、非结构化和由 AI 生成的数据),并需要考虑现有和未来的数据安全、治理和 AI 法规。为了保护您的数据,您需要采取一些最佳实践和预防措施,例如: - 使用提供数据保护和隐私功能的云服务或平台。 - 使用数据质量和验证工具检查您的数据是否有错误、不一致或异常。 - 使用数据治理和伦理框架确保您的数据以负责任和透明的方式使用。 -### 模拟现实世界威胁 - AI红队(AI red teaming) +### 模拟现实世界威胁 - AI 红队(AI red teaming) -模拟现实世界威胁现在被认为是构建弹性AI系统的标准实践,通过采用类似的工具、策略、程序来识别系统的风险并测试防御者的响应。 +模拟现实世界威胁现在被认为是构建弹性 AI 系统的标准实践,通过采用类似的工具、策略、程序来识别系统的风险并测试防御者的响应。 -> AI红队的实践已经演变为具有更广泛的含义:它不仅涵盖了探测安全漏洞,还包括探测其他系统故障,如生成可能有害的内容。AI系统带来了新的风险,而红队是理解这些新风险的核心,如提示注入和产生不切实际的内容。- [Microsoft AI红队构建更安全的AI未来](https://www.microsoft.com/security/blog/2023/08/07/microsoft-ai-red-team-building-future-of-safer-ai/?WT.mc_id=academic-105485-koreyst) +> AI 红队的实践已经演变为具有更广泛的含义:它不仅涵盖了探测安全漏洞,还包括探测其他系统故障,如生成可能有害的内容。AI 系统带来了新的风险,而红队是理解这些新风险的核心,如提示注入和产生不切实际的内容。- [Microsoft AI 红队构建更安全的 AI 未来](https://www.microsoft.com/security/blog/2023/08/07/microsoft-ai-red-team-building-future-of-safer-ai/?WT.mc_id=academic-105485-koreyst) [![红队指引和资源](../../images/13-AI-red-team.png?WT.mc_id=academic-105485-koreyst)]() -以下是塑造Microsoft AI红队计划的关键洞察。 +以下是塑造 Microsoft AI 红队计划的关键洞察。 -1. **AI红队的广泛范围:**AI红队现在包括安全和负责任AI(RAI)结果。传统上,红队专注于安全方面,将模型视为向量(例如,盗用底层模型)。然而,AI系统引入了新的安全漏洞(例如,提示注入,污染),需要特别关注。除了安全之外,AI红队还探测公平问题(例如,刻板印象)和有害内容(例如,暴力美化)。及早识别这些问题允许优先考虑防御投资。 -2. **恶意和良性失败:**AI红队考虑了恶意和良性视角的失败。例如,当红队新的Bing时,我们探索的不仅仅是恶意对手如何颠覆系统,还有普通用户可能遇到的问题或有害内容。与传统的安全红队不同,主要关注恶意行为者,AI红队考虑了更广泛的人物和潜在失败。 -3. **AI系统的动态性:**AI应用不断进化。在大语言模型应用中,开发者适应不断变化的要求。持续的红队确保持续的警惕和适应不断变化的风险。 +1. **AI 红队的广泛范围:**AI 红队现在包括安全和负责任 AI(RAI)结果。传统上,红队专注于安全方面,将模型视为向量(例如,盗用底层模型)。然而,AI 系统引入了新的安全漏洞(例如,提示注入,污染),需要特别关注。除了安全之外,AI 红队还探测公平问题(例如,刻板印象)和有害内容(例如,暴力美化)。及早识别这些问题允许优先考虑防御投资。 +2. **恶意和良性失败:**AI 红队考虑了恶意和良性视角的失败。例如,当红队新的 Bing 时,我们探索的不仅仅是恶意对手如何颠覆系统,还有普通用户可能遇到的问题或有害内容。与传统的安全红队不同,主要关注恶意行为者,AI 红队考虑了更广泛的人物和潜在失败。 +3. **AI 系统的动态性:**AI 应用不断进化。在大语言模型应用中,开发者适应不断变化的要求。持续的红队确保持续的警惕和适应不断变化的风险。 -AI红队并非包罗万象,应被视为补充其他控制措施,如[基于角色的访问控制(RBAC)](https://learn.microsoft.com/azure/ai-services/openai/how-to/role-based-access-control?WT.mc_id=academic-105485-koreyst)和全面的数据管理解决方案。它旨在补充一个安全策略,该策略侧重于采用安全和负责任的AI解决方案,这些解决方案考虑到隐私和安全,同时努力最小化偏见、有害内容和误导信息,这些都可能侵蚀用户信心。 +AI 红队并非包罗万象,应被视为补充其他控制措施,如[基于角色的访问控制(RBAC)](https://learn.microsoft.com/azure/ai-services/openai/how-to/role-based-access-control?WT.mc_id=academic-105485-koreyst)和全面的数据管理解决方案。它旨在补充一个安全策略,该策略侧重于采用安全和负责任的 AI 解决方案,这些解决方案考虑到隐私和安全,同时努力最小化偏见、有害内容和误导信息,这些都可能侵蚀用户信心。 -以下是一些可以帮助您更好地了解红队如何帮助识别和缓解AI系统中的风险的额外阅读材料: +以下是一些可以帮助您更好地了解红队如何帮助识别和缓解 AI 系统中的风险的额外阅读材料: - [为大型语言模型(LLMs)及其应用规划红队](https://learn.microsoft.com/azure/ai-services/openai/concepts/red-teaming?WT.mc_id=academic-105485-koreyst) -- [什么是OpenAI红队网络?](https://openai.com/blog/red-teaming-network?WT.mc_id=academic-105485-koreyst) -- [AI红队 - 构建更安全、更负责任的AI解决方案的关键实践](https://rodtrent.substack.com/p/ai-red-teaming?WT.mc_id=academic-105485-koreyst) -- MITRE [ATLAS (Adversarial Threat Landscape for Artificial-Intelligence Systems)](https://atlas.mitre.org/?WT.mc_id=academic-105485-koreyst),一个知识库,记录了对手在对AI系统进行实际攻击中使用的策略和技术。 +- [什么是 OpenAI 红队网络?](https://openai.com/blog/red-teaming-network?WT.mc_id=academic-105485-koreyst) +- [AI 红队 - 构建更安全、更负责任的 AI 解决方案的关键实践](https://rodtrent.substack.com/p/ai-red-teaming?WT.mc_id=academic-105485-koreyst) +- MITRE [ATLAS (Adversarial Threat Landscape for Artificial-Intelligence Systems)](https://atlas.mitre.org/?WT.mc_id=academic-105485-koreyst),一个知识库,记录了对手在对 AI 系统进行实际攻击中使用的策略和技术。 ## 知识检查 @@ -146,16 +146,16 @@ AI红队并非包罗万象,应被视为补充其他控制措施,如[基于 1. 为数据访问和数据管理实施强大的基于角色的控制 2. 执行并审计数据标签,以防止数据误表达或滥用 -3. 确保您的AI基础设施支持内容过滤 +3. 确保您的 AI 基础设施支持内容过滤 -答案:1,虽然所有这三个建议都很有价值,但确保正确分配用户数据访问权限将大大减少通过LLMs操纵和误解数据的风险。 +答案:1,虽然所有这三个建议都很有价值,但确保正确分配用户数据访问权限将大大减少通过 LLMs 操纵和误解数据的风险。 ## 🚀 挑战 -探索更多关于如何在AI时代[管理和保护敏感信息](https://learn.microsoft.com/training/paths/purview-protect-govern-ai/?WT.mc_id=academic-105485-koreyst)的方法。 +探索更多关于如何在 AI 时代[管理和保护敏感信息](https://learn.microsoft.com/training/paths/purview-protect-govern-ai/?WT.mc_id=academic-105485-koreyst)的方法。 ## 做得好,继续你的学习之旅 -完成本课程后,请继续探索我们的[生成式AI学习系列](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst),以进一步提高你的生成式AI技能! +完成本课程后,请继续探索我们的[生成式 AI 学习系列](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst),以进一步提高你的生成式 AI 技能! -下一站,第14课:[生成式AI应用生命周期](../../../14-the-generative-ai-application-lifecycle/README.md?WT.mc_id=academic-105485-koreyst)! +下一站,第 14 课:[生成式 AI 应用生命周期](../../../14-the-generative-ai-application-lifecycle/README.md?WT.mc_id=academic-105485-koreyst)! diff --git a/14-the-generative-ai-application-lifecycle/README.md b/14-the-generative-ai-application-lifecycle/README.md index d5a90c7bb..c2677f310 100644 --- a/14-the-generative-ai-application-lifecycle/README.md +++ b/14-the-generative-ai-application-lifecycle/README.md @@ -1,3 +1,5 @@ +[![Integrating with function calling](./images/14-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson14-gh) + # The Generative AI Application Lifecycle An important question for all AI applications is the relevance of AI features, as AI is a fast evolving field, to ensure that your application remains relevant, reliable, and robust, you need to monitor, evaluate, and improve it continuously. This is where the generative AI lifecycle comes in. diff --git a/14-the-generative-ai-application-lifecycle/images/14-lesson-banner.png b/14-the-generative-ai-application-lifecycle/images/14-lesson-banner.png new file mode 100644 index 000000000..931cb4f93 Binary files /dev/null and b/14-the-generative-ai-application-lifecycle/images/14-lesson-banner.png differ diff --git a/14-the-generative-ai-application-lifecycle/translations/cn/README.md b/14-the-generative-ai-application-lifecycle/translations/cn/README.md index 972c8b3b9..bb6c481e1 100644 --- a/14-the-generative-ai-application-lifecycle/translations/cn/README.md +++ b/14-the-generative-ai-application-lifecycle/translations/cn/README.md @@ -1,43 +1,45 @@ -# 生成式AI应用生命周期 +[![Integrating with function calling](../../images/14-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson14-gh) -在所有AI应用的开发中,一个核心问题是如何保持AI特性的持续相关性。鉴于AI技术的快速进步,为了确保你的应用能够持续提供相关、可靠且强大的性能,你需要不断地监控、评估并优化它。这正是生成式AI生命周期发挥作用的地方。 +# 生成式 AI 应用生命周期 -生成式AI生命周期提供了一个框架,指引你穿越开发、部署和维护生成式AI应用的各个阶段。它帮助你明确目标、衡量性能、识别挑战,并实施解决方案。此外,它还支持你确保应用遵循特定领域及其利益相关者的伦理和法律标准。遵循生成式AI生命周期,可以保证你的应用持续创造价值,满足用户需求。 +在所有 AI 应用的开发中,一个核心问题是如何保持 AI 特性的持续相关性。鉴于 AI 技术的快速进步,为了确保你的应用能够持续提供相关、可靠且强大的性能,你需要不断地监控、评估并优化它。这正是生成式 AI 生命周期发挥作用的地方。 + +生成式 AI 生命周期提供了一个框架,指引你穿越开发、部署和维护生成式 AI 应用的各个阶段。它帮助你明确目标、衡量性能、识别挑战,并实施解决方案。此外,它还支持你确保应用遵循特定领域及其利益相关者的伦理和法律标准。遵循生成式 AI 生命周期,可以保证你的应用持续创造价值,满足用户需求。 ## 引言 在本章中,你将学到: -- 从MLOps到LLMOps的范式转变 -- LLM生命周期 +- 从 MLOps 到 LLMOps 的范式转变 +- LLM 生命周期 - 生命周期工具 - 生命周期量化与评估 -## 从MLOps到LLMOps的范式转变 +## 从 MLOps 到 LLMOps 的范式转变 -大型语言模型(LLMs)作为人工智能工具箱中的新成员,它们在分析和生成任务中表现出强大的能力。然而,这种能力也给我们如何高效地管理AI和传统机器学习任务带来了挑战。 +大型语言模型(LLMs)作为人工智能工具箱中的新成员,它们在分析和生成任务中表现出强大的能力。然而,这种能力也给我们如何高效地管理 AI 和传统机器学习任务带来了挑战。 -这要求我们采用新的范式来适应这一变化,以正确的激励措施引导其发展。我们可以将传统的AI应用称为“ML应用”,将基于最新技术和技术的新型AI应用称为“GenAI应用”或简称“AI应用”。这种分类方式从多个方面改变了我们的讨论框架,如下比较所示。 +这要求我们采用新的范式来适应这一变化,以正确的激励措施引导其发展。我们可以将传统的 AI 应用称为“ML 应用”,将基于最新技术和技术的新型 AI 应用称为“GenAI 应用”或简称“AI 应用”。这种分类方式从多个方面改变了我们的讨论框架,如下比较所示。 ![LLMOps vs. MLOps comparison](../../images/01-llmops-shift.png?WT.mc_id=academic-105485-koreys) -注意,在LLMOps中,我们更加关注应用开发者,并将集成作为关键点,采用“模型即服务”,并围绕以下几个关键指标进行思考: +注意,在 LLMOps 中,我们更加关注应用开发者,并将集成作为关键点,采用“模型即服务”,并围绕以下几个关键指标进行思考: - 质量:响应的质量 -- 危害:负责任的AI +- 危害:负责任的 AI - 诚信:响应的合理性(是否有意义?是否正确?) - 成本:解决方案的预算 - 延迟:令牌响应的平均时间 -## LLM生命周期 +## LLM 生命周期 首先,让我们通过下图了解生命周期及其变化。 ![LLMOps infographic](../../images/02-llmops.png?WT.mc_id=academic-105485-koreys) -可以看出,这与MLOps的传统生命周期有所不同。LLMs引入了许多新的需求,如提示工程、质量改进技术(微调、RAG、元提示)、负责任AI的不同评估和责任,以及新的评估指标(质量、危害、诚信、成本和延迟)。 +可以看出,这与 MLOps 的传统生命周期有所不同。LLMs 引入了许多新的需求,如提示工程、质量改进技术(微调、RAG、元提示)、负责任 AI 的不同评估和责任,以及新的评估指标(质量、危害、诚信、成本和延迟)。 -例如,看看我们如何进行构思。利用提示工程与不同LLMs进行实验,探索各种可能性,测试假设是否成立。 +例如,看看我们如何进行构思。利用提示工程与不同 LLMs 进行实验,探索各种可能性,测试假设是否成立。 注意,这不是一个线性过程,而是一个集成的循环过程,迭代且具有一个总体周期。 @@ -48,36 +50,36 @@ 这个过程可能看起来复杂,让我们先关注三个主要步骤: 1. 构思/探索:在这里,我们可以根据业务需求进行探索。原型设计,创建[PromptFlow](https://microsoft.github.io/promptflow/index.html?WT.mc_id=academic-105485-koreyst),并测试其是否足够有效来验证我们的假设。 -2. 构建/增强:现在开始评估更大的数据集并实施技术,如微调和RAG,以检验我们的解决方案的稳健性。如果不符合要求,重新实施、添加新的流程步骤或重组数据可能会有所帮助。经过流程和规模测试后,如果一切顺利并满足我们的指标,就准备进入下一个阶段。 +2. 构建/增强:现在开始评估更大的数据集并实施技术,如微调和 RAG,以检验我们的解决方案的稳健性。如果不符合要求,重新实施、添加新的流程步骤或重组数据可能会有所帮助。经过流程和规模测试后,如果一切顺利并满足我们的指标,就准备进入下一个阶段。 3. 运营化:集成监控和警报系统到我们的系统,部署和应用程序集成。 然后,我们有管理的整体周期,重点关注安全、合规和治理。 -恭喜,现在你的AI应用已经准备就绪,可以投入使用了。想要动手体验,可以尝试[Contoso Chat Demo.](https://nitya.github.io/contoso-chat/?WT.mc_id=academic-105485-koreys) +恭喜,现在你的 AI 应用已经准备就绪,可以投入使用了。想要动手体验,可以尝试[Contoso Chat Demo.](https://nitya.github.io/contoso-chat/?WT.mc_id=academic-105485-koreys) 那么,我们可以使用哪些工具呢? ## 生命周期工具 -Microsoft提供的[Azure AI Platform](https://azure.microsoft.com/solutions/ai/?WT.mc_id=academic-105485-koreys)和[PromptFlow](https://microsoft.github.io/promptflow/index.html?WT.mc_id=academic-105485-koreyst),简化了生命周期的实施,让你的应用快速上线。 +Microsoft 提供的[Azure AI Platform](https://azure.microsoft.com/solutions/ai/?WT.mc_id=academic-105485-koreys)和[PromptFlow](https://microsoft.github.io/promptflow/index.html?WT.mc_id=academic-105485-koreyst),简化了生命周期的实施,让你的应用快速上线。 -通过[Azure AI Platform](https://azure.microsoft.com/solutions/ai/?WT.mc_id=academic-105485-koreys),你可以利用[AI Studio](https://ai.azure.com/?WT.mc_id=academic-105485-koreys)。AI Studio是一个网页门户,让你可以探索模型、示例和工具,管理资源,进行UI开发流程,以及提供SDK/CLI选项进行代码优先开发。 +通过[Azure AI Platform](https://azure.microsoft.com/solutions/ai/?WT.mc_id=academic-105485-koreys),你可以利用[AI Studio](https://ai.azure.com/?WT.mc_id=academic-105485-koreys)。AI Studio 是一个网页门户,让你可以探索模型、示例和工具,管理资源,进行 UI 开发流程,以及提供 SDK/CLI 选项进行代码优先开发。 ![Azure AI possibilities](../../images/04-azure-ai-platform.png?WT.mc_id=academic-105485-koreys) -Azure AI让你可以使用多种资源,管理你的操作、服务、项目、向量搜索和数据库需求。 +Azure AI 让你可以使用多种资源,管理你的操作、服务、项目、向量搜索和数据库需求。 ![LLMOps with Azure AI](../../images/05-llm-azure-ai-prompt.png?WT.mc_id=academic-105485-koreys) -从概念证明(POC)到大规模应用,利用PromptFlow进行构建: +从概念证明(POC)到大规模应用,利用 PromptFlow 进行构建: -- 从VS Code设计和构建应用,使用视觉和功能工具。 -- 轻松测试和微调你的应用,以实现高质量AI。 -- 使用Azure AI Studio进行集成和迭代,通过云推送和部署实现快速集成。 +- 从 VS Code 设计和构建应用,使用视觉和功能工具。 +- 轻松测试和微调你的应用,以实现高质量 AI。 +- 使用 Azure AI Studio 进行集成和迭代,通过云推送和部署实现快速集成。 ![LLMOps with PromptFlow](../../images/06-llm-promptflow.png?WT.mc_id=academic-105485-koreys) ## 继续学习! -通过[Contoso Chat App](https://nitya.github.io/contoso-chat/?WT.mc_id=academic-105485-koreyst)深入学习我们如何将这些概念应用于实际应用开发,并查看Cloud Advocacy如何在演示中加入这些概念。想要获取更多内容,不妨观看我们的[Ignite breakout session!](https://www.youtube.com/watch?v=DdOylyrTOWg) +通过[Contoso Chat App](https://nitya.github.io/contoso-chat/?WT.mc_id=academic-105485-koreyst)深入学习我们如何将这些概念应用于实际应用开发,并查看 Cloud Advocacy 如何在演示中加入这些概念。想要获取更多内容,不妨观看我们的[Ignite breakout session!](https://www.youtube.com/watch?v=DdOylyrTOWg) -接下来,通过第15课,了解[检索增强生成和向量数据库](../../../15-rag-and-vector-databases/README.md?WT.mc_id=academic-105485-koreyst)如何影响生成式AI,使应用更加吸引用户! +接下来,通过第 15 课,了解[检索增强生成和向量数据库](../../../15-rag-and-vector-databases/README.md?WT.mc_id=academic-105485-koreyst)如何影响生成式 AI,使应用更加吸引用户! diff --git a/15-rag-and-vector-databases/README.md b/15-rag-and-vector-databases/README.md index 6f0f78981..c52013aa2 100644 --- a/15-rag-and-vector-databases/README.md +++ b/15-rag-and-vector-databases/README.md @@ -1,6 +1,6 @@ # Retrieval Augmented Generation (RAG) and Vector Databases - +[![Retrieval Augmented Generation (RAG) and Vector Databases](./images/15-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson15-gh) In the search applications lesson, we briefly learned how to integrate your own data into Large Language Models (LLMs). In this lesson, we will delve further into the concepts of grounding your data in your LLM application, the mechanics of the process and the methods for storing data, including both embeddings and text. diff --git a/15-rag-and-vector-databases/images/15-lesson-banner.png b/15-rag-and-vector-databases/images/15-lesson-banner.png new file mode 100644 index 000000000..453f3b61d Binary files /dev/null and b/15-rag-and-vector-databases/images/15-lesson-banner.png differ diff --git a/16-open-source-models/README.md b/16-open-source-models/README.md index 20e03358c..19f9c69b1 100644 --- a/16-open-source-models/README.md +++ b/16-open-source-models/README.md @@ -1,3 +1,5 @@ +[![Open Source Models](./images/16-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson16-gh) + ## Introduction The world of open-source LLMs is exciting and constantly evolving. This lesson aims to provide an in-depth look at open source models. If you are looking for information on how proprietary models compare to open source models, go to the ["Exploring and Comparing Different LLMs" lesson](../02-exploring-and-comparing-different-llms/README.md?WT.mc_id=academic-105485-koreyst). This lesson will also cover the topic of fine-tuning but a more detailed explanation can be found in the ["Fine-Tuning LLMs" lesson](../18-fine-tuning/README.md?WT.mc_id=academic-105485-koreyst). diff --git a/16-open-source-models/images/16-lesson-banner.png b/16-open-source-models/images/16-lesson-banner.png new file mode 100644 index 000000000..251983038 Binary files /dev/null and b/16-open-source-models/images/16-lesson-banner.png differ diff --git a/17-ai-agents/README.md b/17-ai-agents/README.md index 93f8f5de3..752cd1d24 100644 --- a/17-ai-agents/README.md +++ b/17-ai-agents/README.md @@ -1,3 +1,5 @@ +[![Open Source Models](./images/17-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson17-gh) + ## Introduction AI Agents represent an exciting development in Generative AI, enabling Large Language Models (LLMs) to evolve from assistants into agents capable of taking actions. AI Agent frameworks enable developers to create applications that give LLMs access to tools and state management. These frameworks also enhance visibility, allowing users and developers to monitor the actions planned by LLMs, thereby improving experience management. diff --git a/17-ai-agents/images/17-lesson-banner.png b/17-ai-agents/images/17-lesson-banner.png new file mode 100644 index 000000000..991619c9d Binary files /dev/null and b/17-ai-agents/images/17-lesson-banner.png differ diff --git a/18-fine-tuning/README.md b/18-fine-tuning/README.md index 022e4907a..2243d4299 100644 --- a/18-fine-tuning/README.md +++ b/18-fine-tuning/README.md @@ -1,3 +1,5 @@ +[![Open Source Models](./img/18-lesson-banner.png?WT.mc_id=academic-105485-koreyst)](https://aka.ms/gen-ai-lesson18-gh) + # Fine-Tuning Your LLM Using large language models to build generative AI applications comes with new challenges. A key issue is ensuring response quality (accuracy and relevance) in content generated by the model for a given user request. In previous lessons, we discussed techniques like prompt engineering and retrieval-augmented generation that try to solve the problem by _modifying the prompt input_ to the existing model. @@ -73,14 +75,14 @@ To fine-tune a pre-trained model, you need to have: The following resources provide step-by-step tutorials to walk you through a real example using a selected model with a curated dataset. To work through these tutorials, you need an account on the specific provider, along with access to the relevant model and datasets. -| Provider | Tutorial | Description | -| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| OpenAI | [How to fine-tune chat models](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb?WT.mc_id=academic-105485-koreyst) | Learn to fine-tune a `gpt-35-turbo` for a specific domain ("recipe assistant") by preparing training data, running the fine-tuning job, and using the fine-tuned model for inference. | +| Provider | Tutorial | Description | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| OpenAI | [How to fine-tune chat models](https://github.com/openai/openai-cookbook/blob/main/examples/How_to_finetune_chat_models.ipynb?WT.mc_id=academic-105485-koreyst) | Learn to fine-tune a `gpt-35-turbo` for a specific domain ("recipe assistant") by preparing training data, running the fine-tuning job, and using the fine-tuned model for inference. | | Azure OpenAI | [GPT 3.5 Turbo fine-tuning tutorial](https://learn.microsoft.com/azure/ai-services/openai/tutorials/fine-tune?tabs=python-new%2Ccommand-line?WT.mc_id=academic-105485-koreyst) | Learn to fine-tune a `gpt-35-turbo-0613` model **on Azure** by taking steps to create & upload training data, run the fine-tuning job. Deploy & use the new model. | -| Hugging Face | [Fine-tuning LLMs with Hugging Face](https://www.philschmid.de/fine-tune-llms-in-2024-with-trl?WT.mc_id=academic-105485-koreyst) | This blog post walks you fine-tuning an _open LLM_ (ex: `CodeLlama 7B`) using the [transformers](https://huggingface.co/docs/transformers/index?WT.mc_id=academic-105485-koreyst) library & [Transformer Reinforcement Learning (TRL)](https://huggingface.co/docs/trl/index?WT.mc_id=academic-105485-koreyst]) with open [datasets](https://huggingface.co/docs/datasets/index?WT.mc_id=academic-105485-koreyst) on Hugging Face. | -| | | | -| 🤗 AutoTrain | [Fine-tuning LLMs with AutoTrain](https://github.com/huggingface/autotrain-advanced/) | AutoTrain (or AutoTrain Advanced) is a python library developed by Hugging Face that allows finetuning for many different tasks including LLM finetuning. AutoTrain is a no-code solution and finetuning can be done in your own cloud, on Hugging Face Spaces or locally. It supports both a web-based GUI, CLI and training via yaml config files. | -| | | | +| Hugging Face | [Fine-tuning LLMs with Hugging Face](https://www.philschmid.de/fine-tune-llms-in-2024-with-trl?WT.mc_id=academic-105485-koreyst) | This blog post walks you fine-tuning an _open LLM_ (ex: `CodeLlama 7B`) using the [transformers](https://huggingface.co/docs/transformers/index?WT.mc_id=academic-105485-koreyst) library & [Transformer Reinforcement Learning (TRL)](https://huggingface.co/docs/trl/index?WT.mc_id=academic-105485-koreyst]) with open [datasets](https://huggingface.co/docs/datasets/index?WT.mc_id=academic-105485-koreyst) on Hugging Face. | +| | | | +| 🤗 AutoTrain | [Fine-tuning LLMs with AutoTrain](https://github.com/huggingface/autotrain-advanced/) | AutoTrain (or AutoTrain Advanced) is a python library developed by Hugging Face that allows finetuning for many different tasks including LLM finetuning. AutoTrain is a no-code solution and finetuning can be done in your own cloud, on Hugging Face Spaces or locally. It supports both a web-based GUI, CLI and training via yaml config files. | +| | | | ## Assignment diff --git a/18-fine-tuning/img/18-lesson-banner.png b/18-fine-tuning/img/18-lesson-banner.png new file mode 100644 index 000000000..dc6376c0a Binary files /dev/null and b/18-fine-tuning/img/18-lesson-banner.png differ diff --git a/README.md b/README.md index 4cec2b308..97dc28f47 100644 --- a/README.md +++ b/README.md @@ -61,28 +61,27 @@ Do you have suggestions or found spelling or code errors? [Raise an issue](https ## 🗃️ Lessons -| # | **Lesson Link** | **Description** | **Video** | **Extra Learning** | -|----|----------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------| -| 00 | [Course Setup](./00-course-setup/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** How to Setup Your Development Environment | Coming Soon | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 01 | [Introduction to Generative AI and LLMs](./01-introduction-to-genai/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** Understanding what Generative AI is and how Large Language Models (LLMs) work. | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/introduction-to-generative-ai-and-llms-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 02 | [Exploring and comparing different LLMs](./02-exploring-and-comparing-different-llms/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** How to select the right model for your use case | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/exploring-and-comparing-different-llms-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 03 | [Using Generative AI Responsibly](./03-using-generative-ai-responsibly/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** How to build Generative AI Applications responsibly | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/using-generative-ai-responsibly-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 04 | [Understanding Prompt Engineering Fundamentals](./04-prompt-engineering-fundamentals/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** Hands-on Prompt Engineering Best Practices | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/understanding-prompt-engineering-fundamentals-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 05 | [Creating Advanced Prompts](./05-advanced-prompts/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** How to apply prompt engineering techniques that improve the outcome of your prompts. | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/creating-advanced-prompts-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 06 | [Building Text Generation Applications](./06-text-generation-apps/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** A text generation app using Azure OpenAI / OpenAI API | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/building-text-generation-applications-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 07 | [Building Chat Applications](./07-building-chat-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** Techniques for efficiently building and integrating chat applications. | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/building-chat-applications-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 08 | [Building Search Apps Vector Databases](./08-building-search-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** A search application that uses Embeddings to search for data. | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/building-search-apps-vector-databases-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 09 | [Building Image Generation Applications](./09-building-image-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** A image generation application | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/building-image-generation-applications-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 10 | [Building Low Code AI Applications](./10-building-low-code-ai-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** A Generative AI application using Low Code tools | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/building-low-code-ai-applications-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 11 | [Integrating External Applications with Function Calling](./11-integrating-with-function-calling/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** What is function calling and its use cases for applications | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/integrating-external-applications-with-function-calling-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 12 | [Designing UX for AI Applications](./12-designing-ux-for-ai-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** How to apply UX design principles when developing Generative AI Applications | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/designing-ux-for-ai-applications-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 13 | [Securing Your Generative AI Applications](./13-securing-ai-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** The threats and risks to AI systems and methods to secure these systems. | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/securing-your-generative-ai-applications-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 14 | [The Generative AI Application Lifecycle](./14-the-generative-ai-application-lifecycle/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** The tools and metrics to manage the LLM Lifecycle and LLMOps | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/the-generative-ai-application-lifecycle-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 15 | [Retrieval Augmented Generation (RAG) and Vector Databases](./15-rag-and-vector-databases/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** An application using a RAG Framework to retrieve embeddings from a Vector Databases | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/retrieval-augmented-generation-rag-and-vector-databases-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 16 | [Open Source Models and Hugging Face](./16-open-source-models/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** An application using open source models available on Hugging Face | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/open-source-models-and-hugging-face-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 17 | [AI Agents](./17-ai-agents/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** An application using an AI Agent Framework | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/ai-agents-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | -| 18 | [Fine-Tuning LLMs](./18-fine-tuning/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** The what, why and how of fine-tuning LLMs | [Video](https://learn.microsoft.com/shows/generative-ai-for-beginners/finetuning-llms-generative-ai-for-beginners?WT.mc_id=academic-105485-koreyst) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | - +| # | **Lesson Link** | **Description** | **Video** | **Extra Learning** | +| --- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------ | +| 00 | [Course Setup](./00-course-setup/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** How to Setup Your Development Environment | Coming Soon | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 01 | [Introduction to Generative AI and LLMs](./01-introduction-to-genai/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** Understanding what Generative AI is and how Large Language Models (LLMs) work. | [Video](https://aka.ms/gen-ai-lesson-1-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 02 | [Exploring and comparing different LLMs](./02-exploring-and-comparing-different-llms/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** How to select the right model for your use case | [Video](https://aka.ms/gen-ai-lesson2-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 03 | [Using Generative AI Responsibly](./03-using-generative-ai-responsibly/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** How to build Generative AI Applications responsibly | [Video](https://aka.ms/gen-ai-lesson3-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 04 | [Understanding Prompt Engineering Fundamentals](./04-prompt-engineering-fundamentals/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** Hands-on Prompt Engineering Best Practices | [Video](https://aka.ms/gen-ai-lesson4-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 05 | [Creating Advanced Prompts](./05-advanced-prompts/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** How to apply prompt engineering techniques that improve the outcome of your prompts. | [Video](https://aka.ms/gen-ai-lesson5-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 06 | [Building Text Generation Applications](./06-text-generation-apps/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** A text generation app using Azure OpenAI / OpenAI API | [Video](https://aka.ms/gen-ai-lesson6-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 07 | [Building Chat Applications](./07-building-chat-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** Techniques for efficiently building and integrating chat applications. | [Video](https://aka.ms/gen-ai-lessons7-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 08 | [Building Search Apps Vector Databases](./08-building-search-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** A search application that uses Embeddings to search for data. | [Video](https://aka.ms/gen-ai-lesson8-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 09 | [Building Image Generation Applications](./09-building-image-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** A image generation application | [Video](https://aka.ms/gen-ai-lesson9-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 10 | [Building Low Code AI Applications](./10-building-low-code-ai-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** A Generative AI application using Low Code tools | [Video](https://aka.ms/gen-ai-lesson10-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 11 | [Integrating External Applications with Function Calling](./11-integrating-with-function-calling/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** What is function calling and its use cases for applications | [Video](https://aka.ms/gen-ai-lesson11-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 12 | [Designing UX for AI Applications](./12-designing-ux-for-ai-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** How to apply UX design principles when developing Generative AI Applications | [Video](https://aka.ms/gen-ai-lesson12-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 13 | [Securing Your Generative AI Applications](./13-securing-ai-applications/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** The threats and risks to AI systems and methods to secure these systems. | [Video](https://aka.ms/gen-ai-lesson13-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 14 | [The Generative AI Application Lifecycle](./14-the-generative-ai-application-lifecycle/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** The tools and metrics to manage the LLM Lifecycle and LLMOps | [Video](https://aka.ms/gen-ai-lesson14-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 15 | [Retrieval Augmented Generation (RAG) and Vector Databases](./15-rag-and-vector-databases/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** An application using a RAG Framework to retrieve embeddings from a Vector Databases | [Video](https://aka.ms/gen-ai-lesson15-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 16 | [Open Source Models and Hugging Face](./16-open-source-models/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** An application using open source models available on Hugging Face | [Video](https://aka.ms/gen-ai-lesson16-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 17 | [AI Agents](./17-ai-agents/README.md?WT.mc_id=academic-105485-koreyst) | **Build:** An application using an AI Agent Framework | [Video](https://aka.ms/gen-ai-lesson17-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | +| 18 | [Fine-Tuning LLMs](./18-fine-tuning/README.md?WT.mc_id=academic-105485-koreyst) | **Learn:** The what, why and how of fine-tuning LLMs | [Video](https://aka.ms/gen-ai-lesson18-gh) | [Learn More](https://aka.ms/genai-collection?WT.mc_id=academic-105485-koreyst) | ### 🌟 Special thanks