File size: 11,530 Bytes
acc4ffe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ba5f8741",
   "metadata": {},
   "source": [
    "# Custom Agent\n",
    "\n",
    "This notebook goes through how to create your own custom agent.\n",
    "\n",
    "An agent consists of three parts:\n",
    "    \n",
    "    - Tools: The tools the agent has available to use.\n",
    "    - LLMChain: The LLMChain that produces the text that is parsed in a certain way to determine which action to take.\n",
    "    - The agent class itself: this parses the output of the LLMChain to determin which action to take.\n",
    "        \n",
    "        \n",
    "In this notebook we walk through two types of custom agents. The first type shows how to create a custom LLMChain, but still use an existing agent class to parse the output. The second shows how to create a custom agent class."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6064f080",
   "metadata": {},
   "source": [
    "### Custom LLMChain\n",
    "\n",
    "The first way to create a custom agent is to use an existing Agent class, but use a custom LLMChain. This is the simplest way to create a custom Agent. It is highly reccomended that you work with the `ZeroShotAgent`, as at the moment that is by far the most generalizable one. \n",
    "\n",
    "Most of the work in creating the custom LLMChain comes down to the prompt. Because we are using an existing agent class to parse the output, it is very important that the prompt say to produce text in that format. Additionally, we currently require an `agent_scratchpad` input variable to put notes on previous actions and observations. This should almost always be the final part of the prompt. However, besides those instructions, you can customize the prompt as you wish.\n",
    "\n",
    "To ensure that the prompt contains the appropriate instructions, we will utilize a helper method on that class. The helper method for the `ZeroShotAgent` takes the following arguments:\n",
    "\n",
    "- tools: List of tools the agent will have access to, used to format the prompt.\n",
    "- prefix: String to put before the list of tools.\n",
    "- suffix: String to put after the list of tools.\n",
    "- input_variables: List of input variables the final prompt will expect.\n",
    "\n",
    "For this exercise, we will give our agent access to Google Search, and we will customize it in that we will have it answer as a pirate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "9af9734e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import ZeroShotAgent, Tool, AgentExecutor\n",
    "from langchain import OpenAI, SerpAPIWrapper, LLMChain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "becda2a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "search = SerpAPIWrapper()\n",
    "tools = [\n",
    "    Tool(\n",
    "        name = \"Search\",\n",
    "        func=search.run,\n",
    "        description=\"useful for when you need to answer questions about current events\"\n",
    "    )\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "339b1bb8",
   "metadata": {},
   "outputs": [],
   "source": [
    "prefix = \"\"\"Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:\"\"\"\n",
    "suffix = \"\"\"Begin! Remember to speak as a pirate when giving your final answer. Use lots of \"Args\"\n",
    "\n",
    "Question: {input}\n",
    "{agent_scratchpad}\"\"\"\n",
    "\n",
    "prompt = ZeroShotAgent.create_prompt(\n",
    "    tools, \n",
    "    prefix=prefix, \n",
    "    suffix=suffix, \n",
    "    input_variables=[\"input\", \"agent_scratchpad\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "59db7b58",
   "metadata": {},
   "source": [
    "In case we are curious, we can now take a look at the final prompt template to see what it looks like when its all put together."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "e21d2098",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:\n",
      "\n",
      "Search: useful for when you need to answer questions about current events\n",
      "\n",
      "Use the following format:\n",
      "\n",
      "Question: the input question you must answer\n",
      "Thought: you should always think about what to do\n",
      "Action: the action to take, should be one of [Search]\n",
      "Action Input: the input to the action\n",
      "Observation: the result of the action\n",
      "... (this Thought/Action/Action Input/Observation can repeat N times)\n",
      "Thought: I now know the final answer\n",
      "Final Answer: the final answer to the original input question\n",
      "\n",
      "Begin! Remember to speak as a pirate when giving your final answer. Use lots of \"Args\"\n",
      "\n",
      "Question: {input}\n",
      "{agent_scratchpad}\n"
     ]
    }
   ],
   "source": [
    "print(prompt.template)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5e028e6d",
   "metadata": {},
   "source": [
    "Note that we are able to feed agents a self-defined prompt template, i.e. not restricted to the prompt generated by the `create_prompt` function, assuming it meets the agent's requirements. \n",
    "\n",
    "For example, for `ZeroShotAgent`, we will need to ensure that it meets the following requirements. There should a string starting with \"Action:\" and a following string starting with \"Action Input:\", and both should be separated by a newline.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "9b1cc2a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "e4f5092f",
   "metadata": {},
   "outputs": [],
   "source": [
    "tool_names = [tool.name for tool in tools]\n",
    "agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "490604e9",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "653b1617",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mThought: I need to find out the population of Canada\n",
      "Action: Search\n",
      "Action Input: Population of Canada 2023\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3mThe current population of Canada is 38,610,447 as of Saturday, February 18, 2023, based on Worldometer elaboration of the latest United Nations data. Canada 2020 population is estimated at 37,742,154 people at mid year according to UN data.\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m I now know the final answer\n",
      "Final Answer: Arrr, Canada be havin' 38,610,447 scallywags livin' there as of 2023!\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "\"Arrr, Canada be havin' 38,610,447 scallywags livin' there as of 2023!\""
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.run(\"How many people live in canada as of 2023?\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "040eb343",
   "metadata": {},
   "source": [
    "### Multiple inputs\n",
    "Agents can also work with prompts that require multiple inputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "43dbfa2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "prefix = \"\"\"Answer the following questions as best you can. You have access to the following tools:\"\"\"\n",
    "suffix = \"\"\"When answering, you MUST speak in the following language: {language}.\n",
    "\n",
    "Question: {input}\n",
    "{agent_scratchpad}\"\"\"\n",
    "\n",
    "prompt = ZeroShotAgent.create_prompt(\n",
    "    tools, \n",
    "    prefix=prefix, \n",
    "    suffix=suffix, \n",
    "    input_variables=[\"input\", \"language\", \"agent_scratchpad\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "0f087313",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "92c75a10",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "ac5b83bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "c960e4ff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mThought: I need to find out the population of Canada in 2023.\n",
      "Action: Search\n",
      "Action Input: Population of Canada in 2023\u001b[0m\n",
      "Observation: \u001b[36;1m\u001b[1;3mThe current population of Canada is 38,610,447 as of Saturday, February 18, 2023, based on Worldometer elaboration of the latest United Nations data. Canada 2020 population is estimated at 37,742,154 people at mid year according to UN data.\u001b[0m\n",
      "Thought:\u001b[32;1m\u001b[1;3m I now know the final answer.\n",
      "Final Answer: La popolazione del Canada nel 2023 è stimata in 38.610.447 persone.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'La popolazione del Canada nel 2023 è stimata in 38.610.447 persone.'"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.run(input=\"How many people live in canada as of 2023?\", language=\"italian\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90171b2b",
   "metadata": {},
   "source": [
    "### Custom Agent Class\n",
    "\n",
    "Coming soon."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adefb4c2",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.1"
  },
  "vscode": {
   "interpreter": {
    "hash": "18784188d7ecd866c0586ac068b02361a6896dc3a29b64f5cc957f09c590acef"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}