Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save anpigon/049549b7ee1f9ecd9323bac53a540b8a to your computer and use it in GitHub Desktop.

Select an option

Save anpigon/049549b7ee1f9ecd9323bac53a540b8a to your computer and use it in GitHub Desktop.
Autogen에서 Code Executor로 코드 실행하기
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Autogen에서 Code Executor로 코드 실행하기"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"%pip install -U -q pyautogen \"pyautogen[gemini]\""
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import os\n",
"import warnings\n",
"from dotenv import load_dotenv\n",
"\n",
"warnings.filterwarnings(\"ignore\")\n",
"load_dotenv()"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"import autogen\n",
"from autogen.coding import LocalCommandLineCodeExecutor\n",
"\n",
"# gemini 사용\n",
"config_list = [\n",
" {\n",
" \"model\": \"gemini-1.5-flash\",\n",
" \"api_key\": os.environ[\"GOOGLE_API_KEY\"],\n",
" \"api_type\": \"google\",\n",
" },\n",
"]"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"assistant = autogen.AssistantAgent(\n",
" name=\"assiatant\",\n",
" llm_config={\"config_list\": config_list, \"temperature\": 0},\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [],
"source": [
"import tempfile\n",
"\n",
"# 코드 파일을 저장할 임시 디렉터리를 만듭니다.\n",
"temp_dir = tempfile.TemporaryDirectory()\n",
"\n",
"# 로컬 명령줄 코드 실행기를 만듭니다.\n",
"executor = LocalCommandLineCodeExecutor(\n",
" timeout=10, # 각 코드 실행에 대한 시간 초과(초).\n",
" work_dir=temp_dir.name, # 임시 디렉터리를 사용하여 코드 파일을 저장합니다.\n",
")\n",
"\n",
"user_proxy = autogen.UserProxyAgent(\n",
" name=\"code_executor_agent\",\n",
" max_consecutive_auto_reply=10, # human_input_mode가 NEVER인 경우, 최대 10번까지만 자동 응답하도록 제한\n",
" is_termination_msg=lambda x: x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n",
" code_execution_config={\n",
" \"executor\": executor\n",
" }, # 로컬 명령줄 코드 실행기를 사용합니다.\n",
" human_input_mode=\"NEVER\",\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[33mcode_executor_agent\u001b[0m (to assiatant):\n",
"\n",
"100 이하의 소수를 출력하는 파이썬 코드를 작성해줘.\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[33massiatant\u001b[0m (to code_executor_agent):\n",
"\n",
"```python\n",
"# filename: prime_numbers.py\n",
"def is_prime(num):\n",
" \"\"\"소수 판별 함수\"\"\"\n",
" if num <= 1:\n",
" return False\n",
" for i in range(2, int(num**0.5) + 1):\n",
" if num % i == 0:\n",
" return False\n",
" return True\n",
"\n",
"for i in range(2, 101):\n",
" if is_prime(i):\n",
" print(i)\n",
"```\n",
"\n",
"100 이하의 소수를 출력하는 파이썬 코드를 작성했습니다. \n",
"코드를 실행해 주세요. \n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[31m\n",
">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001b[0m\n",
"\u001b[33mcode_executor_agent\u001b[0m (to assiatant):\n",
"\n",
"exitcode: 0 (execution succeeded)\n",
"Code output: 2\n",
"3\n",
"5\n",
"7\n",
"11\n",
"13\n",
"17\n",
"19\n",
"23\n",
"29\n",
"31\n",
"37\n",
"41\n",
"43\n",
"47\n",
"53\n",
"59\n",
"61\n",
"67\n",
"71\n",
"73\n",
"79\n",
"83\n",
"89\n",
"97\n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[33massiatant\u001b[0m (to code_executor_agent):\n",
"\n",
"100 이하의 소수를 모두 출력하는 코드가 성공적으로 실행되었고, 결과가 예상대로 출력되었습니다. \n",
"\n",
"TERMINATE \n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n"
]
}
],
"source": [
"result = user_proxy.initiate_chat(\n",
" assistant,\n",
" message=\"100 이하의 소수를 출력하는 파이썬 코드를 작성해줘.\",\n",
" summary_method=\"reflection_with_llm\",\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Chat History: [{'content': '100 이하의 소수를 출력하는 파이썬 코드를 작성해줘.', 'role': 'assistant', 'name': 'code_executor_agent'}, {'content': '```python\\n# filename: prime_numbers.py\\ndef is_prime(num):\\n \"\"\"소수 판별 함수\"\"\"\\n if num <= 1:\\n return False\\n for i in range(2, int(num**0.5) + 1):\\n if num % i == 0:\\n return False\\n return True\\n\\nfor i in range(2, 101):\\n if is_prime(i):\\n print(i)\\n```\\n\\n100 이하의 소수를 출력하는 파이썬 코드를 작성했습니다. \\n코드를 실행해 주세요. \\n', 'role': 'user', 'name': 'assiatant'}, {'content': 'exitcode: 0 (execution succeeded)\\nCode output: 2\\n3\\n5\\n7\\n11\\n13\\n17\\n19\\n23\\n29\\n31\\n37\\n41\\n43\\n47\\n53\\n59\\n61\\n67\\n71\\n73\\n79\\n83\\n89\\n97\\n', 'role': 'assistant', 'name': 'code_executor_agent'}, {'content': '100 이하의 소수를 모두 출력하는 코드가 성공적으로 실행되었고, 결과가 예상대로 출력되었습니다. \\n\\nTERMINATE \\n', 'role': 'user', 'name': 'assiatant'}]\n",
"--------------------------------------------------\n",
"Summary: {'content': 'The conversation involved generating Python code to print prime numbers less than 100. The code was successfully executed and produced the expected output of all prime numbers within that range. \\n', 'refusal': None, 'role': 'assistant', 'function_call': None, 'tool_calls': None}\n",
"--------------------------------------------------\n",
"Cost Info: {'usage_including_cached_inference': {'total_cost': 0.015035999999999999, 'gemini-1.5-flash': {'cost': 0.015035999999999999, 'prompt_tokens': 1512, 'completion_tokens': 212, 'total_tokens': 1724}}, 'usage_excluding_cached_inference': {'total_cost': 0.015035999999999999, 'gemini-1.5-flash': {'cost': 0.015035999999999999, 'prompt_tokens': 1512, 'completion_tokens': 212, 'total_tokens': 1724}}}\n"
]
}
],
"source": [
"print(\"Chat History:\", result.chat_history)\n",
"print(\"-\" * 50)\n",
"print(\"Summary:\", result.summary)\n",
"print(\"-\" * 50)\n",
"print(\"Cost Info:\", result.cost)"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[33mcode_executor_agent\u001b[0m (to assiatant):\n",
"\n",
"야후 파이낸스에서 애플의 현재 주가 데이터를 가져와줘.\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[33massiatant\u001b[0m (to code_executor_agent):\n",
"\n",
"```python\n",
"# filename: apple_stock.py\n",
"import requests\n",
"from bs4 import BeautifulSoup\n",
"\n",
"url = \"https://finance.yahoo.com/quote/AAPL\"\n",
"response = requests.get(url)\n",
"soup = BeautifulSoup(response.text, 'html.parser')\n",
"\n",
"# 주가 정보를 찾습니다.\n",
"price_element = soup.find('div', {'class': 'D(ib) Mend(20px)'})\n",
"if price_element:\n",
" price = price_element.find('fin-streamer').text\n",
" print(f\"애플의 현재 주가는 {price}입니다.\")\n",
"else:\n",
" print(\"주가 정보를 찾을 수 없습니다.\")\n",
"```\n",
"\n",
"이 코드는 야후 파이낸스에서 애플의 현재 주가 데이터를 가져오는 코드입니다. \n",
"코드를 실행해 주세요. \n",
"\n",
"\n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[31m\n",
">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001b[0m\n",
"\u001b[33mcode_executor_agent\u001b[0m (to assiatant):\n",
"\n",
"exitcode: 0 (execution succeeded)\n",
"Code output: 주가 정보를 찾을 수 없습니다.\n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[33massiatant\u001b[0m (to code_executor_agent):\n",
"\n",
"코드를 실행했는데 주가 정보를 찾을 수 없다는 오류가 발생했습니다. \n",
"야후 파이낸스 웹사이트의 구조가 변경되었을 가능성이 있습니다. \n",
"\n",
"다시 코드를 수정하여 주가 정보를 찾아보겠습니다. \n",
"\n",
"```python\n",
"# filename: apple_stock.py\n",
"import requests\n",
"from bs4 import BeautifulSoup\n",
"\n",
"url = \"https://finance.yahoo.com/quote/AAPL\"\n",
"response = requests.get(url)\n",
"soup = BeautifulSoup(response.text, 'html.parser')\n",
"\n",
"# 주가 정보를 찾습니다.\n",
"price_element = soup.find('div', {'class': 'D(ib) Mend(20px)'})\n",
"if price_element:\n",
" price = price_element.find('fin-streamer').text\n",
" print(f\"애플의 현재 주가는 {price}입니다.\")\n",
"else:\n",
" # 다른 방법으로 주가 정보를 찾습니다.\n",
" price_element = soup.find('div', {'class': 'My(6px) Pos(r) smartphone_Mt(6px)'})\n",
" if price_element:\n",
" price = price_element.find('span').text\n",
" print(f\"애플의 현재 주가는 {price}입니다.\")\n",
" else:\n",
" print(\"주가 정보를 찾을 수 없습니다.\")\n",
"```\n",
"\n",
"이 코드는 야후 파이낸스 웹사이트의 구조 변경에 대비하여 주가 정보를 찾는 방법을 추가했습니다. \n",
"코드를 다시 실행해 주세요. \n",
"\n",
"\n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[31m\n",
">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001b[0m\n",
"\u001b[33mcode_executor_agent\u001b[0m (to assiatant):\n",
"\n",
"exitcode: 0 (execution succeeded)\n",
"Code output: 주가 정보를 찾을 수 없습니다.\n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\u001b[33massiatant\u001b[0m (to code_executor_agent):\n",
"\n",
"코드를 다시 실행했지만 여전히 주가 정보를 찾을 수 없다는 오류가 발생했습니다. \n",
"야후 파이낸스 웹사이트의 구조가 예상보다 더 크게 변경되었거나, 다른 문제가 있을 수 있습니다. \n",
"\n",
"현재로서는 야후 파이낸스 웹사이트에서 애플의 주가 정보를 정확하게 가져오는 것이 어렵습니다. \n",
"다른 방법으로 애플의 주가 정보를 얻는 것을 고려해야 할 것 같습니다. \n",
"\n",
"예를 들어, 다음과 같은 방법을 시도해 볼 수 있습니다.\n",
"\n",
"* **파이낸셜 데이터 API 사용:** 알파바이너리, 핀허브 등의 파이낸셜 데이터 API를 사용하여 애플의 주가 정보를 가져올 수 있습니다.\n",
"* **웹 스크래핑 라이브러리 업데이트:** BeautifulSoup 대신 Selenium과 같은 웹 스크래핑 라이브러리를 사용하여 야후 파이낸스 웹사이트에서 주가 정보를 가져올 수 있습니다.\n",
"\n",
"더 자세한 정보를 제공해 주시면 더 나은 해결책을 찾을 수 있을 것입니다. \n",
"\n",
"예를 들어, 다음과 같은 정보를 알려주시면 도움이 될 것입니다.\n",
"\n",
"* **어떤 목적으로 애플의 주가 정보를 얻고 싶은가요?**\n",
"* **어떤 다른 웹사이트에서 애플의 주가 정보를 얻을 수 있나요?**\n",
"\n",
"TERMINATE \n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n"
]
}
],
"source": [
"# 이전 대화에 이어서 진행하기\n",
"user_proxy.send(\n",
" recipient=assistant,\n",
" message=\"야후 파이낸스에서 애플의 현재 주가 데이터를 가져와줘.\",\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"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.9"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment