diff --git "a/archive/AI_Engineering/RAG\354\231\200_\354\227\220\354\235\264\354\240\204\355\212\270_\355\224\204\353\240\210\354\240\240\355\205\214\354\235\264\354\205\230.pptx" "b/archive/AI_Engineering/RAG\354\231\200_\354\227\220\354\235\264\354\240\204\355\212\270_\355\224\204\353\240\210\354\240\240\355\205\214\354\235\264\354\205\230.pptx" new file mode 100644 index 00000000..ad9c7c49 Binary files /dev/null and "b/archive/AI_Engineering/RAG\354\231\200_\354\227\220\354\235\264\354\240\204\355\212\270_\355\224\204\353\240\210\354\240\240\355\205\214\354\235\264\354\205\230.pptx" differ diff --git "a/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/13.LLM\354\232\264\354\230\201\355\225\230\352\270\260.pdf" "b/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/13.LLM\354\232\264\354\230\201\355\225\230\352\270\260.pdf" new file mode 100644 index 00000000..a0fee660 Binary files /dev/null and "b/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/13.LLM\354\232\264\354\230\201\355\225\230\352\270\260.pdf" differ diff --git "a/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/CH15_LLM_\354\227\220\354\235\264\354\240\204\355\212\270_song.ipynb" "b/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/CH15_LLM_\354\227\220\354\235\264\354\240\204\355\212\270_song.ipynb" index 830637e3..615be177 100644 --- "a/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/CH15_LLM_\354\227\220\354\235\264\354\240\204\355\212\270_song.ipynb" +++ "b/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/CH15_LLM_\354\227\220\354\235\264\354\240\204\355\212\270_song.ipynb" @@ -19,7 +19,7 @@ } ], "source": [ - "!pip install \"pyautogen[retrievechat]==0.2.6\" -qqq" + "!pip install \"ag2[retrievechat]==0.2.6\" -qqq" ] }, { @@ -226,7 +226,7 @@ "
\n", "\"AutoGen\n", "\n", - "[![Twitter](https://img.shields.io/twitter/url/https/twitter.com/cloudposse.svg?style=social&label=Follow%20%40pyautogen)](https://twitter.com/pyautogen)\n", + "[![Twitter](https://img.shields.io/twitter/url/https/twitter.com/cloudposse.svg?style=social&label=Follow%20%40ag2)](https://twitter.com/ag2)\n", "[![LinkedIn](https://img.shields.io/badge/LinkedIn-Company?style=flat&logo=linkedin&logoColor=white)](https://www.linkedin.com/company/105812540)\n", "[![Discord](https://img.shields.io/badge/discord-chat-green?logo=discord)](https://aka.ms/autogen-discord)\n", "[![Documentation](https://img.shields.io/badge/Documentation-AutoGen-blue?logo=read-the-docs)](https://microsoft.github.io/autogen/)\n", @@ -235,7 +235,7 @@ "
\n", "\n", "
\n", - " Important: This is the official project. We are not affiliated with any fork or startup. See our statement.\n", + " Important: This is the official project. We are not affiliated with any fork or startup. See our statement.\n", "
\n", "\n", "# AutoGen\n", diff --git "a/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/llm-main/15\354\236\245/chapter_15.ipynb" "b/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/llm-main/15\354\236\245/chapter_15.ipynb" index 0404cab0..bb077223 100644 --- "a/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/llm-main/15\354\236\245/chapter_15.ipynb" +++ "b/archive/LLM\354\235\204_\355\231\234\354\232\251\355\225\234_\354\213\244\354\240\204_AI_\354\225\240\355\224\214\353\246\254\354\274\200\354\235\264\354\205\230_\352\260\234\353\260\234/llm-main/15\354\236\245/chapter_15.ipynb" @@ -1,613 +1,613 @@ -{ - "cells": [ - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "2tSxuD4vTjdb" - }, - "outputs": [], - "source": [ - "!pip install \"pyautogen[retrievechat]==0.2.6\" -qqq" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.2 OpenAI API 키 설정" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "yJy91vfTTl-x" - }, - "outputs": [], - "source": [ - "import json\n", - "\n", - "openai_api_key = \"자신의 API 키 입력\"\n", - "\n", - "with open('OAI_CONFIG_LIST.json', 'w') as f:\n", - " config_list = [\n", - " {\n", - " \"model\": \"gpt-4-turbo-preview\",\n", - " \"api_key\": openai_api_key\n", - " },\n", - " {\n", - " \"model\": \"gpt-4o\",\n", - " \"api_key\": openai_api_key,\n", - " },\n", - " {\n", - " \"model\": \"dall-e-3\",\n", - " \"api_key\": openai_api_key,\n", - " }\n", - "]\n", - " json.dump(config_list, f)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.3 에이전트에 사용할 설정 불러오기" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "6x8D6rR1Trs8" - }, - "outputs": [], - "source": [ - "import autogen\n", - "\n", - "config_list = autogen.config_list_from_json(\n", - " \"OAI_CONFIG_LIST.json\",\n", - " file_location=\".\",\n", - " filter_dict={\n", - " \"model\": [\"gpt-4-turbo-preview\"],\n", - " },\n", - ")\n", - "\n", - "llm_config = {\n", - " \"config_list\": config_list,\n", - " \"temperature\": 0,\n", - "}" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.4 AutoGen의 핵심 구성요소인 UserProxyAgent와 AssistantAgent" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "Vs1-f-W0TtnO" - }, - "outputs": [], - "source": [ - "from autogen import AssistantAgent, UserProxyAgent\n", - "\n", - "assistant = AssistantAgent(\"assistant\", llm_config=llm_config)\n", - "user_proxy = UserProxyAgent(\"user_proxy\",\n", - " is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n", - " human_input_mode=\"NEVER\",\n", - " code_execution_config={\"work_dir\": \"coding\", \"use_docker\": False})" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.5 삼성전자의 3개월 주식 가격 그래프를 그리는 작업 실행" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "swwqTg5ITvqC" - }, - "outputs": [], - "source": [ - "user_proxy.initiate_chat(assistant, message=\"\"\"\n", - "삼성전자의 지난 3개월 주식 가격 그래프를 그려서 samsung_stock_price.png 파일로 저장해줘.\n", - "plotly 라이브러리를 사용하고 그래프 아래를 투명한 녹색으로 채워줘.\n", - "값을 잘 확인할 수 있도록 y축은 구간 최소값에서 시작하도록 해줘.\n", - "이미지 비율은 보기 좋게 적절히 설정해줘.\n", - "\"\"\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.6 RAG 에이전트 클래스를 사용한 작업 실행" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "ag8s81nTTyLB" - }, - "outputs": [], - "source": [ - "import autogen\n", - "from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent\n", - "from autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent\n", - "\n", - "assistant = RetrieveAssistantAgent(\n", - " name=\"assistant\",\n", - " system_message=\"You are a helpful assistant.\",\n", - " llm_config=llm_config,\n", - ")\n", - "\n", - "ragproxyagent = RetrieveUserProxyAgent(\n", - " name=\"ragproxyagent\",\n", - " retrieve_config={\n", - " \"task\": \"qa\",\n", - " \"docs_path\": \"https://raw.githubusercontent.com/microsoft/autogen/main/README.md\",\n", - " \"collection_name\": \"default-sentence-transformers\"\n", - " },\n", - ")\n", - "\n", - "assistant.reset()\n", - "ragproxyagent.initiate_chat(assistant, problem=\"AutoGen이 뭐야?\")\n", - "\n", - "# assistant (to ragproxyagent):\n", - "# AutoGen은 여러 에이전트가 상호 대화하여 작업을 해결할 수 있는 LLM(Large Language Model) 애플리케이션 개발을 가능하게 하는 프레임워크입니다. AutoGen 에이전트는 사용자 정의 가능하며, 대화 가능하고, 인간 참여를 원활하게 허용합니다. LLM, 인간 입력, 도구의 조합을 사용하는 다양한 모드에서 작동할 수 있습니다." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.7 외부 정보를 활용하지 못하는 기본 에이전트의 답변" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "kXZMtrQMTzla" - }, - "outputs": [], - "source": [ - "assistant.reset()\n", - "userproxyagent = autogen.UserProxyAgent(\n", - " name=\"userproxyagent\",\n", - ")\n", - "userproxyagent.initiate_chat(assistant, message=\"Autogen이 뭐야?\")\n", - "\n", - "# assistant (to userproxyagent):\n", - "# \"Autogen\"은 자동 생성을 의미하는 용어로, 주로 컴퓨터 프로그래밍에서 사용됩니다. 이는 코드, 문서, 또는 다른 데이터를 자동으로 생성하는 프로세스를 가리킵니다. 이는 반복적인 작업을 줄이고, 효율성을 높이며, 오류를 줄일 수 있습니다. 특정 컨텍스트에 따라 \"Autogen\"의 정확한 의미는 다를 수 있습니다." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.8 OpenAI 임베딩 모델을 사용하도록 설정하기" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "TxmtFFciT26Z" - }, - "outputs": [], - "source": [ - "from chromadb.utils import embedding_functions\n", - "\n", - "openai_ef = embedding_functions.OpenAIEmbeddingFunction(\n", - " api_key=openai_api_key,\n", - " model_name=\"text-embedding-3-small\"\n", - " )\n", - "\n", - "ragproxyagent = RetrieveUserProxyAgent(\n", - " name=\"ragproxyagent\",\n", - " is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n", - " human_input_mode=\"NEVER\",\n", - " retrieve_config={\n", - " \"task\": \"qa\",\n", - " \"docs_path\": \"https://raw.githubusercontent.com/microsoft/autogen/main/README.md\",\n", - " \"embedding_function\": openai_ef,\n", - " \"collection_name\": \"openai-embedding-3\",\n", - " },\n", - ")\n", - "\n", - "assistant.reset()\n", - "ragproxyagent.initiate_chat(assistant, problem=\"Autogen이 뭐야?\")\n", - "\n", - "# assistant (to ragproxyagent):\n", - "# AutoGen은 여러 에이전트가 상호 대화하여 작업을 해결할 수 있는 LLM(Large Language Model) 애플리케이션 개발을 가능하게 하는 프레임워크입니다. AutoGen 에이전트는 사용자 정의 가능하며, 대화 가능하고, 인간 참여를 원활하게 허용합니다. LLM, 인간 입력, 도구의 조합을 사용하는 다양한 모드에서 작동할 수 있습니다." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.9 대화에 참여할 에이전트" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "pTJYh__XT5MV" - }, - "outputs": [], - "source": [ - "def termination_msg(x):\n", - " return isinstance(x, dict) and \"TERMINATE\" == str(x.get(\"content\", \"\"))[-9:].upper()\n", - "\n", - "# RAG를 사용하지 않는 사용자 역할 에이전트\n", - "user = autogen.UserProxyAgent(\n", - " name=\"Admin\",\n", - " is_termination_msg=termination_msg,\n", - " human_input_mode=\"NEVER\",\n", - " system_message=\"The boss who ask questions and give tasks.\",\n", - " code_execution_config=False,\n", - " default_auto_reply=\"Reply `TERMINATE` if the task is done.\",\n", - ")\n", - "# RAG를 사용하는 사용자 역할 에이전트\n", - "user_rag = RetrieveUserProxyAgent(\n", - " name=\"Admin_RAG\",\n", - " is_termination_msg=termination_msg,\n", - " system_message=\"Assistant who has extra content retrieval power for solving difficult problems.\",\n", - " human_input_mode=\"NEVER\",\n", - " max_consecutive_auto_reply=3,\n", - " code_execution_config=False,\n", - " retrieve_config={\n", - " \"task\": \"code\",\n", - " \"docs_path\": \"https://raw.githubusercontent.com/microsoft/autogen/main/samples/apps/autogen-studio/README.md\",\n", - " \"chunk_token_size\": 1000,\n", - " \"collection_name\": \"groupchat-rag\",\n", - " }\n", - ")\n", - "# 프로그래머 역할의 에이전트\n", - "coder = AssistantAgent(\n", - " name=\"Senior_Python_Engineer\",\n", - " is_termination_msg=termination_msg,\n", - " system_message=\"You are a senior python engineer. Reply `TERMINATE` in the end when everything is done.\",\n", - " llm_config=llm_config,\n", - ")\n", - "# 프로덕트 매니저 역할의 에이전트\n", - "pm = autogen.AssistantAgent(\n", - " name=\"Product_Manager\",\n", - " is_termination_msg=termination_msg,\n", - " system_message=\"You are a product manager. Reply `TERMINATE` in the end when everything is done.\",\n", - " llm_config=llm_config,\n", - ")\n", - "\n", - "PROBLEM = \"AutoGen Studio는 무엇이고 AutoGen Studio로 어떤 제품을 만들 수 있을까?\"" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.10 RAG 사용 여부에 따른 2개의 그룹챗 정의 및 실행" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "f8TsOdwOT69h" - }, - "outputs": [], - "source": [ - "def _reset_agents():\n", - " user.reset()\n", - " user_rag.reset()\n", - " coder.reset()\n", - " pm.reset()\n", - "\n", - "def rag_chat():\n", - " _reset_agents()\n", - " groupchat = autogen.GroupChat(\n", - " agents=[user_rag, coder, pm],\n", - " messages=[], max_round=12, speaker_selection_method=\"round_robin\"\n", - " )\n", - " manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)\n", - "\n", - " user_rag.initiate_chat(\n", - " manager,\n", - " problem=PROBLEM,\n", - " )\n", - "\n", - "def norag_chat():\n", - " _reset_agents()\n", - " groupchat = autogen.GroupChat(\n", - " agents=[user, coder, pm],\n", - " messages=[],\n", - " max_round=12,\n", - " speaker_selection_method=\"auto\",\n", - " allow_repeat_speaker=False,\n", - " )\n", - " manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)\n", - "\n", - " user.initiate_chat(\n", - " manager,\n", - " message=PROBLEM,\n", - " )" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.11 2개의 그룹챗을 실행한 결과 비교" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "cqTstaGdT8jK" - }, - "outputs": [], - "source": [ - "norag_chat()\n", - "# AutoGen Studio는 자동화된 코드 생성 도구입니다. 이 도구를 사용하면 개발자들이 더 빠르게, 더 효율적으로 코드를 작성할 수 있습니다.\n", - "# AutoGen Studio를 사용하면 다양한 유형의 소프트웨어 제품을 만들 수 있습니다. 예를 들어, 웹 애플리케이션, 모바일 애플리케이션, 데스크톱 애플리케이션, API, 데이터베이스 등을 만들 수 있습니다.\n", - "# ..." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "QcFtDRO5W8HM" - }, - "outputs": [], - "source": [ - "rag_chat()\n", - "# AutoGen Studio는 AutoGen 프레임워크를 기반으로 한 AI 앱입니다. 이 앱은 AI 에이전트를 빠르게 프로토타입화하고, 스킬을 향상시키고, 워크플로우로 구성하고, 작업을 완료하기 위해 그들과 상호 작용하는 데 도움을 줍니다. 이 앱은 GitHub의 [microsoft/autogen](https://github.com/microsoft/autogen/tree/main/samples/apps/autogen-studio)에서 코드를 찾을 수 있습니다.\n", - "# AutoGen Studio를 사용하면 다음과 같은 기능을 수행할 수 있습니다:\n", - "# - 에이전트를 구축/구성하고, 그들의 구성(예: 스킬, 온도, 모델, 에이전트 시스템 메시지, 모델 등)을 수정하고, 워크플로우로 구성합니다.\n", - "# ..." - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.12 실습 준비하기" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "ZesPNJIvT-zD" - }, - "outputs": [], - "source": [ - "import os\n", - "import re\n", - "import time\n", - "from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union\n", - "\n", - "import matplotlib.pyplot as plt\n", - "import PIL\n", - "import requests\n", - "from openai import OpenAI\n", - "from PIL import Image\n", - "\n", - "from autogen import Agent, AssistantAgent, ConversableAgent, UserProxyAgent\n", - "from autogen.agentchat.contrib.img_utils import _to_pil, get_image_data\n", - "from autogen.agentchat.contrib.multimodal_conversable_agent import MultimodalConversableAgent\n", - "\n", - "config_list_4o = autogen.config_list_from_json(\n", - " \"OAI_CONFIG_LIST.json\",\n", - " filter_dict={\n", - " \"model\": [\"gpt-4o\"],\n", - " },\n", - ")\n", - "\n", - "config_list_dalle = autogen.config_list_from_json(\n", - " \"OAI_CONFIG_LIST.json\",\n", - " filter_dict={\n", - " \"model\": [\"dall-e-3\"],\n", - " },\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.13 DALLEAgent 정의" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "AHe0sa5oUAjx" - }, - "outputs": [], - "source": [ - "def dalle_call(client, prompt, model=\"dall-e-3\", size=\"1024x1024\", quality=\"standard\", n=1) -> str:\n", - " response = client.images.generate(\n", - " model=model,\n", - " prompt=prompt,\n", - " size=size,\n", - " quality=quality,\n", - " n=n,\n", - " )\n", - " image_url = response.data[0].url\n", - " img_data = get_image_data(image_url)\n", - " return img_data\n", - "\n", - "class DALLEAgent(ConversableAgent):\n", - " def __init__(self, name, llm_config: dict, **kwargs):\n", - " super().__init__(name, llm_config=llm_config, **kwargs)\n", - "\n", - " try:\n", - " config_list = llm_config[\"config_list\"]\n", - " api_key = config_list[0][\"api_key\"]\n", - " except Exception as e:\n", - " print(\"Unable to fetch API Key, because\", e)\n", - " api_key = os.getenv(\"OPENAI_API_KEY\")\n", - " self.client = OpenAI(api_key=api_key)\n", - " self.register_reply([Agent, None], DALLEAgent.generate_dalle_reply)\n", - "\n", - " def generate_dalle_reply(self, messages, sender, config):\n", - " client = self.client if config is None else config\n", - " if client is None:\n", - " return False, None\n", - " if messages is None:\n", - " messages = self._oai_messages[sender]\n", - "\n", - " prompt = messages[-1][\"content\"]\n", - " img_data = dalle_call(client=self.client, prompt=prompt)\n", - " plt.imshow(_to_pil(img_data))\n", - " plt.axis(\"off\")\n", - " plt.show()\n", - " return True, 'result.jpg'" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.14 이미지 생성 에이전트 실행" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "_tA6zvkMUDsg" - }, - "outputs": [], - "source": [ - "painter = DALLEAgent(name=\"Painter\", llm_config={\"config_list\": config_list_dalle})\n", - "\n", - "user_proxy = UserProxyAgent(\n", - " name=\"User_proxy\", system_message=\"A human admin.\", human_input_mode=\"NEVER\", max_consecutive_auto_reply=0\n", - ")\n", - "\n", - "# 이미지 생성 작업 실행하기\n", - "user_proxy.initiate_chat(\n", - " painter,\n", - " message=\"갈색의 털을 가진 귀여운 강아지를 그려줘\",\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.15 이미지를 입력으로 받을 수 있는 GPT-4o 에이전트 생성" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "1dFWqylXUFSH" - }, - "outputs": [], - "source": [ - "image_agent = MultimodalConversableAgent(\n", - " name=\"image-explainer\",\n", - " system_message=\"Explane input image for painter to create similar image.\",\n", - " max_consecutive_auto_reply=10,\n", - " llm_config={\"config_list\": config_list_4o, \"temperature\": 0.5, \"max_tokens\": 1500},\n", - ")\n", - "\n", - "user_proxy = autogen.UserProxyAgent(\n", - " name=\"User_proxy\",\n", - " system_message=\"A human admin.\",\n", - " human_input_mode=\"NEVER\",\n", - " max_consecutive_auto_reply=0,\n", - " code_execution_config=False\n", - ")\n", - "\n", - "groupchat = autogen.GroupChat(agents=[user_proxy, image_agent, painter], messages=[], max_round=12)\n", - "manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.16 유사한 이미지를 생성하도록 에이전트 실행" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "gLpNLFd-UHbd" - }, - "outputs": [], - "source": [ - "user_proxy.initiate_chat(\n", - " manager,\n", - " message=f\"\"\"아래 이미지랑 비슷한 이미지를 만들어줘.\n", - ".\"\"\",\n", - ")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 예제 15.18 멀티 모달 에이전트에 텍스트로 명령" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "id": "iwZAycesUIyy" - }, - "outputs": [], - "source": [ - "user_proxy.initiate_chat(\n", - " manager,\n", - " message=\"갈색의 털을 가진 귀여운 강아지를 그려줘\",\n", - ")" - ] - } - ], - "metadata": { - "colab": { - "provenance": [] - }, - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.11.4" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "2tSxuD4vTjdb" + }, + "outputs": [], + "source": [ + "!pip install \"ag2[retrievechat]==0.2.6\" -qqq" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.2 OpenAI API 키 설정" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "yJy91vfTTl-x" + }, + "outputs": [], + "source": [ + "import json\n", + "\n", + "openai_api_key = \"자신의 API 키 입력\"\n", + "\n", + "with open('OAI_CONFIG_LIST.json', 'w') as f:\n", + " config_list = [\n", + " {\n", + " \"model\": \"gpt-4-turbo-preview\",\n", + " \"api_key\": openai_api_key\n", + " },\n", + " {\n", + " \"model\": \"gpt-4o\",\n", + " \"api_key\": openai_api_key,\n", + " },\n", + " {\n", + " \"model\": \"dall-e-3\",\n", + " \"api_key\": openai_api_key,\n", + " }\n", + "]\n", + " json.dump(config_list, f)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.3 에이전트에 사용할 설정 불러오기" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "6x8D6rR1Trs8" + }, + "outputs": [], + "source": [ + "import autogen\n", + "\n", + "config_list = autogen.config_list_from_json(\n", + " \"OAI_CONFIG_LIST.json\",\n", + " file_location=\".\",\n", + " filter_dict={\n", + " \"model\": [\"gpt-4-turbo-preview\"],\n", + " },\n", + ")\n", + "\n", + "llm_config = {\n", + " \"config_list\": config_list,\n", + " \"temperature\": 0,\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.4 AutoGen의 핵심 구성요소인 UserProxyAgent와 AssistantAgent" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "Vs1-f-W0TtnO" + }, + "outputs": [], + "source": [ + "from autogen import AssistantAgent, UserProxyAgent\n", + "\n", + "assistant = AssistantAgent(\"assistant\", llm_config=llm_config)\n", + "user_proxy = UserProxyAgent(\"user_proxy\",\n", + " is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n", + " human_input_mode=\"NEVER\",\n", + " code_execution_config={\"work_dir\": \"coding\", \"use_docker\": False})" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.5 삼성전자의 3개월 주식 가격 그래프를 그리는 작업 실행" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "swwqTg5ITvqC" + }, + "outputs": [], + "source": [ + "user_proxy.initiate_chat(assistant, message=\"\"\"\n", + "삼성전자의 지난 3개월 주식 가격 그래프를 그려서 samsung_stock_price.png 파일로 저장해줘.\n", + "plotly 라이브러리를 사용하고 그래프 아래를 투명한 녹색으로 채워줘.\n", + "값을 잘 확인할 수 있도록 y축은 구간 최소값에서 시작하도록 해줘.\n", + "이미지 비율은 보기 좋게 적절히 설정해줘.\n", + "\"\"\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.6 RAG 에이전트 클래스를 사용한 작업 실행" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "ag8s81nTTyLB" + }, + "outputs": [], + "source": [ + "import autogen\n", + "from autogen.agentchat.contrib.retrieve_assistant_agent import RetrieveAssistantAgent\n", + "from autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent\n", + "\n", + "assistant = RetrieveAssistantAgent(\n", + " name=\"assistant\",\n", + " system_message=\"You are a helpful assistant.\",\n", + " llm_config=llm_config,\n", + ")\n", + "\n", + "ragproxyagent = RetrieveUserProxyAgent(\n", + " name=\"ragproxyagent\",\n", + " retrieve_config={\n", + " \"task\": \"qa\",\n", + " \"docs_path\": \"https://raw.githubusercontent.com/microsoft/autogen/main/README.md\",\n", + " \"collection_name\": \"default-sentence-transformers\"\n", + " },\n", + ")\n", + "\n", + "assistant.reset()\n", + "ragproxyagent.initiate_chat(assistant, problem=\"AutoGen이 뭐야?\")\n", + "\n", + "# assistant (to ragproxyagent):\n", + "# AutoGen은 여러 에이전트가 상호 대화하여 작업을 해결할 수 있는 LLM(Large Language Model) 애플리케이션 개발을 가능하게 하는 프레임워크입니다. AutoGen 에이전트는 사용자 정의 가능하며, 대화 가능하고, 인간 참여를 원활하게 허용합니다. LLM, 인간 입력, 도구의 조합을 사용하는 다양한 모드에서 작동할 수 있습니다." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.7 외부 정보를 활용하지 못하는 기본 에이전트의 답변" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "kXZMtrQMTzla" + }, + "outputs": [], + "source": [ + "assistant.reset()\n", + "userproxyagent = autogen.UserProxyAgent(\n", + " name=\"userproxyagent\",\n", + ")\n", + "userproxyagent.initiate_chat(assistant, message=\"Autogen이 뭐야?\")\n", + "\n", + "# assistant (to userproxyagent):\n", + "# \"Autogen\"은 자동 생성을 의미하는 용어로, 주로 컴퓨터 프로그래밍에서 사용됩니다. 이는 코드, 문서, 또는 다른 데이터를 자동으로 생성하는 프로세스를 가리킵니다. 이는 반복적인 작업을 줄이고, 효율성을 높이며, 오류를 줄일 수 있습니다. 특정 컨텍스트에 따라 \"Autogen\"의 정확한 의미는 다를 수 있습니다." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.8 OpenAI 임베딩 모델을 사용하도록 설정하기" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "TxmtFFciT26Z" + }, + "outputs": [], + "source": [ + "from chromadb.utils import embedding_functions\n", + "\n", + "openai_ef = embedding_functions.OpenAIEmbeddingFunction(\n", + " api_key=openai_api_key,\n", + " model_name=\"text-embedding-3-small\"\n", + " )\n", + "\n", + "ragproxyagent = RetrieveUserProxyAgent(\n", + " name=\"ragproxyagent\",\n", + " is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n", + " human_input_mode=\"NEVER\",\n", + " retrieve_config={\n", + " \"task\": \"qa\",\n", + " \"docs_path\": \"https://raw.githubusercontent.com/microsoft/autogen/main/README.md\",\n", + " \"embedding_function\": openai_ef,\n", + " \"collection_name\": \"openai-embedding-3\",\n", + " },\n", + ")\n", + "\n", + "assistant.reset()\n", + "ragproxyagent.initiate_chat(assistant, problem=\"Autogen이 뭐야?\")\n", + "\n", + "# assistant (to ragproxyagent):\n", + "# AutoGen은 여러 에이전트가 상호 대화하여 작업을 해결할 수 있는 LLM(Large Language Model) 애플리케이션 개발을 가능하게 하는 프레임워크입니다. AutoGen 에이전트는 사용자 정의 가능하며, 대화 가능하고, 인간 참여를 원활하게 허용합니다. LLM, 인간 입력, 도구의 조합을 사용하는 다양한 모드에서 작동할 수 있습니다." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.9 대화에 참여할 에이전트" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "pTJYh__XT5MV" + }, + "outputs": [], + "source": [ + "def termination_msg(x):\n", + " return isinstance(x, dict) and \"TERMINATE\" == str(x.get(\"content\", \"\"))[-9:].upper()\n", + "\n", + "# RAG를 사용하지 않는 사용자 역할 에이전트\n", + "user = autogen.UserProxyAgent(\n", + " name=\"Admin\",\n", + " is_termination_msg=termination_msg,\n", + " human_input_mode=\"NEVER\",\n", + " system_message=\"The boss who ask questions and give tasks.\",\n", + " code_execution_config=False,\n", + " default_auto_reply=\"Reply `TERMINATE` if the task is done.\",\n", + ")\n", + "# RAG를 사용하는 사용자 역할 에이전트\n", + "user_rag = RetrieveUserProxyAgent(\n", + " name=\"Admin_RAG\",\n", + " is_termination_msg=termination_msg,\n", + " system_message=\"Assistant who has extra content retrieval power for solving difficult problems.\",\n", + " human_input_mode=\"NEVER\",\n", + " max_consecutive_auto_reply=3,\n", + " code_execution_config=False,\n", + " retrieve_config={\n", + " \"task\": \"code\",\n", + " \"docs_path\": \"https://raw.githubusercontent.com/microsoft/autogen/main/samples/apps/autogen-studio/README.md\",\n", + " \"chunk_token_size\": 1000,\n", + " \"collection_name\": \"groupchat-rag\",\n", + " }\n", + ")\n", + "# 프로그래머 역할의 에이전트\n", + "coder = AssistantAgent(\n", + " name=\"Senior_Python_Engineer\",\n", + " is_termination_msg=termination_msg,\n", + " system_message=\"You are a senior python engineer. Reply `TERMINATE` in the end when everything is done.\",\n", + " llm_config=llm_config,\n", + ")\n", + "# 프로덕트 매니저 역할의 에이전트\n", + "pm = autogen.AssistantAgent(\n", + " name=\"Product_Manager\",\n", + " is_termination_msg=termination_msg,\n", + " system_message=\"You are a product manager. Reply `TERMINATE` in the end when everything is done.\",\n", + " llm_config=llm_config,\n", + ")\n", + "\n", + "PROBLEM = \"AutoGen Studio는 무엇이고 AutoGen Studio로 어떤 제품을 만들 수 있을까?\"" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.10 RAG 사용 여부에 따른 2개의 그룹챗 정의 및 실행" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "f8TsOdwOT69h" + }, + "outputs": [], + "source": [ + "def _reset_agents():\n", + " user.reset()\n", + " user_rag.reset()\n", + " coder.reset()\n", + " pm.reset()\n", + "\n", + "def rag_chat():\n", + " _reset_agents()\n", + " groupchat = autogen.GroupChat(\n", + " agents=[user_rag, coder, pm],\n", + " messages=[], max_round=12, speaker_selection_method=\"round_robin\"\n", + " )\n", + " manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)\n", + "\n", + " user_rag.initiate_chat(\n", + " manager,\n", + " problem=PROBLEM,\n", + " )\n", + "\n", + "def norag_chat():\n", + " _reset_agents()\n", + " groupchat = autogen.GroupChat(\n", + " agents=[user, coder, pm],\n", + " messages=[],\n", + " max_round=12,\n", + " speaker_selection_method=\"auto\",\n", + " allow_repeat_speaker=False,\n", + " )\n", + " manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)\n", + "\n", + " user.initiate_chat(\n", + " manager,\n", + " message=PROBLEM,\n", + " )" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.11 2개의 그룹챗을 실행한 결과 비교" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "cqTstaGdT8jK" + }, + "outputs": [], + "source": [ + "norag_chat()\n", + "# AutoGen Studio는 자동화된 코드 생성 도구입니다. 이 도구를 사용하면 개발자들이 더 빠르게, 더 효율적으로 코드를 작성할 수 있습니다.\n", + "# AutoGen Studio를 사용하면 다양한 유형의 소프트웨어 제품을 만들 수 있습니다. 예를 들어, 웹 애플리케이션, 모바일 애플리케이션, 데스크톱 애플리케이션, API, 데이터베이스 등을 만들 수 있습니다.\n", + "# ..." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "QcFtDRO5W8HM" + }, + "outputs": [], + "source": [ + "rag_chat()\n", + "# AutoGen Studio는 AutoGen 프레임워크를 기반으로 한 AI 앱입니다. 이 앱은 AI 에이전트를 빠르게 프로토타입화하고, 스킬을 향상시키고, 워크플로우로 구성하고, 작업을 완료하기 위해 그들과 상호 작용하는 데 도움을 줍니다. 이 앱은 GitHub의 [microsoft/autogen](https://github.com/microsoft/autogen/tree/main/samples/apps/autogen-studio)에서 코드를 찾을 수 있습니다.\n", + "# AutoGen Studio를 사용하면 다음과 같은 기능을 수행할 수 있습니다:\n", + "# - 에이전트를 구축/구성하고, 그들의 구성(예: 스킬, 온도, 모델, 에이전트 시스템 메시지, 모델 등)을 수정하고, 워크플로우로 구성합니다.\n", + "# ..." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.12 실습 준비하기" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "ZesPNJIvT-zD" + }, + "outputs": [], + "source": [ + "import os\n", + "import re\n", + "import time\n", + "from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union\n", + "\n", + "import matplotlib.pyplot as plt\n", + "import PIL\n", + "import requests\n", + "from openai import OpenAI\n", + "from PIL import Image\n", + "\n", + "from autogen import Agent, AssistantAgent, ConversableAgent, UserProxyAgent\n", + "from autogen.agentchat.contrib.img_utils import _to_pil, get_image_data\n", + "from autogen.agentchat.contrib.multimodal_conversable_agent import MultimodalConversableAgent\n", + "\n", + "config_list_4o = autogen.config_list_from_json(\n", + " \"OAI_CONFIG_LIST.json\",\n", + " filter_dict={\n", + " \"model\": [\"gpt-4o\"],\n", + " },\n", + ")\n", + "\n", + "config_list_dalle = autogen.config_list_from_json(\n", + " \"OAI_CONFIG_LIST.json\",\n", + " filter_dict={\n", + " \"model\": [\"dall-e-3\"],\n", + " },\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.13 DALLEAgent 정의" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "AHe0sa5oUAjx" + }, + "outputs": [], + "source": [ + "def dalle_call(client, prompt, model=\"dall-e-3\", size=\"1024x1024\", quality=\"standard\", n=1) -> str:\n", + " response = client.images.generate(\n", + " model=model,\n", + " prompt=prompt,\n", + " size=size,\n", + " quality=quality,\n", + " n=n,\n", + " )\n", + " image_url = response.data[0].url\n", + " img_data = get_image_data(image_url)\n", + " return img_data\n", + "\n", + "class DALLEAgent(ConversableAgent):\n", + " def __init__(self, name, llm_config: dict, **kwargs):\n", + " super().__init__(name, llm_config=llm_config, **kwargs)\n", + "\n", + " try:\n", + " config_list = llm_config[\"config_list\"]\n", + " api_key = config_list[0][\"api_key\"]\n", + " except Exception as e:\n", + " print(\"Unable to fetch API Key, because\", e)\n", + " api_key = os.getenv(\"OPENAI_API_KEY\")\n", + " self.client = OpenAI(api_key=api_key)\n", + " self.register_reply([Agent, None], DALLEAgent.generate_dalle_reply)\n", + "\n", + " def generate_dalle_reply(self, messages, sender, config):\n", + " client = self.client if config is None else config\n", + " if client is None:\n", + " return False, None\n", + " if messages is None:\n", + " messages = self._oai_messages[sender]\n", + "\n", + " prompt = messages[-1][\"content\"]\n", + " img_data = dalle_call(client=self.client, prompt=prompt)\n", + " plt.imshow(_to_pil(img_data))\n", + " plt.axis(\"off\")\n", + " plt.show()\n", + " return True, 'result.jpg'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.14 이미지 생성 에이전트 실행" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "_tA6zvkMUDsg" + }, + "outputs": [], + "source": [ + "painter = DALLEAgent(name=\"Painter\", llm_config={\"config_list\": config_list_dalle})\n", + "\n", + "user_proxy = UserProxyAgent(\n", + " name=\"User_proxy\", system_message=\"A human admin.\", human_input_mode=\"NEVER\", max_consecutive_auto_reply=0\n", + ")\n", + "\n", + "# 이미지 생성 작업 실행하기\n", + "user_proxy.initiate_chat(\n", + " painter,\n", + " message=\"갈색의 털을 가진 귀여운 강아지를 그려줘\",\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.15 이미지를 입력으로 받을 수 있는 GPT-4o 에이전트 생성" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "1dFWqylXUFSH" + }, + "outputs": [], + "source": [ + "image_agent = MultimodalConversableAgent(\n", + " name=\"image-explainer\",\n", + " system_message=\"Explane input image for painter to create similar image.\",\n", + " max_consecutive_auto_reply=10,\n", + " llm_config={\"config_list\": config_list_4o, \"temperature\": 0.5, \"max_tokens\": 1500},\n", + ")\n", + "\n", + "user_proxy = autogen.UserProxyAgent(\n", + " name=\"User_proxy\",\n", + " system_message=\"A human admin.\",\n", + " human_input_mode=\"NEVER\",\n", + " max_consecutive_auto_reply=0,\n", + " code_execution_config=False\n", + ")\n", + "\n", + "groupchat = autogen.GroupChat(agents=[user_proxy, image_agent, painter], messages=[], max_round=12)\n", + "manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.16 유사한 이미지를 생성하도록 에이전트 실행" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "gLpNLFd-UHbd" + }, + "outputs": [], + "source": [ + "user_proxy.initiate_chat(\n", + " manager,\n", + " message=f\"\"\"아래 이미지랑 비슷한 이미지를 만들어줘.\n", + ".\"\"\",\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 예제 15.18 멀티 모달 에이전트에 텍스트로 명령" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "id": "iwZAycesUIyy" + }, + "outputs": [], + "source": [ + "user_proxy.initiate_chat(\n", + " manager,\n", + " message=\"갈색의 털을 가진 귀여운 강아지를 그려줘\",\n", + ")" + ] + } + ], + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.4" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +}