File size: 31,222 Bytes
ed4d993
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# CAMEL Role-Playing Autonomous Cooperative Agents\n",
    "\n",
    "This is a langchain implementation of paper: \"CAMEL: Communicative Agents for “MindExploration of Large Scale Language Model Society\".\n",
    "\n",
    "Overview:\n",
    "\n",
    "The rapid advancement of conversational and chat-based language models has led to remarkable progress in complex task-solving. However, their success heavily relies on human input to guide the conversation, which can be challenging and time-consuming. This paper explores the potential of building scalable techniques to facilitate autonomous cooperation among communicative agents and provide insight into their \"cognitive\" processes. To address the challenges of achieving autonomous cooperation, we propose a novel communicative agent framework named role-playing. Our approach involves using inception prompting to guide chat agents toward task completion while maintaining consistency with human intentions. We showcase how role-playing can be used to generate conversational data for studying the behaviors and capabilities of chat agents, providing a valuable resource for investigating conversational language models. Our contributions include introducing a novel communicative agent framework, offering a scalable approach for studying the cooperative behaviors and capabilities of multi-agent systems, and open-sourcing our library to support research on communicative agents and beyond.\n",
    "\n",
    "The original implementation: https://github.com/lightaime/camel\n",
    "\n",
    "Project website: https://www.camel-ai.org/\n",
    "\n",
    "Arxiv paper: https://arxiv.org/abs/2303.17760\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Import LangChain related modules "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "\n",
    "from langchain.prompts.chat import (\n",
    "    HumanMessagePromptTemplate,\n",
    "    SystemMessagePromptTemplate,\n",
    ")\n",
    "from langchain.schema import (\n",
    "    AIMessage,\n",
    "    BaseMessage,\n",
    "    HumanMessage,\n",
    "    SystemMessage,\n",
    ")\n",
    "from langchain_openai import ChatOpenAI"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Define a CAMEL agent helper class"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "class CAMELAgent:\n",
    "    def __init__(\n",
    "        self,\n",
    "        system_message: SystemMessage,\n",
    "        model: ChatOpenAI,\n",
    "    ) -> None:\n",
    "        self.system_message = system_message\n",
    "        self.model = model\n",
    "        self.init_messages()\n",
    "\n",
    "    def reset(self) -> None:\n",
    "        self.init_messages()\n",
    "        return self.stored_messages\n",
    "\n",
    "    def init_messages(self) -> None:\n",
    "        self.stored_messages = [self.system_message]\n",
    "\n",
    "    def update_messages(self, message: BaseMessage) -> List[BaseMessage]:\n",
    "        self.stored_messages.append(message)\n",
    "        return self.stored_messages\n",
    "\n",
    "    def step(\n",
    "        self,\n",
    "        input_message: HumanMessage,\n",
    "    ) -> AIMessage:\n",
    "        messages = self.update_messages(input_message)\n",
    "\n",
    "        output_message = self.model.invoke(messages)\n",
    "        self.update_messages(output_message)\n",
    "\n",
    "        return output_message"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup OpenAI API key and roles and task for role-playing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"\"\n",
    "\n",
    "assistant_role_name = \"Python Programmer\"\n",
    "user_role_name = \"Stock Trader\"\n",
    "task = \"Develop a trading bot for the stock market\"\n",
    "word_limit = 50  # word limit for task brainstorming"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create a task specify agent for brainstorming and get the specified task"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Specified task: Develop a Python-based swing trading bot that scans market trends, monitors stocks, and generates trading signals to help a stock trader to place optimal buy and sell orders with defined stop losses and profit targets.\n"
     ]
    }
   ],
   "source": [
    "task_specifier_sys_msg = SystemMessage(content=\"You can make a task more specific.\")\n",
    "task_specifier_prompt = \"\"\"Here is a task that {assistant_role_name} will help {user_role_name} to complete: {task}.\n",
    "Please make it more specific. Be creative and imaginative.\n",
    "Please reply with the specified task in {word_limit} words or less. Do not add anything else.\"\"\"\n",
    "task_specifier_template = HumanMessagePromptTemplate.from_template(\n",
    "    template=task_specifier_prompt\n",
    ")\n",
    "task_specify_agent = CAMELAgent(task_specifier_sys_msg, ChatOpenAI(temperature=1.0))\n",
    "task_specifier_msg = task_specifier_template.format_messages(\n",
    "    assistant_role_name=assistant_role_name,\n",
    "    user_role_name=user_role_name,\n",
    "    task=task,\n",
    "    word_limit=word_limit,\n",
    ")[0]\n",
    "specified_task_msg = task_specify_agent.step(task_specifier_msg)\n",
    "print(f\"Specified task: {specified_task_msg.content}\")\n",
    "specified_task = specified_task_msg.content"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create inception prompts for AI assistant and AI user for role-playing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "assistant_inception_prompt = \"\"\"Never forget you are a {assistant_role_name} and I am a {user_role_name}. Never flip roles! Never instruct me!\n",
    "We share a common interest in collaborating to successfully complete a task.\n",
    "You must help me to complete the task.\n",
    "Here is the task: {task}. Never forget our task!\n",
    "I must instruct you based on your expertise and my needs to complete the task.\n",
    "\n",
    "I must give you one instruction at a time.\n",
    "You must write a specific solution that appropriately completes the requested instruction.\n",
    "You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\n",
    "Do not add anything else other than your solution to my instruction.\n",
    "You are never supposed to ask me any questions you only answer questions.\n",
    "You are never supposed to reply with a flake solution. Explain your solutions.\n",
    "Your solution must be declarative sentences and simple present tense.\n",
    "Unless I say the task is completed, you should always start with:\n",
    "\n",
    "Solution: <YOUR_SOLUTION>\n",
    "\n",
    "<YOUR_SOLUTION> should be specific and provide preferable implementations and examples for task-solving.\n",
    "Always end <YOUR_SOLUTION> with: Next request.\"\"\"\n",
    "\n",
    "user_inception_prompt = \"\"\"Never forget you are a {user_role_name} and I am a {assistant_role_name}. Never flip roles! You will always instruct me.\n",
    "We share a common interest in collaborating to successfully complete a task.\n",
    "I must help you to complete the task.\n",
    "Here is the task: {task}. Never forget our task!\n",
    "You must instruct me based on my expertise and your needs to complete the task ONLY in the following two ways:\n",
    "\n",
    "1. Instruct with a necessary input:\n",
    "Instruction: <YOUR_INSTRUCTION>\n",
    "Input: <YOUR_INPUT>\n",
    "\n",
    "2. Instruct without any input:\n",
    "Instruction: <YOUR_INSTRUCTION>\n",
    "Input: None\n",
    "\n",
    "The \"Instruction\" describes a task or question. The paired \"Input\" provides further context or information for the requested \"Instruction\".\n",
    "\n",
    "You must give me one instruction at a time.\n",
    "I must write a response that appropriately completes the requested instruction.\n",
    "I must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.\n",
    "You should instruct me not ask me questions.\n",
    "Now you must start to instruct me using the two ways described above.\n",
    "Do not add anything else other than your instruction and the optional corresponding input!\n",
    "Keep giving me instructions and necessary inputs until you think the task is completed.\n",
    "When the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.\n",
    "Never say <CAMEL_TASK_DONE> unless my responses have solved your task.\"\"\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create a helper helper to get system messages for AI assistant and AI user from role names and the task"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_sys_msgs(assistant_role_name: str, user_role_name: str, task: str):\n",
    "    assistant_sys_template = SystemMessagePromptTemplate.from_template(\n",
    "        template=assistant_inception_prompt\n",
    "    )\n",
    "    assistant_sys_msg = assistant_sys_template.format_messages(\n",
    "        assistant_role_name=assistant_role_name,\n",
    "        user_role_name=user_role_name,\n",
    "        task=task,\n",
    "    )[0]\n",
    "\n",
    "    user_sys_template = SystemMessagePromptTemplate.from_template(\n",
    "        template=user_inception_prompt\n",
    "    )\n",
    "    user_sys_msg = user_sys_template.format_messages(\n",
    "        assistant_role_name=assistant_role_name,\n",
    "        user_role_name=user_role_name,\n",
    "        task=task,\n",
    "    )[0]\n",
    "\n",
    "    return assistant_sys_msg, user_sys_msg"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create AI assistant agent and AI user agent from obtained system messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "assistant_sys_msg, user_sys_msg = get_sys_msgs(\n",
    "    assistant_role_name, user_role_name, specified_task\n",
    ")\n",
    "assistant_agent = CAMELAgent(assistant_sys_msg, ChatOpenAI(temperature=0.2))\n",
    "user_agent = CAMELAgent(user_sys_msg, ChatOpenAI(temperature=0.2))\n",
    "\n",
    "# Reset agents\n",
    "assistant_agent.reset()\n",
    "user_agent.reset()\n",
    "\n",
    "# Initialize chats\n",
    "user_msg = HumanMessage(\n",
    "    content=(\n",
    "        f\"{user_sys_msg.content}. \"\n",
    "        \"Now start to give me introductions one by one. \"\n",
    "        \"Only reply with Instruction and Input.\"\n",
    "    )\n",
    ")\n",
    "\n",
    "assistant_msg = HumanMessage(content=f\"{assistant_sys_msg.content}\")\n",
    "assistant_msg = assistant_agent.step(user_msg)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Start role-playing session to solve the task!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original task prompt:\n",
      "Develop a trading bot for the stock market\n",
      "\n",
      "Specified task prompt:\n",
      "Develop a Python-based swing trading bot that scans market trends, monitors stocks, and generates trading signals to help a stock trader to place optimal buy and sell orders with defined stop losses and profit targets.\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Install the necessary Python libraries for data analysis and trading.\n",
      "Input: None\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can install the necessary Python libraries using pip, a package installer for Python. We can install pandas, numpy, matplotlib, and ta-lib for data analysis and trading. We can use the following command to install these libraries:\n",
      "\n",
      "```\n",
      "pip install pandas numpy matplotlib ta-lib\n",
      "```\n",
      "\n",
      "Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Import the necessary libraries in the Python script.\n",
      "Input: None\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can import the necessary libraries in the Python script using the import statement. We need to import pandas, numpy, matplotlib, and ta-lib for data analysis and trading. We can use the following code to import these libraries:\n",
      "\n",
      "```\n",
      "import pandas as pd\n",
      "import numpy as np\n",
      "import matplotlib.pyplot as plt\n",
      "import talib as ta\n",
      "```\n",
      "\n",
      "Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Load historical stock data into a pandas DataFrame.\n",
      "Input: The path to the CSV file containing the historical stock data.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can load historical stock data into a pandas DataFrame using the `read_csv()` function from pandas. We need to pass the path to the CSV file containing the historical stock data as an argument to this function. We can use the following code to load the historical stock data:\n",
      "\n",
      "```\n",
      "df = pd.read_csv('path/to/csv/file.csv')\n",
      "```\n",
      "\n",
      "This will load the historical stock data into a pandas DataFrame called `df`. Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Preprocess the historical stock data by setting the date column as the index and sorting the DataFrame in ascending order by date.\n",
      "Input: None.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can preprocess the historical stock data by setting the date column as the index and sorting the DataFrame in ascending order by date using the `set_index()` and `sort_index()` functions from pandas. We can use the following code to preprocess the historical stock data:\n",
      "\n",
      "```\n",
      "df = df.set_index('date')\n",
      "df = df.sort_index(ascending=True)\n",
      "```\n",
      "\n",
      "This will set the date column as the index and sort the DataFrame in ascending order by date. Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Calculate the short-term and long-term moving averages for the stock data using the `ta.SMA()` function from ta-lib.\n",
      "Input: The period for the short-term moving average and the period for the long-term moving average.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can calculate the short-term and long-term moving averages for the stock data using the `ta.SMA()` function from ta-lib. We need to pass the period for the short-term moving average and the period for the long-term moving average as arguments to this function. We can use the following code to calculate the short-term and long-term moving averages:\n",
      "\n",
      "```\n",
      "short_ma = ta.SMA(df['close'], timeperiod=short_period)\n",
      "long_ma = ta.SMA(df['close'], timeperiod=long_period)\n",
      "```\n",
      "\n",
      "This will calculate the short-term and long-term moving averages for the stock data and store them in the `short_ma` and `long_ma` variables, respectively. Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Create a new DataFrame that combines the historical stock data with the short-term and long-term moving averages.\n",
      "Input: None.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can create a new DataFrame that combines the historical stock data with the short-term and long-term moving averages using the `concat()` function from pandas. We need to pass the historical stock data, the short-term moving average, and the long-term moving average as arguments to this function. We can use the following code to create the new DataFrame:\n",
      "\n",
      "```\n",
      "new_df = pd.concat([df, short_ma, long_ma], axis=1)\n",
      "new_df.columns = ['open', 'high', 'low', 'close', 'volume', 'short_ma', 'long_ma']\n",
      "```\n",
      "\n",
      "This will create a new DataFrame called `new_df` that combines the historical stock data with the short-term and long-term moving averages. The columns of the new DataFrame are named 'open', 'high', 'low', 'close', 'volume', 'short_ma', and 'long_ma'. Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Create a new column in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages.\n",
      "Input: None.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can create a new column in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages. We can use the following code to create the new column:\n",
      "\n",
      "```\n",
      "new_df['signal'] = np.where(new_df['short_ma'] > new_df['long_ma'], 1, -1)\n",
      "```\n",
      "\n",
      "This will create a new column called 'signal' in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages. If the short-term moving average is greater than the long-term moving average, the signal is 1 (buy), otherwise the signal is -1 (sell). Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Create a new column in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target.\n",
      "Input: The stop loss and profit target as percentages.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can create a new column in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target. We need to pass the stop loss and profit target as percentages as arguments to this function. We can use the following code to create the new column:\n",
      "\n",
      "```\n",
      "stop_loss = stop_loss_percent / 100\n",
      "profit_target = profit_target_percent / 100\n",
      "\n",
      "new_df['pnl'] = 0.0\n",
      "buy_price = 0.0\n",
      "for i in range(1, len(new_df)):\n",
      "    if new_df['signal'][i] == 1 and new_df['signal'][i-1] == -1:\n",
      "        buy_price = new_df['close'][i]\n",
      "    elif new_df['signal'][i] == -1 and new_df['signal'][i-1] == 1:\n",
      "        sell_price = new_df['close'][i]\n",
      "        if sell_price <= buy_price * (1 - stop_loss):\n",
      "            new_df['pnl'][i] = -stop_loss\n",
      "        elif sell_price >= buy_price * (1 + profit_target):\n",
      "            new_df['pnl'][i] = profit_target\n",
      "        else:\n",
      "            new_df['pnl'][i] = (sell_price - buy_price) / buy_price\n",
      "```\n",
      "\n",
      "This will create a new column called 'pnl' in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target. The stop loss and profit target are calculated based on the stop_loss_percent and profit_target_percent variables, respectively. The buy and sell prices are stored in the buy_price and sell_price variables, respectively. If the sell price is less than or equal to the stop loss, the profit or loss is set to -stop_loss. If the sell price is greater than or equal to the profit target, the profit or loss is set to profit_target. Otherwise, the profit or loss is calculated as (sell_price - buy_price) / buy_price. Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Calculate the total profit or loss for all trades.\n",
      "Input: None.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can calculate the total profit or loss for all trades by summing the values in the 'pnl' column of the DataFrame. We can use the following code to calculate the total profit or loss:\n",
      "\n",
      "```\n",
      "total_pnl = new_df['pnl'].sum()\n",
      "```\n",
      "\n",
      "This will calculate the total profit or loss for all trades and store it in the total_pnl variable. Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Visualize the stock data, short-term moving average, and long-term moving average using a line chart.\n",
      "Input: None.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can visualize the stock data, short-term moving average, and long-term moving average using a line chart using the `plot()` function from pandas. We can use the following code to visualize the data:\n",
      "\n",
      "```\n",
      "plt.figure(figsize=(12,6))\n",
      "plt.plot(new_df.index, new_df['close'], label='Close')\n",
      "plt.plot(new_df.index, new_df['short_ma'], label='Short MA')\n",
      "plt.plot(new_df.index, new_df['long_ma'], label='Long MA')\n",
      "plt.xlabel('Date')\n",
      "plt.ylabel('Price')\n",
      "plt.title('Stock Data with Moving Averages')\n",
      "plt.legend()\n",
      "plt.show()\n",
      "```\n",
      "\n",
      "This will create a line chart that visualizes the stock data, short-term moving average, and long-term moving average. The x-axis represents the date and the y-axis represents the price. The chart also includes a legend that labels each line. Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Visualize the buy and sell signals using a scatter plot.\n",
      "Input: None.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can visualize the buy and sell signals using a scatter plot using the `scatter()` function from matplotlib. We can use the following code to visualize the signals:\n",
      "\n",
      "```\n",
      "buy_signals = new_df[new_df['signal'] == 1]\n",
      "sell_signals = new_df[new_df['signal'] == -1]\n",
      "\n",
      "plt.figure(figsize=(12,6))\n",
      "plt.scatter(buy_signals.index, buy_signals['close'], label='Buy', marker='^', color='green')\n",
      "plt.scatter(sell_signals.index, sell_signals['close'], label='Sell', marker='v', color='red')\n",
      "plt.plot(new_df.index, new_df['close'], label='Close')\n",
      "plt.xlabel('Date')\n",
      "plt.ylabel('Price')\n",
      "plt.title('Buy and Sell Signals')\n",
      "plt.legend()\n",
      "plt.show()\n",
      "```\n",
      "\n",
      "This will create a scatter plot that visualizes the buy and sell signals. The x-axis represents the date and the y-axis represents the price. The chart also includes a legend that labels each point. Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Print the total profit or loss for all trades.\n",
      "Input: None.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: We can print the total profit or loss for all trades using the `print()` function. We can use the following code to print the total profit or loss:\n",
      "\n",
      "```\n",
      "print('Total Profit/Loss: {:.2%}'.format(total_pnl))\n",
      "```\n",
      "\n",
      "This will print the total profit or loss for all trades in percentage format with two decimal places. Next request.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "Instruction: Finalize the code by putting all the code snippets together in a single Python script.\n",
      "Input: The necessary inputs for each code snippet.\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Solution: Here is the complete Python script that puts all the code snippets together:\n",
      "\n",
      "```\n",
      "import pandas as pd\n",
      "import numpy as np\n",
      "import matplotlib.pyplot as plt\n",
      "import talib as ta\n",
      "\n",
      "# Load historical stock data into a pandas DataFrame\n",
      "df = pd.read_csv('path/to/csv/file.csv')\n",
      "\n",
      "# Preprocess the historical stock data\n",
      "df = df.set_index('date')\n",
      "df = df.sort_index(ascending=True)\n",
      "\n",
      "# Calculate the short-term and long-term moving averages\n",
      "short_period = 10\n",
      "long_period = 30\n",
      "short_ma = ta.SMA(df['close'], timeperiod=short_period)\n",
      "long_ma = ta.SMA(df['close'], timeperiod=long_period)\n",
      "\n",
      "# Create a new DataFrame that combines the historical stock data with the short-term and long-term moving averages\n",
      "new_df = pd.concat([df, short_ma, long_ma], axis=1)\n",
      "new_df.columns = ['open', 'high', 'low', 'close', 'volume', 'short_ma', 'long_ma']\n",
      "\n",
      "# Create a new column in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages\n",
      "new_df['signal'] = np.where(new_df['short_ma'] > new_df['long_ma'], 1, -1)\n",
      "\n",
      "# Create a new column in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target\n",
      "stop_loss_percent = 5\n",
      "profit_target_percent = 10\n",
      "stop_loss = stop_loss_percent / 100\n",
      "profit_target = profit_target_percent / 100\n",
      "new_df['pnl'] = 0.0\n",
      "buy_price = 0.0\n",
      "for i in range(1, len(new_df)):\n",
      "    if new_df['signal'][i] == 1 and new_df['signal'][i-1] == -1:\n",
      "        buy_price = new_df['close'][i]\n",
      "    elif new_df['signal'][i] == -1 and new_df['signal'][i-1] == 1:\n",
      "        sell_price = new_df['close'][i]\n",
      "        if sell_price <= buy_price * (1 - stop_loss):\n",
      "            new_df['pnl'][i] = -stop_loss\n",
      "        elif sell_price >= buy_price * (1 + profit_target):\n",
      "            new_df['pnl'][i] = profit_target\n",
      "        else:\n",
      "            new_df['pnl'][i] = (sell_price - buy_price) / buy_price\n",
      "\n",
      "# Calculate the total profit or loss for all trades\n",
      "total_pnl = new_df['pnl'].sum()\n",
      "\n",
      "# Visualize the stock data, short-term moving average, and long-term moving average using a line chart\n",
      "plt.figure(figsize=(12,6))\n",
      "plt.plot(new_df.index, new_df['close'], label='Close')\n",
      "plt.plot(new_df.index, new_df['short_ma'], label='Short MA')\n",
      "plt.plot(new_df.index, new_df['long_ma'], label='Long MA')\n",
      "plt.xlabel('Date')\n",
      "plt.ylabel('Price')\n",
      "plt.title('Stock Data with Moving Averages')\n",
      "plt.legend()\n",
      "plt.show()\n",
      "\n",
      "# Visualize the buy and sell signals using a scatter plot\n",
      "buy_signals = new_df[new_df['signal'] == 1]\n",
      "sell_signals = new_df[new_df['signal'] == -1]\n",
      "plt.figure(figsize=(12,6))\n",
      "plt.scatter(buy_signals.index, buy_signals['close'], label='Buy', marker='^', color='green')\n",
      "plt.scatter(sell_signals.index, sell_signals['close'], label='Sell', marker='v', color='red')\n",
      "plt.plot(new_df.index, new_df['close'], label='Close')\n",
      "plt.xlabel('Date')\n",
      "plt.ylabel('Price')\n",
      "plt.title('Buy and Sell Signals')\n",
      "plt.legend()\n",
      "plt.show()\n",
      "\n",
      "# Print the total profit or loss for all trades\n",
      "print('Total Profit/Loss: {:.2%}'.format(total_pnl))\n",
      "```\n",
      "\n",
      "You need to replace the path/to/csv/file.csv with the actual path to the CSV file containing the historical stock data. You can also adjust the short_period, long_period, stop_loss_percent, and profit_target_percent variables to suit your needs.\n",
      "\n",
      "\n",
      "AI User (Stock Trader):\n",
      "\n",
      "<CAMEL_TASK_DONE>\n",
      "\n",
      "\n",
      "AI Assistant (Python Programmer):\n",
      "\n",
      "Great! Let me know if you need any further assistance.\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print(f\"Original task prompt:\\n{task}\\n\")\n",
    "print(f\"Specified task prompt:\\n{specified_task}\\n\")\n",
    "\n",
    "chat_turn_limit, n = 30, 0\n",
    "while n < chat_turn_limit:\n",
    "    n += 1\n",
    "    user_ai_msg = user_agent.step(assistant_msg)\n",
    "    user_msg = HumanMessage(content=user_ai_msg.content)\n",
    "    print(f\"AI User ({user_role_name}):\\n\\n{user_msg.content}\\n\\n\")\n",
    "\n",
    "    assistant_ai_msg = assistant_agent.step(user_msg)\n",
    "    assistant_msg = HumanMessage(content=assistant_ai_msg.content)\n",
    "    print(f\"AI Assistant ({assistant_role_name}):\\n\\n{assistant_msg.content}\\n\\n\")\n",
    "    if \"<CAMEL_TASK_DONE>\" in user_msg.content:\n",
    "        break"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "camel",
   "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.10.9"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}