autogen

Форк
0
/
agentchat_groupchat_RAG.ipynb 
1264 строки · 62.8 Кб
1
{
2
 "cells": [
3
  {
4
   "attachments": {},
5
   "cell_type": "markdown",
6
   "metadata": {},
7
   "source": [
8
    "# Group Chat with Retrieval Augmented Generation\n",
9
    "\n",
10
    "AutoGen supports conversable agents powered by LLMs, tools, or humans, performing tasks collectively via automated chat. This framework allows tool use and human participation through multi-agent conversation.\n",
11
    "Please find documentation about this feature [here](https://microsoft.github.io/autogen/docs/Use-Cases/agent_chat).\n",
12
    "\n",
13
    "````{=mdx}\n",
14
    ":::info Requirements\n",
15
    "Some extra dependencies are needed for this notebook, which can be installed via pip:\n",
16
    "\n",
17
    "```bash\n",
18
    "pip install pyautogen[retrievechat]\n",
19
    "```\n",
20
    "\n",
21
    "For more information, please refer to the [installation guide](/docs/installation/).\n",
22
    ":::\n",
23
    "````"
24
   ]
25
  },
26
  {
27
   "attachments": {},
28
   "cell_type": "markdown",
29
   "metadata": {},
30
   "source": [
31
    "## Set your API Endpoint\n",
32
    "\n",
33
    "The [`config_list_from_json`](https://microsoft.github.io/autogen/docs/reference/oai/openai_utils#config_list_from_json) function loads a list of configurations from an environment variable or a json file."
34
   ]
35
  },
36
  {
37
   "cell_type": "code",
38
   "execution_count": 1,
39
   "metadata": {},
40
   "outputs": [
41
    {
42
     "name": "stdout",
43
     "output_type": "stream",
44
     "text": [
45
      "LLM models:  ['gpt4-1106-preview', 'gpt-35-turbo', 'gpt-35-turbo-0613']\n"
46
     ]
47
    }
48
   ],
49
   "source": [
50
    "import chromadb\n",
51
    "from typing_extensions import Annotated\n",
52
    "\n",
53
    "import autogen\n",
54
    "from autogen import AssistantAgent\n",
55
    "from autogen.agentchat.contrib.retrieve_user_proxy_agent import RetrieveUserProxyAgent\n",
56
    "\n",
57
    "config_list = autogen.config_list_from_json(\"OAI_CONFIG_LIST\")\n",
58
    "\n",
59
    "print(\"LLM models: \", [config_list[i][\"model\"] for i in range(len(config_list))])"
60
   ]
61
  },
62
  {
63
   "attachments": {},
64
   "cell_type": "markdown",
65
   "metadata": {},
66
   "source": [
67
    "````{=mdx}\n",
68
    ":::tip\n",
69
    "Learn more about configuring LLMs for agents [here](/docs/topics/llm_configuration).\n",
70
    ":::\n",
71
    "````\n",
72
    "\n",
73
    "## Construct Agents"
74
   ]
75
  },
76
  {
77
   "cell_type": "code",
78
   "execution_count": 2,
79
   "metadata": {},
80
   "outputs": [
81
    {
82
     "name": "stderr",
83
     "output_type": "stream",
84
     "text": [
85
      "/home/lijiang1/anaconda3/envs/autogen/lib/python3.10/site-packages/transformers/utils/generic.py:311: UserWarning: torch.utils._pytree._register_pytree_node is deprecated. Please use torch.utils._pytree.register_pytree_node instead.\n",
86
      "  torch.utils._pytree._register_pytree_node(\n"
87
     ]
88
    }
89
   ],
90
   "source": [
91
    "def termination_msg(x):\n",
92
    "    return isinstance(x, dict) and \"TERMINATE\" == str(x.get(\"content\", \"\"))[-9:].upper()\n",
93
    "\n",
94
    "\n",
95
    "llm_config = {\"config_list\": config_list, \"timeout\": 60, \"temperature\": 0.8, \"seed\": 1234}\n",
96
    "\n",
97
    "boss = autogen.UserProxyAgent(\n",
98
    "    name=\"Boss\",\n",
99
    "    is_termination_msg=termination_msg,\n",
100
    "    human_input_mode=\"NEVER\",\n",
101
    "    code_execution_config=False,  # we don't want to execute code in this case.\n",
102
    "    default_auto_reply=\"Reply `TERMINATE` if the task is done.\",\n",
103
    "    description=\"The boss who ask questions and give tasks.\",\n",
104
    ")\n",
105
    "\n",
106
    "boss_aid = RetrieveUserProxyAgent(\n",
107
    "    name=\"Boss_Assistant\",\n",
108
    "    is_termination_msg=termination_msg,\n",
109
    "    human_input_mode=\"NEVER\",\n",
110
    "    default_auto_reply=\"Reply `TERMINATE` if the task is done.\",\n",
111
    "    max_consecutive_auto_reply=3,\n",
112
    "    retrieve_config={\n",
113
    "        \"task\": \"code\",\n",
114
    "        \"docs_path\": \"https://raw.githubusercontent.com/microsoft/FLAML/main/website/docs/Examples/Integrate%20-%20Spark.md\",\n",
115
    "        \"chunk_token_size\": 1000,\n",
116
    "        \"model\": config_list[0][\"model\"],\n",
117
    "        \"collection_name\": \"groupchat\",\n",
118
    "        \"get_or_create\": True,\n",
119
    "    },\n",
120
    "    code_execution_config=False,  # we don't want to execute code in this case.\n",
121
    "    description=\"Assistant who has extra content retrieval power for solving difficult problems.\",\n",
122
    ")\n",
123
    "\n",
124
    "coder = AssistantAgent(\n",
125
    "    name=\"Senior_Python_Engineer\",\n",
126
    "    is_termination_msg=termination_msg,\n",
127
    "    system_message=\"You are a senior python engineer, you provide python code to answer questions. Reply `TERMINATE` in the end when everything is done.\",\n",
128
    "    llm_config=llm_config,\n",
129
    "    description=\"Senior Python Engineer who can write code to solve problems and answer questions.\",\n",
130
    ")\n",
131
    "\n",
132
    "pm = autogen.AssistantAgent(\n",
133
    "    name=\"Product_Manager\",\n",
134
    "    is_termination_msg=termination_msg,\n",
135
    "    system_message=\"You are a product manager. Reply `TERMINATE` in the end when everything is done.\",\n",
136
    "    llm_config=llm_config,\n",
137
    "    description=\"Product Manager who can design and plan the project.\",\n",
138
    ")\n",
139
    "\n",
140
    "reviewer = autogen.AssistantAgent(\n",
141
    "    name=\"Code_Reviewer\",\n",
142
    "    is_termination_msg=termination_msg,\n",
143
    "    system_message=\"You are a code reviewer. Reply `TERMINATE` in the end when everything is done.\",\n",
144
    "    llm_config=llm_config,\n",
145
    "    description=\"Code Reviewer who can review the code.\",\n",
146
    ")\n",
147
    "\n",
148
    "PROBLEM = \"How to use spark for parallel training in FLAML? Give me sample code.\"\n",
149
    "\n",
150
    "\n",
151
    "def _reset_agents():\n",
152
    "    boss.reset()\n",
153
    "    boss_aid.reset()\n",
154
    "    coder.reset()\n",
155
    "    pm.reset()\n",
156
    "    reviewer.reset()\n",
157
    "\n",
158
    "\n",
159
    "def rag_chat():\n",
160
    "    _reset_agents()\n",
161
    "    groupchat = autogen.GroupChat(\n",
162
    "        agents=[boss_aid, pm, coder, reviewer], messages=[], max_round=12, speaker_selection_method=\"round_robin\"\n",
163
    "    )\n",
164
    "    manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)\n",
165
    "\n",
166
    "    # Start chatting with boss_aid as this is the user proxy agent.\n",
167
    "    boss_aid.initiate_chat(\n",
168
    "        manager,\n",
169
    "        message=boss_aid.message_generator,\n",
170
    "        problem=PROBLEM,\n",
171
    "        n_results=3,\n",
172
    "    )\n",
173
    "\n",
174
    "\n",
175
    "def norag_chat():\n",
176
    "    _reset_agents()\n",
177
    "    groupchat = autogen.GroupChat(\n",
178
    "        agents=[boss, pm, coder, reviewer],\n",
179
    "        messages=[],\n",
180
    "        max_round=12,\n",
181
    "        speaker_selection_method=\"auto\",\n",
182
    "        allow_repeat_speaker=False,\n",
183
    "    )\n",
184
    "    manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)\n",
185
    "\n",
186
    "    # Start chatting with the boss as this is the user proxy agent.\n",
187
    "    boss.initiate_chat(\n",
188
    "        manager,\n",
189
    "        message=PROBLEM,\n",
190
    "    )\n",
191
    "\n",
192
    "\n",
193
    "def call_rag_chat():\n",
194
    "    _reset_agents()\n",
195
    "\n",
196
    "    # In this case, we will have multiple user proxy agents and we don't initiate the chat\n",
197
    "    # with RAG user proxy agent.\n",
198
    "    # In order to use RAG user proxy agent, we need to wrap RAG agents in a function and call\n",
199
    "    # it from other agents.\n",
200
    "    def retrieve_content(\n",
201
    "        message: Annotated[\n",
202
    "            str,\n",
203
    "            \"Refined message which keeps the original meaning and can be used to retrieve content for code generation and question answering.\",\n",
204
    "        ],\n",
205
    "        n_results: Annotated[int, \"number of results\"] = 3,\n",
206
    "    ) -> str:\n",
207
    "        boss_aid.n_results = n_results  # Set the number of results to be retrieved.\n",
208
    "        # Check if we need to update the context.\n",
209
    "        update_context_case1, update_context_case2 = boss_aid._check_update_context(message)\n",
210
    "        if (update_context_case1 or update_context_case2) and boss_aid.update_context:\n",
211
    "            boss_aid.problem = message if not hasattr(boss_aid, \"problem\") else boss_aid.problem\n",
212
    "            _, ret_msg = boss_aid._generate_retrieve_user_reply(message)\n",
213
    "        else:\n",
214
    "            _context = {\"problem\": message, \"n_results\": n_results}\n",
215
    "            ret_msg = boss_aid.message_generator(boss_aid, None, _context)\n",
216
    "        return ret_msg if ret_msg else message\n",
217
    "\n",
218
    "    boss_aid.human_input_mode = \"NEVER\"  # Disable human input for boss_aid since it only retrieves content.\n",
219
    "\n",
220
    "    for caller in [pm, coder, reviewer]:\n",
221
    "        d_retrieve_content = caller.register_for_llm(\n",
222
    "            description=\"retrieve content for code generation and question answering.\", api_style=\"function\"\n",
223
    "        )(retrieve_content)\n",
224
    "\n",
225
    "    for executor in [boss, pm]:\n",
226
    "        executor.register_for_execution()(d_retrieve_content)\n",
227
    "\n",
228
    "    groupchat = autogen.GroupChat(\n",
229
    "        agents=[boss, pm, coder, reviewer],\n",
230
    "        messages=[],\n",
231
    "        max_round=12,\n",
232
    "        speaker_selection_method=\"round_robin\",\n",
233
    "        allow_repeat_speaker=False,\n",
234
    "    )\n",
235
    "\n",
236
    "    manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)\n",
237
    "\n",
238
    "    # Start chatting with the boss as this is the user proxy agent.\n",
239
    "    boss.initiate_chat(\n",
240
    "        manager,\n",
241
    "        message=PROBLEM,\n",
242
    "    )"
243
   ]
244
  },
245
  {
246
   "attachments": {},
247
   "cell_type": "markdown",
248
   "metadata": {},
249
   "source": [
250
    "## Start Chat\n",
251
    "\n",
252
    "### UserProxyAgent doesn't get the correct code\n",
253
    "[FLAML](https://github.com/microsoft/FLAML) was open sourced in 2020, so ChatGPT is familiar with it. However, Spark-related APIs were added in 2022, so they were not in ChatGPT's training data. As a result, we end up with invalid code."
254
   ]
255
  },
256
  {
257
   "cell_type": "code",
258
   "execution_count": 3,
259
   "metadata": {},
260
   "outputs": [
261
    {
262
     "name": "stdout",
263
     "output_type": "stream",
264
     "text": [
265
      "\u001b[33mBoss\u001b[0m (to chat_manager):\n",
266
      "\n",
267
      "How to use spark for parallel training in FLAML? Give me sample code.\n",
268
      "\n",
269
      "--------------------------------------------------------------------------------\n"
270
     ]
271
    },
272
    {
273
     "name": "stdout",
274
     "output_type": "stream",
275
     "text": [
276
      "\u001b[33mSenior_Python_Engineer\u001b[0m (to chat_manager):\n",
277
      "\n",
278
      "To use Spark for parallel training in FLAML (Fast and Lightweight AutoML), you would need to set up a Spark cluster and utilize the `spark` backend for joblib, which FLAML uses internally for parallel training. Here’s an example of how you might set up and use Spark with FLAML for AutoML tasks:\n",
279
      "\n",
280
      "Firstly, ensure that you have the Spark cluster set up and the `pyspark` and `joblib-spark` packages installed in your environment. You can install the required packages using pip if they are not already installed:\n",
281
      "\n",
282
      "```python\n",
283
      "!pip install flaml pyspark joblib-spark\n",
284
      "```\n",
285
      "\n",
286
      "Here's a sample code snippet that demonstrates how to use FLAML with Spark for parallel training:\n",
287
      "\n",
288
      "```python\n",
289
      "from flaml import AutoML\n",
290
      "from pyspark.sql import SparkSession\n",
291
      "from sklearn.datasets import load_digits\n",
292
      "from joblibspark import register_spark\n",
293
      "\n",
294
      "# Initialize a Spark session\n",
295
      "spark = SparkSession.builder \\\n",
296
      "    .master(\"local[*]\") \\\n",
297
      "    .appName(\"FLAML_Spark_Example\") \\\n",
298
      "    .getOrCreate()\n",
299
      "\n",
300
      "# Register the joblib spark backend\n",
301
      "register_spark()  # This registers the backend for parallel processing\n",
302
      "\n",
303
      "# Load sample data\n",
304
      "X, y = load_digits(return_X_y=True)\n",
305
      "\n",
306
      "# Initialize an AutoML instance\n",
307
      "automl = AutoML()\n",
308
      "\n",
309
      "# Define the settings for the AutoML run\n",
310
      "settings = {\n",
311
      "    \"time_budget\": 60,  # Total running time in seconds\n",
312
      "    \"metric\": 'accuracy',  # Primary metric for evaluation\n",
313
      "    \"task\": 'classification',  # Task type\n",
314
      "    \"n_jobs\": -1,  # Number of jobs to run in parallel (use -1 for all)\n",
315
      "    \"estimator_list\": ['lgbm', 'rf', 'xgboost'],  # List of estimators to consider\n",
316
      "    \"log_file_name\": \"flaml_log.txt\",  # Log file name\n",
317
      "}\n",
318
      "\n",
319
      "# Run the AutoML search with Spark backend\n",
320
      "automl.fit(X_train=X, y_train=y, **settings)\n",
321
      "\n",
322
      "# Output the best model and its performance\n",
323
      "print(f\"Best ML model: {automl.model}\")\n",
324
      "print(f\"Best ML model's accuracy: {automl.best_loss}\")\n",
325
      "\n",
326
      "# Stop the Spark session\n",
327
      "spark.stop()\n",
328
      "```\n",
329
      "\n",
330
      "The `register_spark()` function from `joblib-spark` is used to register the Spark backend with joblib, which is utilized for parallel training within FLAML. The `n_jobs=-1` parameter tells FLAML to use all available Spark executors for parallel training.\n",
331
      "\n",
332
      "Please note that the actual process of setting up a Spark cluster can be complex and might involve additional steps such as configuring Spark workers, allocating resources, and more, which are beyond the scope of this code snippet.\n",
333
      "\n",
334
      "If you encounter any issues or need to adjust configurations for your specific Spark setup, please refer to the Spark and FLAML documentation for more details.\n",
335
      "\n",
336
      "When you run the code, ensure that your Spark cluster is properly configured and accessible from your Python environment. Adjust the `.master(\"local[*]\")` to point to your Spark master's URL if you are running a cluster that is not local.\n",
337
      "\n",
338
      "--------------------------------------------------------------------------------\n",
339
      "To use Spark for parallel training in FLAML (Fast and Lightweight AutoML), you would need to set up a Spark cluster and utilize the `spark` backend for joblib, which FLAML uses internally for parallel training. Here’s an example of how you might set up and use Spark with FLAML for AutoML tasks:\n",
340
      "\n",
341
      "Firstly, ensure that you have the Spark cluster set up and the `pyspark` and `joblib-spark` packages installed in your environment. You can install the required packages using pip if they are not already installed:\n",
342
      "\n",
343
      "```python\n",
344
      "!pip install flaml pyspark joblib-spark\n",
345
      "```\n",
346
      "\n",
347
      "Here's a sample code snippet that demonstrates how to use FLAML with Spark for parallel training:\n",
348
      "\n",
349
      "```python\n",
350
      "from flaml import AutoML\n",
351
      "from pyspark.sql import SparkSession\n",
352
      "from sklearn.datasets import load_digits\n",
353
      "from joblibspark import register_spark\n",
354
      "\n",
355
      "# Initialize a Spark session\n",
356
      "spark = SparkSession.builder \\\n",
357
      "    .master(\"local[*]\") \\\n",
358
      "    .appName(\"FLAML_Spark_Example\") \\\n",
359
      "    .getOrCreate()\n",
360
      "\n",
361
      "# Register the joblib spark backend\n",
362
      "register_spark()  # This registers the backend for parallel processing\n",
363
      "\n",
364
      "# Load sample data\n",
365
      "X, y = load_digits(return_X_y=True)\n",
366
      "\n",
367
      "# Initialize an AutoML instance\n",
368
      "automl = AutoML()\n",
369
      "\n",
370
      "# Define the settings for the AutoML run\n",
371
      "settings = {\n",
372
      "    \"time_budget\": 60,  # Total running time in seconds\n",
373
      "    \"metric\": 'accuracy',  # Primary metric for evaluation\n",
374
      "    \"task\": 'classification',  # Task type\n",
375
      "    \"n_jobs\": -1,  # Number of jobs to run in parallel (use -1 for all)\n",
376
      "    \"estimator_list\": ['lgbm', 'rf', 'xgboost'],  # List of estimators to consider\n",
377
      "    \"log_file_name\": \"flaml_log.txt\",  # Log file name\n",
378
      "}\n",
379
      "\n",
380
      "# Run the AutoML search with Spark backend\n",
381
      "automl.fit(X_train=X, y_train=y, **settings)\n",
382
      "\n",
383
      "# Output the best model and its performance\n",
384
      "print(f\"Best ML model: {automl.model}\")\n",
385
      "print(f\"Best ML model's accuracy: {automl.best_loss}\")\n",
386
      "\n",
387
      "# Stop the Spark session\n",
388
      "spark.stop()\n",
389
      "```\n",
390
      "\n",
391
      "The `register_spark()` function from `joblib-spark` is used to register the Spark backend with joblib, which is utilized for parallel training within FLAML. The `n_jobs=-1` parameter tells FLAML to use all available Spark executors for parallel training.\n",
392
      "\n",
393
      "Please note that the actual process of setting up a Spark cluster can be complex and might involve additional steps such as configuring Spark workers, allocating resources, and more, which are beyond the scope of this code snippet.\n",
394
      "\n",
395
      "If you encounter any issues or need to adjust configurations for your specific Spark setup, please refer to the Spark and FLAML documentation for more details.\n",
396
      "\n",
397
      "When you run the code, ensure that your Spark cluster is properly configured and accessible from your Python environment. Adjust the `.master(\"local[*]\")` to point to your Spark master's URL if you are running a cluster that is not local.\n",
398
      "\n",
399
      "--------------------------------------------------------------------------------\n",
400
      "\u001b[33mCode_Reviewer\u001b[0m (to chat_manager):\n",
401
      "\n",
402
      "TERMINATE\n",
403
      "\n",
404
      "--------------------------------------------------------------------------------\n"
405
     ]
406
    }
407
   ],
408
   "source": [
409
    "norag_chat()"
410
   ]
411
  },
412
  {
413
   "attachments": {},
414
   "cell_type": "markdown",
415
   "metadata": {},
416
   "source": [
417
    "### RetrieveUserProxyAgent get the correct code\n",
418
    "Since RetrieveUserProxyAgent can perform retrieval-augmented generation based on the given documentation file, ChatGPT can generate the correct code for us!"
419
   ]
420
  },
421
  {
422
   "cell_type": "code",
423
   "execution_count": 4,
424
   "metadata": {},
425
   "outputs": [
426
    {
427
     "name": "stderr",
428
     "output_type": "stream",
429
     "text": [
430
      "2024-04-07 18:26:04,562 - autogen.agentchat.contrib.retrieve_user_proxy_agent - INFO - \u001b[32mUse the existing collection `groupchat`.\u001b[0m\n"
431
     ]
432
    },
433
    {
434
     "name": "stdout",
435
     "output_type": "stream",
436
     "text": [
437
      "Trying to create collection.\n"
438
     ]
439
    },
440
    {
441
     "name": "stderr",
442
     "output_type": "stream",
443
     "text": [
444
      "2024-04-07 18:26:05,485 - autogen.agentchat.contrib.retrieve_user_proxy_agent - INFO - Found 1 chunks.\u001b[0m\n",
445
      "Number of requested results 3 is greater than number of elements in index 1, updating n_results = 1\n",
446
      "Model gpt4-1106-preview not found. Using cl100k_base encoding.\n"
447
     ]
448
    },
449
    {
450
     "name": "stdout",
451
     "output_type": "stream",
452
     "text": [
453
      "VectorDB returns doc_ids:  [['bdfbc921']]\n",
454
      "\u001b[32mAdding content of doc bdfbc921 to context.\u001b[0m\n",
455
      "\u001b[33mBoss_Assistant\u001b[0m (to chat_manager):\n",
456
      "\n",
457
      "You're a retrieve augmented coding assistant. You answer user's questions based on your own knowledge and the\n",
458
      "context provided by the user.\n",
459
      "If you can't answer the question with or without the current context, you should reply exactly `UPDATE CONTEXT`.\n",
460
      "For code generation, you must obey the following rules:\n",
461
      "Rule 1. You MUST NOT install any packages because all the packages needed are already installed.\n",
462
      "Rule 2. You must follow the formats below to write your code:\n",
463
      "```language\n",
464
      "# your code\n",
465
      "```\n",
466
      "\n",
467
      "User's question is: How to use spark for parallel training in FLAML? Give me sample code.\n",
468
      "\n",
469
      "Context is: # Integrate - Spark\n",
470
      "\n",
471
      "FLAML has integrated Spark for distributed training. There are two main aspects of integration with Spark:\n",
472
      "\n",
473
      "- Use Spark ML estimators for AutoML.\n",
474
      "- Use Spark to run training in parallel spark jobs.\n",
475
      "\n",
476
      "## Spark ML Estimators\n",
477
      "\n",
478
      "FLAML integrates estimators based on Spark ML models. These models are trained in parallel using Spark, so we called them Spark estimators. To use these models, you first need to organize your data in the required format.\n",
479
      "\n",
480
      "### Data\n",
481
      "\n",
482
      "For Spark estimators, AutoML only consumes Spark data. FLAML provides a convenient function `to_pandas_on_spark` in the `flaml.automl.spark.utils` module to convert your data into a pandas-on-spark (`pyspark.pandas`) dataframe/series, which Spark estimators require.\n",
483
      "\n",
484
      "This utility function takes data in the form of a `pandas.Dataframe` or `pyspark.sql.Dataframe` and converts it into a pandas-on-spark dataframe. It also takes `pandas.Series` or `pyspark.sql.Dataframe` and converts it into a [pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html) series. If you pass in a `pyspark.pandas.Dataframe`, it will not make any changes.\n",
485
      "\n",
486
      "This function also accepts optional arguments `index_col` and `default_index_type`.\n",
487
      "\n",
488
      "- `index_col` is the column name to use as the index, default is None.\n",
489
      "- `default_index_type` is the default index type, default is \"distributed-sequence\". More info about default index type could be found on Spark official [documentation](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)\n",
490
      "\n",
491
      "Here is an example code snippet for Spark Data:\n",
492
      "\n",
493
      "```python\n",
494
      "import pandas as pd\n",
495
      "from flaml.automl.spark.utils import to_pandas_on_spark\n",
496
      "\n",
497
      "# Creating a dictionary\n",
498
      "data = {\n",
499
      "    \"Square_Feet\": [800, 1200, 1800, 1500, 850],\n",
500
      "    \"Age_Years\": [20, 15, 10, 7, 25],\n",
501
      "    \"Price\": [100000, 200000, 300000, 240000, 120000],\n",
502
      "}\n",
503
      "\n",
504
      "# Creating a pandas DataFrame\n",
505
      "dataframe = pd.DataFrame(data)\n",
506
      "label = \"Price\"\n",
507
      "\n",
508
      "# Convert to pandas-on-spark dataframe\n",
509
      "psdf = to_pandas_on_spark(dataframe)\n",
510
      "```\n",
511
      "\n",
512
      "To use Spark ML models you need to format your data appropriately. Specifically, use [`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html) to merge all feature columns into a single vector column.\n",
513
      "\n",
514
      "Here is an example of how to use it:\n",
515
      "\n",
516
      "```python\n",
517
      "from pyspark.ml.feature import VectorAssembler\n",
518
      "\n",
519
      "columns = psdf.columns\n",
520
      "feature_cols = [col for col in columns if col != label]\n",
521
      "featurizer = VectorAssembler(inputCols=feature_cols, outputCol=\"features\")\n",
522
      "psdf = featurizer.transform(psdf.to_spark(index_col=\"index\"))[\"index\", \"features\"]\n",
523
      "```\n",
524
      "\n",
525
      "Later in conducting the experiment, use your pandas-on-spark data like non-spark data and pass them using `X_train, y_train` or `dataframe, label`.\n",
526
      "\n",
527
      "### Estimators\n",
528
      "\n",
529
      "#### Model List\n",
530
      "\n",
531
      "- `lgbm_spark`: The class for fine-tuning Spark version LightGBM models, using [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API.\n",
532
      "\n",
533
      "#### Usage\n",
534
      "\n",
535
      "First, prepare your data in the required format as described in the previous section.\n",
536
      "\n",
537
      "By including the models you intend to try in the `estimators_list` argument to `flaml.automl`, FLAML will start trying configurations for these models. If your input is Spark data, FLAML will also use estimators with the `_spark` postfix by default, even if you haven't specified them.\n",
538
      "\n",
539
      "Here is an example code snippet using SparkML models in AutoML:\n",
540
      "\n",
541
      "```python\n",
542
      "import flaml\n",
543
      "\n",
544
      "# prepare your data in pandas-on-spark format as we previously mentioned\n",
545
      "\n",
546
      "automl = flaml.AutoML()\n",
547
      "settings = {\n",
548
      "    \"time_budget\": 30,\n",
549
      "    \"metric\": \"r2\",\n",
550
      "    \"estimator_list\": [\"lgbm_spark\"],  # this setting is optional\n",
551
      "    \"task\": \"regression\",\n",
552
      "}\n",
553
      "\n",
554
      "automl.fit(\n",
555
      "    dataframe=psdf,\n",
556
      "    label=label,\n",
557
      "    **settings,\n",
558
      ")\n",
559
      "```\n",
560
      "\n",
561
      "[Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)\n",
562
      "\n",
563
      "## Parallel Spark Jobs\n",
564
      "\n",
565
      "You can activate Spark as the parallel backend during parallel tuning in both [AutoML](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning) and [Hyperparameter Tuning](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning), by setting the `use_spark` to `true`. FLAML will dispatch your job to the distributed Spark backend using [`joblib-spark`](https://github.com/joblib/joblib-spark).\n",
566
      "\n",
567
      "Please note that you should not set `use_spark` to `true` when applying AutoML and Tuning for Spark Data. This is because only SparkML models will be used for Spark Data in AutoML and Tuning. As SparkML models run in parallel, there is no need to distribute them with `use_spark` again.\n",
568
      "\n",
569
      "All the Spark-related arguments are stated below. These arguments are available in both Hyperparameter Tuning and AutoML:\n",
570
      "\n",
571
      "- `use_spark`: boolean, default=False | Whether to use spark to run the training in parallel spark jobs. This can be used to accelerate training on large models and large datasets, but will incur more overhead in time and thus slow down training in some cases. GPU training is not supported yet when use_spark is True. For Spark clusters, by default, we will launch one trial per executor. However, sometimes we want to launch more trials than the number of executors (e.g., local mode). In this case, we can set the environment variable `FLAML_MAX_CONCURRENT` to override the detected `num_executors`. The final number of concurrent trials will be the minimum of `n_concurrent_trials` and `num_executors`.\n",
572
      "- `n_concurrent_trials`: int, default=1 | The number of concurrent trials. When n_concurrent_trials > 1, FLAML performes parallel tuning.\n",
573
      "- `force_cancel`: boolean, default=False | Whether to forcely cancel Spark jobs if the search time exceeded the time budget. Spark jobs include parallel tuning jobs and Spark-based model training jobs.\n",
574
      "\n",
575
      "An example code snippet for using parallel Spark jobs:\n",
576
      "\n",
577
      "```python\n",
578
      "import flaml\n",
579
      "\n",
580
      "automl_experiment = flaml.AutoML()\n",
581
      "automl_settings = {\n",
582
      "    \"time_budget\": 30,\n",
583
      "    \"metric\": \"r2\",\n",
584
      "    \"task\": \"regression\",\n",
585
      "    \"n_concurrent_trials\": 2,\n",
586
      "    \"use_spark\": True,\n",
587
      "    \"force_cancel\": True,  # Activating the force_cancel option can immediately halt Spark jobs once they exceed the allocated time_budget.\n",
588
      "}\n",
589
      "\n",
590
      "automl.fit(\n",
591
      "    dataframe=dataframe,\n",
592
      "    label=label,\n",
593
      "    **automl_settings,\n",
594
      ")\n",
595
      "```\n",
596
      "\n",
597
      "[Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)\n",
598
      "\n",
599
      "\n",
600
      "\n",
601
      "--------------------------------------------------------------------------------\n",
602
      "\u001b[33mBoss_Assistant\u001b[0m (to chat_manager):\n",
603
      "\n",
604
      "You're a retrieve augmented coding assistant. You answer user's questions based on your own knowledge and the\n",
605
      "context provided by the user.\n",
606
      "If you can't answer the question with or without the current context, you should reply exactly `UPDATE CONTEXT`.\n",
607
      "For code generation, you must obey the following rules:\n",
608
      "Rule 1. You MUST NOT install any packages because all the packages needed are already installed.\n",
609
      "Rule 2. You must follow the formats below to write your code:\n",
610
      "```language\n",
611
      "# your code\n",
612
      "```\n",
613
      "\n",
614
      "User's question is: How to use spark for parallel training in FLAML? Give me sample code.\n",
615
      "\n",
616
      "Context is: # Integrate - Spark\n",
617
      "\n",
618
      "FLAML has integrated Spark for distributed training. There are two main aspects of integration with Spark:\n",
619
      "\n",
620
      "- Use Spark ML estimators for AutoML.\n",
621
      "- Use Spark to run training in parallel spark jobs.\n",
622
      "\n",
623
      "## Spark ML Estimators\n",
624
      "\n",
625
      "FLAML integrates estimators based on Spark ML models. These models are trained in parallel using Spark, so we called them Spark estimators. To use these models, you first need to organize your data in the required format.\n",
626
      "\n",
627
      "### Data\n",
628
      "\n",
629
      "For Spark estimators, AutoML only consumes Spark data. FLAML provides a convenient function `to_pandas_on_spark` in the `flaml.automl.spark.utils` module to convert your data into a pandas-on-spark (`pyspark.pandas`) dataframe/series, which Spark estimators require.\n",
630
      "\n",
631
      "This utility function takes data in the form of a `pandas.Dataframe` or `pyspark.sql.Dataframe` and converts it into a pandas-on-spark dataframe. It also takes `pandas.Series` or `pyspark.sql.Dataframe` and converts it into a [pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html) series. If you pass in a `pyspark.pandas.Dataframe`, it will not make any changes.\n",
632
      "\n",
633
      "This function also accepts optional arguments `index_col` and `default_index_type`.\n",
634
      "\n",
635
      "- `index_col` is the column name to use as the index, default is None.\n",
636
      "- `default_index_type` is the default index type, default is \"distributed-sequence\". More info about default index type could be found on Spark official [documentation](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)\n",
637
      "\n",
638
      "Here is an example code snippet for Spark Data:\n",
639
      "\n",
640
      "```python\n",
641
      "import pandas as pd\n",
642
      "from flaml.automl.spark.utils import to_pandas_on_spark\n",
643
      "\n",
644
      "# Creating a dictionary\n",
645
      "data = {\n",
646
      "    \"Square_Feet\": [800, 1200, 1800, 1500, 850],\n",
647
      "    \"Age_Years\": [20, 15, 10, 7, 25],\n",
648
      "    \"Price\": [100000, 200000, 300000, 240000, 120000],\n",
649
      "}\n",
650
      "\n",
651
      "# Creating a pandas DataFrame\n",
652
      "dataframe = pd.DataFrame(data)\n",
653
      "label = \"Price\"\n",
654
      "\n",
655
      "# Convert to pandas-on-spark dataframe\n",
656
      "psdf = to_pandas_on_spark(dataframe)\n",
657
      "```\n",
658
      "\n",
659
      "To use Spark ML models you need to format your data appropriately. Specifically, use [`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html) to merge all feature columns into a single vector column.\n",
660
      "\n",
661
      "Here is an example of how to use it:\n",
662
      "\n",
663
      "```python\n",
664
      "from pyspark.ml.feature import VectorAssembler\n",
665
      "\n",
666
      "columns = psdf.columns\n",
667
      "feature_cols = [col for col in columns if col != label]\n",
668
      "featurizer = VectorAssembler(inputCols=feature_cols, outputCol=\"features\")\n",
669
      "psdf = featurizer.transform(psdf.to_spark(index_col=\"index\"))[\"index\", \"features\"]\n",
670
      "```\n",
671
      "\n",
672
      "Later in conducting the experiment, use your pandas-on-spark data like non-spark data and pass them using `X_train, y_train` or `dataframe, label`.\n",
673
      "\n",
674
      "### Estimators\n",
675
      "\n",
676
      "#### Model List\n",
677
      "\n",
678
      "- `lgbm_spark`: The class for fine-tuning Spark version LightGBM models, using [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API.\n",
679
      "\n",
680
      "#### Usage\n",
681
      "\n",
682
      "First, prepare your data in the required format as described in the previous section.\n",
683
      "\n",
684
      "By including the models you intend to try in the `estimators_list` argument to `flaml.automl`, FLAML will start trying configurations for these models. If your input is Spark data, FLAML will also use estimators with the `_spark` postfix by default, even if you haven't specified them.\n",
685
      "\n",
686
      "Here is an example code snippet using SparkML models in AutoML:\n",
687
      "\n",
688
      "```python\n",
689
      "import flaml\n",
690
      "\n",
691
      "# prepare your data in pandas-on-spark format as we previously mentioned\n",
692
      "\n",
693
      "automl = flaml.AutoML()\n",
694
      "settings = {\n",
695
      "    \"time_budget\": 30,\n",
696
      "    \"metric\": \"r2\",\n",
697
      "    \"estimator_list\": [\"lgbm_spark\"],  # this setting is optional\n",
698
      "    \"task\": \"regression\",\n",
699
      "}\n",
700
      "\n",
701
      "automl.fit(\n",
702
      "    dataframe=psdf,\n",
703
      "    label=label,\n",
704
      "    **settings,\n",
705
      ")\n",
706
      "```\n",
707
      "\n",
708
      "[Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)\n",
709
      "\n",
710
      "## Parallel Spark Jobs\n",
711
      "\n",
712
      "You can activate Spark as the parallel backend during parallel tuning in both [AutoML](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning) and [Hyperparameter Tuning](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning), by setting the `use_spark` to `true`. FLAML will dispatch your job to the distributed Spark backend using [`joblib-spark`](https://github.com/joblib/joblib-spark).\n",
713
      "\n",
714
      "Please note that you should not set `use_spark` to `true` when applying AutoML and Tuning for Spark Data. This is because only SparkML models will be used for Spark Data in AutoML and Tuning. As SparkML models run in parallel, there is no need to distribute them with `use_spark` again.\n",
715
      "\n",
716
      "All the Spark-related arguments are stated below. These arguments are available in both Hyperparameter Tuning and AutoML:\n",
717
      "\n",
718
      "- `use_spark`: boolean, default=False | Whether to use spark to run the training in parallel spark jobs. This can be used to accelerate training on large models and large datasets, but will incur more overhead in time and thus slow down training in some cases. GPU training is not supported yet when use_spark is True. For Spark clusters, by default, we will launch one trial per executor. However, sometimes we want to launch more trials than the number of executors (e.g., local mode). In this case, we can set the environment variable `FLAML_MAX_CONCURRENT` to override the detected `num_executors`. The final number of concurrent trials will be the minimum of `n_concurrent_trials` and `num_executors`.\n",
719
      "- `n_concurrent_trials`: int, default=1 | The number of concurrent trials. When n_concurrent_trials > 1, FLAML performes parallel tuning.\n",
720
      "- `force_cancel`: boolean, default=False | Whether to forcely cancel Spark jobs if the search time exceeded the time budget. Spark jobs include parallel tuning jobs and Spark-based model training jobs.\n",
721
      "\n",
722
      "An example code snippet for using parallel Spark jobs:\n",
723
      "\n",
724
      "```python\n",
725
      "import flaml\n",
726
      "\n",
727
      "automl_experiment = flaml.AutoML()\n",
728
      "automl_settings = {\n",
729
      "    \"time_budget\": 30,\n",
730
      "    \"metric\": \"r2\",\n",
731
      "    \"task\": \"regression\",\n",
732
      "    \"n_concurrent_trials\": 2,\n",
733
      "    \"use_spark\": True,\n",
734
      "    \"force_cancel\": True,  # Activating the force_cancel option can immediately halt Spark jobs once they exceed the allocated time_budget.\n",
735
      "}\n",
736
      "\n",
737
      "automl.fit(\n",
738
      "    dataframe=dataframe,\n",
739
      "    label=label,\n",
740
      "    **automl_settings,\n",
741
      ")\n",
742
      "```\n",
743
      "\n",
744
      "[Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)\n",
745
      "\n",
746
      "\n",
747
      "\n",
748
      "--------------------------------------------------------------------------------\n",
749
      "\u001b[33mProduct_Manager\u001b[0m (to chat_manager):\n",
750
      "\n",
751
      "```python\n",
752
      "from flaml.automl import AutoML\n",
753
      "from flaml.automl.spark.utils import to_pandas_on_spark\n",
754
      "from pyspark.ml.feature import VectorAssembler\n",
755
      "import pandas as pd\n",
756
      "\n",
757
      "# Sample data in a dictionary\n",
758
      "data = {\n",
759
      "    \"Square_Feet\": [800, 1200, 1800, 1500, 850],\n",
760
      "    \"Age_Years\": [20, 15, 10, 7, 25],\n",
761
      "    \"Price\": [100000, 200000, 300000, 240000, 120000],\n",
762
      "}\n",
763
      "\n",
764
      "# Convert dictionary to pandas DataFrame\n",
765
      "dataframe = pd.DataFrame(data)\n",
766
      "label = \"Price\"\n",
767
      "\n",
768
      "# Convert pandas DataFrame to pandas-on-spark DataFrame\n",
769
      "psdf = to_pandas_on_spark(dataframe)\n",
770
      "\n",
771
      "# Use VectorAssembler to merge feature columns into a single vector column\n",
772
      "feature_cols = [col for col in psdf.columns if col != label]\n",
773
      "featurizer = VectorAssembler(inputCols=feature_cols, outputCol=\"features\")\n",
774
      "psdf = featurizer.transform(psdf.to_spark(index_col=\"index\"))[\"index\", \"features\", label]\n",
775
      "\n",
776
      "# Initialize AutoML instance\n",
777
      "automl = AutoML()\n",
778
      "\n",
779
      "# AutoML settings\n",
780
      "automl_settings = {\n",
781
      "    \"time_budget\": 30,  # Total running time in seconds\n",
782
      "    \"metric\": \"r2\",     # Evaluation metric\n",
783
      "    \"task\": \"regression\",\n",
784
      "    \"n_concurrent_trials\": 2,   # Number of concurrent Spark jobs\n",
785
      "    \"use_spark\": True,          # Enable Spark for parallel training\n",
786
      "    \"force_cancel\": True,       # Force cancel Spark jobs if they exceed the time budget\n",
787
      "    \"estimator_list\": [\"lgbm_spark\"]  # Optional: Specific estimator to use\n",
788
      "}\n",
789
      "\n",
790
      "# Run AutoML fit with pandas-on-spark dataframe\n",
791
      "automl.fit(\n",
792
      "    dataframe=psdf,\n",
793
      "    label=label,\n",
794
      "    **automl_settings,\n",
795
      ")\n",
796
      "```\n",
797
      "TERMINATE\n",
798
      "\n",
799
      "--------------------------------------------------------------------------------\n"
800
     ]
801
    }
802
   ],
803
   "source": [
804
    "rag_chat()\n",
805
    "# type exit to terminate the chat"
806
   ]
807
  },
808
  {
809
   "attachments": {},
810
   "cell_type": "markdown",
811
   "metadata": {},
812
   "source": [
813
    "### Call RetrieveUserProxyAgent while init chat with another user proxy agent\n",
814
    "Sometimes, there might be a need to use RetrieveUserProxyAgent in group chat without initializing the chat with it. In such scenarios, it becomes essential to create a function that wraps the RAG agents and allows them to be called from other agents."
815
   ]
816
  },
817
  {
818
   "cell_type": "code",
819
   "execution_count": 5,
820
   "metadata": {},
821
   "outputs": [
822
    {
823
     "name": "stdout",
824
     "output_type": "stream",
825
     "text": [
826
      "\u001b[33mBoss\u001b[0m (to chat_manager):\n",
827
      "\n",
828
      "How to use spark for parallel training in FLAML? Give me sample code.\n",
829
      "\n",
830
      "--------------------------------------------------------------------------------\n",
831
      "\u001b[33mProduct_Manager\u001b[0m (to chat_manager):\n",
832
      "\n",
833
      "\u001b[32m***** Suggested function call: retrieve_content *****\u001b[0m\n",
834
      "Arguments: \n",
835
      "{\"message\":\"using Apache Spark for parallel training in FLAML with sample code\"}\n",
836
      "\u001b[32m*****************************************************\u001b[0m\n",
837
      "\n",
838
      "--------------------------------------------------------------------------------\n",
839
      "\u001b[35m\n",
840
      ">>>>>>>> EXECUTING FUNCTION retrieve_content...\u001b[0m\n"
841
     ]
842
    },
843
    {
844
     "name": "stderr",
845
     "output_type": "stream",
846
     "text": [
847
      "Number of requested results 3 is greater than number of elements in index 1, updating n_results = 1\n",
848
      "Model gpt4-1106-preview not found. Using cl100k_base encoding.\n"
849
     ]
850
    },
851
    {
852
     "name": "stdout",
853
     "output_type": "stream",
854
     "text": [
855
      "VectorDB returns doc_ids:  [['bdfbc921']]\n",
856
      "\u001b[32mAdding content of doc bdfbc921 to context.\u001b[0m\n",
857
      "\u001b[33mBoss\u001b[0m (to chat_manager):\n",
858
      "\n",
859
      "\u001b[32m***** Response from calling function (retrieve_content) *****\u001b[0m\n",
860
      "You're a retrieve augmented coding assistant. You answer user's questions based on your own knowledge and the\n",
861
      "context provided by the user.\n",
862
      "If you can't answer the question with or without the current context, you should reply exactly `UPDATE CONTEXT`.\n",
863
      "For code generation, you must obey the following rules:\n",
864
      "Rule 1. You MUST NOT install any packages because all the packages needed are already installed.\n",
865
      "Rule 2. You must follow the formats below to write your code:\n",
866
      "```language\n",
867
      "# your code\n",
868
      "```\n",
869
      "\n",
870
      "User's question is: using Apache Spark for parallel training in FLAML with sample code\n",
871
      "\n",
872
      "Context is: # Integrate - Spark\n",
873
      "\n",
874
      "FLAML has integrated Spark for distributed training. There are two main aspects of integration with Spark:\n",
875
      "\n",
876
      "- Use Spark ML estimators for AutoML.\n",
877
      "- Use Spark to run training in parallel spark jobs.\n",
878
      "\n",
879
      "## Spark ML Estimators\n",
880
      "\n",
881
      "FLAML integrates estimators based on Spark ML models. These models are trained in parallel using Spark, so we called them Spark estimators. To use these models, you first need to organize your data in the required format.\n",
882
      "\n",
883
      "### Data\n",
884
      "\n",
885
      "For Spark estimators, AutoML only consumes Spark data. FLAML provides a convenient function `to_pandas_on_spark` in the `flaml.automl.spark.utils` module to convert your data into a pandas-on-spark (`pyspark.pandas`) dataframe/series, which Spark estimators require.\n",
886
      "\n",
887
      "This utility function takes data in the form of a `pandas.Dataframe` or `pyspark.sql.Dataframe` and converts it into a pandas-on-spark dataframe. It also takes `pandas.Series` or `pyspark.sql.Dataframe` and converts it into a [pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html) series. If you pass in a `pyspark.pandas.Dataframe`, it will not make any changes.\n",
888
      "\n",
889
      "This function also accepts optional arguments `index_col` and `default_index_type`.\n",
890
      "\n",
891
      "- `index_col` is the column name to use as the index, default is None.\n",
892
      "- `default_index_type` is the default index type, default is \"distributed-sequence\". More info about default index type could be found on Spark official [documentation](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)\n",
893
      "\n",
894
      "Here is an example code snippet for Spark Data:\n",
895
      "\n",
896
      "```python\n",
897
      "import pandas as pd\n",
898
      "from flaml.automl.spark.utils import to_pandas_on_spark\n",
899
      "\n",
900
      "# Creating a dictionary\n",
901
      "data = {\n",
902
      "    \"Square_Feet\": [800, 1200, 1800, 1500, 850],\n",
903
      "    \"Age_Years\": [20, 15, 10, 7, 25],\n",
904
      "    \"Price\": [100000, 200000, 300000, 240000, 120000],\n",
905
      "}\n",
906
      "\n",
907
      "# Creating a pandas DataFrame\n",
908
      "dataframe = pd.DataFrame(data)\n",
909
      "label = \"Price\"\n",
910
      "\n",
911
      "# Convert to pandas-on-spark dataframe\n",
912
      "psdf = to_pandas_on_spark(dataframe)\n",
913
      "```\n",
914
      "\n",
915
      "To use Spark ML models you need to format your data appropriately. Specifically, use [`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html) to merge all feature columns into a single vector column.\n",
916
      "\n",
917
      "Here is an example of how to use it:\n",
918
      "\n",
919
      "```python\n",
920
      "from pyspark.ml.feature import VectorAssembler\n",
921
      "\n",
922
      "columns = psdf.columns\n",
923
      "feature_cols = [col for col in columns if col != label]\n",
924
      "featurizer = VectorAssembler(inputCols=feature_cols, outputCol=\"features\")\n",
925
      "psdf = featurizer.transform(psdf.to_spark(index_col=\"index\"))[\"index\", \"features\"]\n",
926
      "```\n",
927
      "\n",
928
      "Later in conducting the experiment, use your pandas-on-spark data like non-spark data and pass them using `X_train, y_train` or `dataframe, label`.\n",
929
      "\n",
930
      "### Estimators\n",
931
      "\n",
932
      "#### Model List\n",
933
      "\n",
934
      "- `lgbm_spark`: The class for fine-tuning Spark version LightGBM models, using [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API.\n",
935
      "\n",
936
      "#### Usage\n",
937
      "\n",
938
      "First, prepare your data in the required format as described in the previous section.\n",
939
      "\n",
940
      "By including the models you intend to try in the `estimators_list` argument to `flaml.automl`, FLAML will start trying configurations for these models. If your input is Spark data, FLAML will also use estimators with the `_spark` postfix by default, even if you haven't specified them.\n",
941
      "\n",
942
      "Here is an example code snippet using SparkML models in AutoML:\n",
943
      "\n",
944
      "```python\n",
945
      "import flaml\n",
946
      "\n",
947
      "# prepare your data in pandas-on-spark format as we previously mentioned\n",
948
      "\n",
949
      "automl = flaml.AutoML()\n",
950
      "settings = {\n",
951
      "    \"time_budget\": 30,\n",
952
      "    \"metric\": \"r2\",\n",
953
      "    \"estimator_list\": [\"lgbm_spark\"],  # this setting is optional\n",
954
      "    \"task\": \"regression\",\n",
955
      "}\n",
956
      "\n",
957
      "automl.fit(\n",
958
      "    dataframe=psdf,\n",
959
      "    label=label,\n",
960
      "    **settings,\n",
961
      ")\n",
962
      "```\n",
963
      "\n",
964
      "[Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)\n",
965
      "\n",
966
      "## Parallel Spark Jobs\n",
967
      "\n",
968
      "You can activate Spark as the parallel backend during parallel tuning in both [AutoML](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning) and [Hyperparameter Tuning](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning), by setting the `use_spark` to `true`. FLAML will dispatch your job to the distributed Spark backend using [`joblib-spark`](https://github.com/joblib/joblib-spark).\n",
969
      "\n",
970
      "Please note that you should not set `use_spark` to `true` when applying AutoML and Tuning for Spark Data. This is because only SparkML models will be used for Spark Data in AutoML and Tuning. As SparkML models run in parallel, there is no need to distribute them with `use_spark` again.\n",
971
      "\n",
972
      "All the Spark-related arguments are stated below. These arguments are available in both Hyperparameter Tuning and AutoML:\n",
973
      "\n",
974
      "- `use_spark`: boolean, default=False | Whether to use spark to run the training in parallel spark jobs. This can be used to accelerate training on large models and large datasets, but will incur more overhead in time and thus slow down training in some cases. GPU training is not supported yet when use_spark is True. For Spark clusters, by default, we will launch one trial per executor. However, sometimes we want to launch more trials than the number of executors (e.g., local mode). In this case, we can set the environment variable `FLAML_MAX_CONCURRENT` to override the detected `num_executors`. The final number of concurrent trials will be the minimum of `n_concurrent_trials` and `num_executors`.\n",
975
      "- `n_concurrent_trials`: int, default=1 | The number of concurrent trials. When n_concurrent_trials > 1, FLAML performes parallel tuning.\n",
976
      "- `force_cancel`: boolean, default=False | Whether to forcely cancel Spark jobs if the search time exceeded the time budget. Spark jobs include parallel tuning jobs and Spark-based model training jobs.\n",
977
      "\n",
978
      "An example code snippet for using parallel Spark jobs:\n",
979
      "\n",
980
      "```python\n",
981
      "import flaml\n",
982
      "\n",
983
      "automl_experiment = flaml.AutoML()\n",
984
      "automl_settings = {\n",
985
      "    \"time_budget\": 30,\n",
986
      "    \"metric\": \"r2\",\n",
987
      "    \"task\": \"regression\",\n",
988
      "    \"n_concurrent_trials\": 2,\n",
989
      "    \"use_spark\": True,\n",
990
      "    \"force_cancel\": True,  # Activating the force_cancel option can immediately halt Spark jobs once they exceed the allocated time_budget.\n",
991
      "}\n",
992
      "\n",
993
      "automl.fit(\n",
994
      "    dataframe=dataframe,\n",
995
      "    label=label,\n",
996
      "    **automl_settings,\n",
997
      ")\n",
998
      "```\n",
999
      "\n",
1000
      "[Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)\n",
1001
      "\n",
1002
      "\n",
1003
      "\u001b[32m*************************************************************\u001b[0m\n",
1004
      "\n",
1005
      "--------------------------------------------------------------------------------\n",
1006
      "\u001b[33mBoss\u001b[0m (to chat_manager):\n",
1007
      "\n",
1008
      "\u001b[32m***** Response from calling function (retrieve_content) *****\u001b[0m\n",
1009
      "You're a retrieve augmented coding assistant. You answer user's questions based on your own knowledge and the\n",
1010
      "context provided by the user.\n",
1011
      "If you can't answer the question with or without the current context, you should reply exactly `UPDATE CONTEXT`.\n",
1012
      "For code generation, you must obey the following rules:\n",
1013
      "Rule 1. You MUST NOT install any packages because all the packages needed are already installed.\n",
1014
      "Rule 2. You must follow the formats below to write your code:\n",
1015
      "```language\n",
1016
      "# your code\n",
1017
      "```\n",
1018
      "\n",
1019
      "User's question is: using Apache Spark for parallel training in FLAML with sample code\n",
1020
      "\n",
1021
      "Context is: # Integrate - Spark\n",
1022
      "\n",
1023
      "FLAML has integrated Spark for distributed training. There are two main aspects of integration with Spark:\n",
1024
      "\n",
1025
      "- Use Spark ML estimators for AutoML.\n",
1026
      "- Use Spark to run training in parallel spark jobs.\n",
1027
      "\n",
1028
      "## Spark ML Estimators\n",
1029
      "\n",
1030
      "FLAML integrates estimators based on Spark ML models. These models are trained in parallel using Spark, so we called them Spark estimators. To use these models, you first need to organize your data in the required format.\n",
1031
      "\n",
1032
      "### Data\n",
1033
      "\n",
1034
      "For Spark estimators, AutoML only consumes Spark data. FLAML provides a convenient function `to_pandas_on_spark` in the `flaml.automl.spark.utils` module to convert your data into a pandas-on-spark (`pyspark.pandas`) dataframe/series, which Spark estimators require.\n",
1035
      "\n",
1036
      "This utility function takes data in the form of a `pandas.Dataframe` or `pyspark.sql.Dataframe` and converts it into a pandas-on-spark dataframe. It also takes `pandas.Series` or `pyspark.sql.Dataframe` and converts it into a [pandas-on-spark](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/index.html) series. If you pass in a `pyspark.pandas.Dataframe`, it will not make any changes.\n",
1037
      "\n",
1038
      "This function also accepts optional arguments `index_col` and `default_index_type`.\n",
1039
      "\n",
1040
      "- `index_col` is the column name to use as the index, default is None.\n",
1041
      "- `default_index_type` is the default index type, default is \"distributed-sequence\". More info about default index type could be found on Spark official [documentation](https://spark.apache.org/docs/latest/api/python/user_guide/pandas_on_spark/options.html#default-index-type)\n",
1042
      "\n",
1043
      "Here is an example code snippet for Spark Data:\n",
1044
      "\n",
1045
      "```python\n",
1046
      "import pandas as pd\n",
1047
      "from flaml.automl.spark.utils import to_pandas_on_spark\n",
1048
      "\n",
1049
      "# Creating a dictionary\n",
1050
      "data = {\n",
1051
      "    \"Square_Feet\": [800, 1200, 1800, 1500, 850],\n",
1052
      "    \"Age_Years\": [20, 15, 10, 7, 25],\n",
1053
      "    \"Price\": [100000, 200000, 300000, 240000, 120000],\n",
1054
      "}\n",
1055
      "\n",
1056
      "# Creating a pandas DataFrame\n",
1057
      "dataframe = pd.DataFrame(data)\n",
1058
      "label = \"Price\"\n",
1059
      "\n",
1060
      "# Convert to pandas-on-spark dataframe\n",
1061
      "psdf = to_pandas_on_spark(dataframe)\n",
1062
      "```\n",
1063
      "\n",
1064
      "To use Spark ML models you need to format your data appropriately. Specifically, use [`VectorAssembler`](https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.ml.feature.VectorAssembler.html) to merge all feature columns into a single vector column.\n",
1065
      "\n",
1066
      "Here is an example of how to use it:\n",
1067
      "\n",
1068
      "```python\n",
1069
      "from pyspark.ml.feature import VectorAssembler\n",
1070
      "\n",
1071
      "columns = psdf.columns\n",
1072
      "feature_cols = [col for col in columns if col != label]\n",
1073
      "featurizer = VectorAssembler(inputCols=feature_cols, outputCol=\"features\")\n",
1074
      "psdf = featurizer.transform(psdf.to_spark(index_col=\"index\"))[\"index\", \"features\"]\n",
1075
      "```\n",
1076
      "\n",
1077
      "Later in conducting the experiment, use your pandas-on-spark data like non-spark data and pass them using `X_train, y_train` or `dataframe, label`.\n",
1078
      "\n",
1079
      "### Estimators\n",
1080
      "\n",
1081
      "#### Model List\n",
1082
      "\n",
1083
      "- `lgbm_spark`: The class for fine-tuning Spark version LightGBM models, using [SynapseML](https://microsoft.github.io/SynapseML/docs/features/lightgbm/about/) API.\n",
1084
      "\n",
1085
      "#### Usage\n",
1086
      "\n",
1087
      "First, prepare your data in the required format as described in the previous section.\n",
1088
      "\n",
1089
      "By including the models you intend to try in the `estimators_list` argument to `flaml.automl`, FLAML will start trying configurations for these models. If your input is Spark data, FLAML will also use estimators with the `_spark` postfix by default, even if you haven't specified them.\n",
1090
      "\n",
1091
      "Here is an example code snippet using SparkML models in AutoML:\n",
1092
      "\n",
1093
      "```python\n",
1094
      "import flaml\n",
1095
      "\n",
1096
      "# prepare your data in pandas-on-spark format as we previously mentioned\n",
1097
      "\n",
1098
      "automl = flaml.AutoML()\n",
1099
      "settings = {\n",
1100
      "    \"time_budget\": 30,\n",
1101
      "    \"metric\": \"r2\",\n",
1102
      "    \"estimator_list\": [\"lgbm_spark\"],  # this setting is optional\n",
1103
      "    \"task\": \"regression\",\n",
1104
      "}\n",
1105
      "\n",
1106
      "automl.fit(\n",
1107
      "    dataframe=psdf,\n",
1108
      "    label=label,\n",
1109
      "    **settings,\n",
1110
      ")\n",
1111
      "```\n",
1112
      "\n",
1113
      "[Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_bankrupt_synapseml.ipynb)\n",
1114
      "\n",
1115
      "## Parallel Spark Jobs\n",
1116
      "\n",
1117
      "You can activate Spark as the parallel backend during parallel tuning in both [AutoML](/docs/Use-Cases/Task-Oriented-AutoML#parallel-tuning) and [Hyperparameter Tuning](/docs/Use-Cases/Tune-User-Defined-Function#parallel-tuning), by setting the `use_spark` to `true`. FLAML will dispatch your job to the distributed Spark backend using [`joblib-spark`](https://github.com/joblib/joblib-spark).\n",
1118
      "\n",
1119
      "Please note that you should not set `use_spark` to `true` when applying AutoML and Tuning for Spark Data. This is because only SparkML models will be used for Spark Data in AutoML and Tuning. As SparkML models run in parallel, there is no need to distribute them with `use_spark` again.\n",
1120
      "\n",
1121
      "All the Spark-related arguments are stated below. These arguments are available in both Hyperparameter Tuning and AutoML:\n",
1122
      "\n",
1123
      "- `use_spark`: boolean, default=False | Whether to use spark to run the training in parallel spark jobs. This can be used to accelerate training on large models and large datasets, but will incur more overhead in time and thus slow down training in some cases. GPU training is not supported yet when use_spark is True. For Spark clusters, by default, we will launch one trial per executor. However, sometimes we want to launch more trials than the number of executors (e.g., local mode). In this case, we can set the environment variable `FLAML_MAX_CONCURRENT` to override the detected `num_executors`. The final number of concurrent trials will be the minimum of `n_concurrent_trials` and `num_executors`.\n",
1124
      "- `n_concurrent_trials`: int, default=1 | The number of concurrent trials. When n_concurrent_trials > 1, FLAML performes parallel tuning.\n",
1125
      "- `force_cancel`: boolean, default=False | Whether to forcely cancel Spark jobs if the search time exceeded the time budget. Spark jobs include parallel tuning jobs and Spark-based model training jobs.\n",
1126
      "\n",
1127
      "An example code snippet for using parallel Spark jobs:\n",
1128
      "\n",
1129
      "```python\n",
1130
      "import flaml\n",
1131
      "\n",
1132
      "automl_experiment = flaml.AutoML()\n",
1133
      "automl_settings = {\n",
1134
      "    \"time_budget\": 30,\n",
1135
      "    \"metric\": \"r2\",\n",
1136
      "    \"task\": \"regression\",\n",
1137
      "    \"n_concurrent_trials\": 2,\n",
1138
      "    \"use_spark\": True,\n",
1139
      "    \"force_cancel\": True,  # Activating the force_cancel option can immediately halt Spark jobs once they exceed the allocated time_budget.\n",
1140
      "}\n",
1141
      "\n",
1142
      "automl.fit(\n",
1143
      "    dataframe=dataframe,\n",
1144
      "    label=label,\n",
1145
      "    **automl_settings,\n",
1146
      ")\n",
1147
      "```\n",
1148
      "\n",
1149
      "[Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/integrate_spark.ipynb)\n",
1150
      "\n",
1151
      "\n",
1152
      "\u001b[32m*************************************************************\u001b[0m\n",
1153
      "\n",
1154
      "--------------------------------------------------------------------------------\n",
1155
      "\u001b[33mProduct_Manager\u001b[0m (to chat_manager):\n",
1156
      "\n",
1157
      "To use Apache Spark for parallel training in FLAML, you can follow these steps:\n",
1158
      "\n",
1159
      "1. Ensure your data is in the required pandas-on-spark format.\n",
1160
      "2. Use Spark ML estimators by including them in the `estimator_list`.\n",
1161
      "3. Set `use_spark` to `True` for parallel tuning.\n",
1162
      "\n",
1163
      "Here's a sample code demonstrating how to use Spark for parallel training in FLAML:\n",
1164
      "\n",
1165
      "```python\n",
1166
      "import flaml\n",
1167
      "from flaml.automl.spark.utils import to_pandas_on_spark\n",
1168
      "import pandas as pd\n",
1169
      "from pyspark.ml.feature import VectorAssembler\n",
1170
      "\n",
1171
      "# Sample data in a pandas DataFrame\n",
1172
      "data = {\n",
1173
      "    \"Square_Feet\": [800, 1200, 1800, 1500, 850],\n",
1174
      "    \"Age_Years\": [20, 15, 10, 7, 25],\n",
1175
      "    \"Price\": [100000, 200000, 300000, 240000, 120000],\n",
1176
      "}\n",
1177
      "label = \"Price\"\n",
1178
      "\n",
1179
      "# Creating a pandas DataFrame\n",
1180
      "dataframe = pd.DataFrame(data)\n",
1181
      "\n",
1182
      "# Convert to pandas-on-spark dataframe\n",
1183
      "psdf = to_pandas_on_spark(dataframe)\n",
1184
      "\n",
1185
      "# Prepare features using VectorAssembler\n",
1186
      "columns = psdf.columns\n",
1187
      "feature_cols = [col for col in columns if col != label]\n",
1188
      "featurizer = VectorAssembler(inputCols=feature_cols, outputCol=\"features\")\n",
1189
      "psdf = featurizer.transform(psdf.to_spark(index_col=\"index\"))[\"index\", \"features\"]\n",
1190
      "\n",
1191
      "# Initialize AutoML\n",
1192
      "automl = flaml.AutoML()\n",
1193
      "\n",
1194
      "# Configure settings for AutoML\n",
1195
      "settings = {\n",
1196
      "    \"time_budget\": 30,  # time budget in seconds\n",
1197
      "    \"metric\": \"r2\",\n",
1198
      "    \"estimator_list\": [\"lgbm_spark\"],  # using Spark ML estimators\n",
1199
      "    \"task\": \"regression\",\n",
1200
      "    \"n_concurrent_trials\": 2,  # number of parallel trials\n",
1201
      "    \"use_spark\": True,  # enable parallel training using Spark\n",
1202
      "    \"force_cancel\": True,  # force cancel Spark jobs if time_budget is exceeded\n",
1203
      "}\n",
1204
      "\n",
1205
      "# Start the training\n",
1206
      "automl.fit(dataframe=psdf, label=label, **settings)\n",
1207
      "```\n",
1208
      "\n",
1209
      "In this code snippet:\n",
1210
      "- The `to_pandas_on_spark` function is used to convert the pandas DataFrame to a pandas-on-spark DataFrame.\n",
1211
      "- `VectorAssembler` is used to transform feature columns into a single vector column.\n",
1212
      "- The `AutoML` object is created, and settings are configured for the AutoML run, including setting `use_spark` to `True` for parallel training.\n",
1213
      "- The `fit` method is called to start the automated machine learning process.\n",
1214
      "\n",
1215
      "By using these settings, FLAML will train the models in parallel using Spark, which can accelerate the training process on large models and datasets.\n",
1216
      "\n",
1217
      "TERMINATE\n",
1218
      "\n",
1219
      "--------------------------------------------------------------------------------\n"
1220
     ]
1221
    }
1222
   ],
1223
   "source": [
1224
    "call_rag_chat()"
1225
   ]
1226
  },
1227
  {
1228
   "cell_type": "code",
1229
   "execution_count": null,
1230
   "metadata": {},
1231
   "outputs": [],
1232
   "source": []
1233
  }
1234
 ],
1235
 "metadata": {
1236
  "front_matter": {
1237
   "description": "Implement and manage a multi-agent chat system using AutoGen, where AI assistants retrieve information, generate code, and interact collaboratively to solve complex tasks, especially in areas not covered by their training data.",
1238
   "tags": [
1239
    "group chat",
1240
    "orchestration",
1241
    "RAG"
1242
   ]
1243
  },
1244
  "kernelspec": {
1245
   "display_name": "flaml",
1246
   "language": "python",
1247
   "name": "python3"
1248
  },
1249
  "language_info": {
1250
   "codemirror_mode": {
1251
    "name": "ipython",
1252
    "version": 3
1253
   },
1254
   "file_extension": ".py",
1255
   "mimetype": "text/x-python",
1256
   "name": "python",
1257
   "nbconvert_exporter": "python",
1258
   "pygments_lexer": "ipython3",
1259
   "version": "3.10.13"
1260
  }
1261
 },
1262
 "nbformat": 4,
1263
 "nbformat_minor": 2
1264
}
1265

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

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

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

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