autogen

Форк
0
/
agentchat_oai_assistant_function_call.ipynb 
304 строки · 11.1 Кб
1
{
2
 "cells": [
3
  {
4
   "cell_type": "markdown",
5
   "metadata": {},
6
   "source": [
7
    "# Chat with OpenAI Assistant using function call in AutoGen: OSS Insights for Advanced GitHub Data Analysis\n",
8
    "\n",
9
    "This Jupyter Notebook demonstrates how to leverage OSS Insight (Open Source Software Insight) for advanced GitHub data analysis by defining `Function calls` in AutoGen for the OpenAI Assistant. \n",
10
    "\n",
11
    "The notebook is structured into four main sections:\n",
12
    "\n",
13
    "1. Function Schema and Implementation\n",
14
    "2. Defining an OpenAI Assistant Agent in AutoGen\n",
15
    "3. Fetching GitHub Insight Data using Function Call\n",
16
    "\n",
17
    "## Requirements\n",
18
    "\n",
19
    "AutoGen requires `Python>=3.8`. To run this notebook example, please install:\n",
20
    "````{=mdx}\n",
21
    ":::info Requirements\n",
22
    "Install `pyautogen`:\n",
23
    "```bash\n",
24
    "pip install pyautogen\n",
25
    "```\n",
26
    "\n",
27
    "For more information, please refer to the [installation guide](/docs/installation/).\n",
28
    ":::\n",
29
    "````"
30
   ]
31
  },
32
  {
33
   "cell_type": "code",
34
   "execution_count": null,
35
   "metadata": {},
36
   "outputs": [],
37
   "source": [
38
    "%%capture --no-stderr\n",
39
    "# %pip install \"pyautogen>=0.2.3\""
40
   ]
41
  },
42
  {
43
   "cell_type": "markdown",
44
   "metadata": {},
45
   "source": [
46
    "## Function Schema and Implementation\n",
47
    "\n",
48
    "This section provides the function schema definition and their implementation details. These functions are tailored to fetch and process data from GitHub, utilizing OSS Insight's capabilities."
49
   ]
50
  },
51
  {
52
   "cell_type": "code",
53
   "execution_count": 1,
54
   "metadata": {},
55
   "outputs": [],
56
   "source": [
57
    "import logging\n",
58
    "import os\n",
59
    "\n",
60
    "from autogen import UserProxyAgent, config_list_from_json\n",
61
    "from autogen.agentchat.contrib.gpt_assistant_agent import GPTAssistantAgent\n",
62
    "\n",
63
    "logger = logging.getLogger(__name__)\n",
64
    "logger.setLevel(logging.WARNING)\n",
65
    "\n",
66
    "ossinsight_api_schema = {\n",
67
    "    \"name\": \"ossinsight_data_api\",\n",
68
    "    \"parameters\": {\n",
69
    "        \"type\": \"object\",\n",
70
    "        \"properties\": {\n",
71
    "            \"question\": {\n",
72
    "                \"type\": \"string\",\n",
73
    "                \"description\": (\n",
74
    "                    \"Enter your GitHub data question in the form of a clear and specific question to ensure the returned data is accurate and valuable. \"\n",
75
    "                    \"For optimal results, specify the desired format for the data table in your request.\"\n",
76
    "                ),\n",
77
    "            }\n",
78
    "        },\n",
79
    "        \"required\": [\"question\"],\n",
80
    "    },\n",
81
    "    \"description\": \"This is an API endpoint allowing users (analysts) to input question about GitHub in text format to retrieve the related and structured data.\",\n",
82
    "}\n",
83
    "\n",
84
    "\n",
85
    "def get_ossinsight(question):\n",
86
    "    \"\"\"\n",
87
    "    [Mock] Retrieve the top 10 developers with the most followers on GitHub.\n",
88
    "    \"\"\"\n",
89
    "    report_components = [\n",
90
    "        f\"Question: {question}\",\n",
91
    "        \"SQL: SELECT `login` AS `user_login`, `followers` AS `followers` FROM `github_users` ORDER BY `followers` DESC LIMIT 10\",\n",
92
    "        \"\"\"Results:\n",
93
    "  {'followers': 166730, 'user_login': 'torvalds'}\n",
94
    "  {'followers': 86239, 'user_login': 'yyx990803'}\n",
95
    "  {'followers': 77611, 'user_login': 'gaearon'}\n",
96
    "  {'followers': 72668, 'user_login': 'ruanyf'}\n",
97
    "  {'followers': 65415, 'user_login': 'JakeWharton'}\n",
98
    "  {'followers': 60972, 'user_login': 'peng-zhihui'}\n",
99
    "  {'followers': 58172, 'user_login': 'bradtraversy'}\n",
100
    "  {'followers': 52143, 'user_login': 'gustavoguanabara'}\n",
101
    "  {'followers': 51542, 'user_login': 'sindresorhus'}\n",
102
    "  {'followers': 49621, 'user_login': 'tj'}\"\"\",\n",
103
    "    ]\n",
104
    "    return \"\\n\" + \"\\n\\n\".join(report_components) + \"\\n\""
105
   ]
106
  },
107
  {
108
   "cell_type": "markdown",
109
   "metadata": {},
110
   "source": [
111
    "## Defining an OpenAI Assistant Agent in AutoGen\n",
112
    "\n",
113
    "Here, we explore how to define an OpenAI Assistant Agent within the AutoGen. This includes setting up the agent to make use of the previously defined function calls for data retrieval and analysis."
114
   ]
115
  },
116
  {
117
   "cell_type": "code",
118
   "execution_count": 2,
119
   "metadata": {},
120
   "outputs": [
121
    {
122
     "name": "stderr",
123
     "output_type": "stream",
124
     "text": [
125
      "OpenAI client config of GPTAssistantAgent(OSS Analyst) - model: gpt-4-turbo-preview\n",
126
      "GPT Assistant only supports one OpenAI client. Using the first client in the list.\n",
127
      "No matching assistant found, creating a new assistant\n"
128
     ]
129
    }
130
   ],
131
   "source": [
132
    "assistant_id = os.environ.get(\"ASSISTANT_ID\", None)\n",
133
    "config_list = config_list_from_json(\"OAI_CONFIG_LIST\")\n",
134
    "llm_config = {\n",
135
    "    \"config_list\": config_list,\n",
136
    "}\n",
137
    "assistant_config = {\n",
138
    "    \"assistant_id\": assistant_id,\n",
139
    "    \"tools\": [\n",
140
    "        {\n",
141
    "            \"type\": \"function\",\n",
142
    "            \"function\": ossinsight_api_schema,\n",
143
    "        }\n",
144
    "    ],\n",
145
    "}\n",
146
    "\n",
147
    "oss_analyst = GPTAssistantAgent(\n",
148
    "    name=\"OSS Analyst\",\n",
149
    "    instructions=(\n",
150
    "        \"Hello, Open Source Project Analyst. You'll conduct comprehensive evaluations of open source projects or organizations on the GitHub platform, \"\n",
151
    "        \"analyzing project trajectories, contributor engagements, open source trends, and other vital parameters. \"\n",
152
    "        \"Please carefully read the context of the conversation to identify the current analysis question or problem that needs addressing.\"\n",
153
    "    ),\n",
154
    "    llm_config=llm_config,\n",
155
    "    assistant_config=assistant_config,\n",
156
    "    verbose=True,\n",
157
    ")\n",
158
    "oss_analyst.register_function(\n",
159
    "    function_map={\n",
160
    "        \"ossinsight_data_api\": get_ossinsight,\n",
161
    "    }\n",
162
    ")"
163
   ]
164
  },
165
  {
166
   "cell_type": "markdown",
167
   "metadata": {},
168
   "source": [
169
    "````{=mdx}\n",
170
    ":::tip\n",
171
    "Learn more about configuring LLMs for agents [here](/docs/topics/llm_configuration).\n",
172
    ":::\n",
173
    "````\n"
174
   ]
175
  },
176
  {
177
   "cell_type": "markdown",
178
   "metadata": {},
179
   "source": [
180
    "## Fetching GitHub Insight Data using Function Call\n",
181
    "\n",
182
    "This part of the notebook demonstrates the practical application of the defined functions and the OpenAI Assistant Agent in fetching and interpreting GitHub Insight data."
183
   ]
184
  },
185
  {
186
   "cell_type": "code",
187
   "execution_count": 3,
188
   "metadata": {},
189
   "outputs": [
190
    {
191
     "name": "stdout",
192
     "output_type": "stream",
193
     "text": [
194
      "\u001b[33muser_proxy\u001b[0m (to OSS Analyst):\n",
195
      "\n",
196
      "Top 10 developers with the most followers\n",
197
      "\n",
198
      "--------------------------------------------------------------------------------\n",
199
      "\u001b[35m\n",
200
      ">>>>>>>> EXECUTING FUNCTION ossinsight_data_api...\u001b[0m\n",
201
      "\u001b[35m\n",
202
      "Input arguments: {'question': 'Top 10 developers with the most followers'}\n",
203
      "Output:\n",
204
      "\n",
205
      "Question: Top 10 developers with the most followers\n",
206
      "\n",
207
      "SQL: SELECT `login` AS `user_login`, `followers` AS `followers` FROM `github_users` ORDER BY `followers` DESC LIMIT 10\n",
208
      "\n",
209
      "Results:\n",
210
      "  {'followers': 166730, 'user_login': 'torvalds'}\n",
211
      "  {'followers': 86239, 'user_login': 'yyx990803'}\n",
212
      "  {'followers': 77611, 'user_login': 'gaearon'}\n",
213
      "  {'followers': 72668, 'user_login': 'ruanyf'}\n",
214
      "  {'followers': 65415, 'user_login': 'JakeWharton'}\n",
215
      "  {'followers': 60972, 'user_login': 'peng-zhihui'}\n",
216
      "  {'followers': 58172, 'user_login': 'bradtraversy'}\n",
217
      "  {'followers': 52143, 'user_login': 'gustavoguanabara'}\n",
218
      "  {'followers': 51542, 'user_login': 'sindresorhus'}\n",
219
      "  {'followers': 49621, 'user_login': 'tj'}\n",
220
      "\u001b[0m\n",
221
      "\u001b[33mOSS Analyst\u001b[0m (to user_proxy):\n",
222
      "\n",
223
      "The top 10 developers with the most followers on GitHub are:\n",
224
      "\n",
225
      "1. **Linus Torvalds** (`torvalds`) with 166,730 followers\n",
226
      "2. **Evan You** (`yyx990803`) with 86,239 followers\n",
227
      "3. **Dan Abramov** (`gaearon`) with 77,611 followers\n",
228
      "4. **Ruan YiFeng** (`ruanyf`) with 72,668 followers\n",
229
      "5. **Jake Wharton** (`JakeWharton`) with 65,415 followers\n",
230
      "6. **Peng Zhihui** (`peng-zhihui`) with 60,972 followers\n",
231
      "7. **Brad Traversy** (`bradtraversy`) with 58,172 followers\n",
232
      "8. **Gustavo Guanabara** (`gustavoguanabara`) with 52,143 followers\n",
233
      "9. **Sindre Sorhus** (`sindresorhus`) with 51,542 followers\n",
234
      "10. **TJ Holowaychuk** (`tj`) with 49,621 followers\n",
235
      "\n",
236
      "\n",
237
      "--------------------------------------------------------------------------------\n",
238
      "\u001b[33muser_proxy\u001b[0m (to OSS Analyst):\n",
239
      "\n",
240
      "\n",
241
      "\n",
242
      "--------------------------------------------------------------------------------\n",
243
      "\u001b[33mOSS Analyst\u001b[0m (to user_proxy):\n",
244
      "\n",
245
      "It looks like there is no question or prompt for me to respond to. Could you please provide more details or ask a question that you would like assistance with?\n",
246
      "\n",
247
      "\n",
248
      "--------------------------------------------------------------------------------\n"
249
     ]
250
    },
251
    {
252
     "name": "stderr",
253
     "output_type": "stream",
254
     "text": [
255
      "Permanently deleting assistant...\n"
256
     ]
257
    }
258
   ],
259
   "source": [
260
    "user_proxy = UserProxyAgent(\n",
261
    "    name=\"user_proxy\",\n",
262
    "    code_execution_config={\n",
263
    "        \"work_dir\": \"coding\",\n",
264
    "        \"use_docker\": False,\n",
265
    "    },  # Please set use_docker=True if docker is available to run the generated code. Using docker is safer than running the generated code directly.\n",
266
    "    is_termination_msg=lambda msg: \"TERMINATE\" in msg[\"content\"],\n",
267
    "    human_input_mode=\"NEVER\",\n",
268
    "    max_consecutive_auto_reply=1,\n",
269
    ")\n",
270
    "\n",
271
    "user_proxy.initiate_chat(oss_analyst, message=\"Top 10 developers with the most followers\")\n",
272
    "oss_analyst.delete_assistant()"
273
   ]
274
  }
275
 ],
276
 "metadata": {
277
  "front_matter": {
278
   "description": "This Jupyter Notebook demonstrates how to leverage OSS Insight (Open Source Software Insight) for advanced GitHub data analysis by defining `Function calls` in AutoGen for the OpenAI Assistant.",
279
   "tags": [
280
    "OpenAI Assistant",
281
    "function call"
282
   ]
283
  },
284
  "kernelspec": {
285
   "display_name": "autogen",
286
   "language": "python",
287
   "name": "python3"
288
  },
289
  "language_info": {
290
   "codemirror_mode": {
291
    "name": "ipython",
292
    "version": 3
293
   },
294
   "file_extension": ".py",
295
   "mimetype": "text/x-python",
296
   "name": "python",
297
   "nbconvert_exporter": "python",
298
   "pygments_lexer": "ipython3",
299
   "version": "3.10.13"
300
  }
301
 },
302
 "nbformat": 4,
303
 "nbformat_minor": 2
304
}
305

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.