File size: 33,740 Bytes
db5855f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b3c04f1a",
   "metadata": {},
   "source": [
    "# Create LLM Agent using OpenVINO\n",

    "\n",

    "LLM are limited to the knowledge on which they have been trained and the additional knowledge provided as context, as a result, if a useful piece of information is missing the provided knowledge, the model cannot “go around” and try to find it in other sources. This is the reason why we need to introduce the concept of Agents.\n",

    "\n",

    "The core idea of agents is to use a language model to choose a sequence of actions to take. In agents, a language model is used as a reasoning engine to determine which actions to take and in which order. Agents can be seen as applications powered by LLMs and integrated with a set of tools like search engines, databases, websites, and so on. Within an agent, the LLM is the reasoning engine that, based on the user input, is able to plan and execute a set of actions that are needed to fulfill the request.\n",

    "\n",

    "![agent](https://github.com/openvinotoolkit/openvino_notebooks/assets/91237924/22fa5396-8381-400f-a78f-97e25d57d807)\n",

    "\n",

    "[LangChain](https://python.langchain.com/docs/get_started/introduction) is a framework for developing applications powered by language models. LangChain comes with a number of built-in agents that are optimized for different use cases.\n",

    "\n",

    "This notebook explores how to create an AI Agent step by step using OpenVINO and LangChain.\n",

    "\n",

    "#### Table of contents:\n",

    "\n",

    "- [Prerequisites](#Prerequisites)\n",

    "- [Create tools](#Create-tools)\n",

    "- [Create prompt template](#Create-prompt-template)\n",

    "- [Create LLM](#Create-LLM)\n",

    "  - [Download model](#Select-model)\n",

    "  - [Select inference device for LLM](#Select-inference-device-for-LLM)\n",

    "- [Create agent](#Create-agent)\n",

    "- [Run the agent](#Run-agent)\n",

    "- [Interactive Demo](#Interactive-Demo)\n",

    "  - [Use built-in tool](#Use-built-in-tool)\n"

   ]

  },

  {

   "attachments": {},

   "cell_type": "markdown",

   "id": "f7bb0a67",

   "metadata": {},

   "source": [

    "## Prerequisites\n",

    "\n",

    "[back to top ⬆️](#Table-of-contents:)\n"

   ]

  },

  {

   "cell_type": "code",

   "execution_count": 1,

   "id": "47d43de7-9946-482d-84cb-222294c1cda8",

   "metadata": {},

   "outputs": [],

   "source": [

    "import os\n",

    "\n",

    "os.environ[\"GIT_CLONE_PROTECTION_ACTIVE\"] = \"false\"\n",
    "\n",
    "%pip install -Uq pip\n",
    "%pip uninstall -q -y optimum optimum-intel\n",
    "%pip install --pre -Uq openvino openvino-tokenizers[transformers] --extra-index-url https://storage.openvinotoolkit.org/simple/wheels/nightly\n",
    "%pip install -q --extra-index-url https://download.pytorch.org/whl/cpu\\\n",
    "\"git+https://github.com/huggingface/optimum-intel.git\"\\\n",
    "\"git+https://github.com/openvinotoolkit/nncf.git\"\\\n",
    "\"torch>=2.1\"\\\n",
    "\"datasets\"\\\n",
    "\"accelerate\"\\\n",
    "\"gradio\"\\\n",
    "\"transformers>=4.38.1\" \"langchain>=0.2.0\" \"langchain-community>=0.2.0\" \"wikipedia\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c722d565",
   "metadata": {},
   "source": [
    "## Create a tools\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "First, we need to create some tools to call. In this example, we will create 3 custom functions to do basic calculation. For [more information](https://python.langchain.com/docs/modules/tools/) on creating custom tools.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e8bfe609-1823-4df7-9a68-f210a58a0d38",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.tools import tool\n",
    "\n",
    "\n",
    "@tool\n",
    "def multiply(first_int: int, second_int: int) -> int:\n",
    "    \"\"\"Multiply two integers together.\"\"\"\n",
    "    return first_int * second_int\n",
    "\n",
    "\n",
    "@tool\n",
    "def add(first_int: int, second_int: int) -> int:\n",
    "    \"Add two integers.\"\n",
    "    return first_int + second_int\n",
    "\n",
    "\n",
    "@tool\n",
    "def exponentiate(base: int, exponent: int) -> int:\n",
    "    \"Exponentiate the base to the exponent power.\"\n",
    "    return base**exponent"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "6b476967",
   "metadata": {},
   "source": [
    "Tools are interfaces that an agent, chain, or LLM can use to interact with the world. They combine a few things:\n",
    "\n",
    "1. The name of the tool\n",
    "2. A description of what the tool is\n",
    "3. JSON schema of what the inputs to the tool are\n",
    "4. The function to call\n",
    "5. Whether the result of a tool should be returned directly to the user\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5ea4ce13",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name of `multiply` tool: multiply\n",
      "description of `multiply` tool: multiply(first_int: int, second_int: int) -> int - Multiply two integers together.\n"
     ]
    }
   ],
   "source": [
    "print(f\"name of `multiply` tool: {multiply.name}\")\n",
    "print(f\"description of `multiply` tool: {multiply.description}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d5f1ac30",
   "metadata": {},
   "source": [
    "Now that we have created all of them, and we can create a list of tools that we will use downstream.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a5c41830",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [multiply, add, exponentiate]"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "dba80270",
   "metadata": {},
   "source": [
    "## Create prompt template\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "A prompt for a language model is a set of instructions or input provided by a user to guide the model's response, helping it understand the context and generate relevant and coherent language-based output, such as answering questions, completing sentences, or engaging in a conversation.\n",
    "\n",
    "Different agents have different prompting styles for reasoning. In this example, we will use [ReAct agent](https://react-lm.github.io/) with its typical prompt template. For a full list of built-in agents see [agent types](https://python.langchain.com/docs/modules/agents/agent_types/).\n",
    "\n",
    "![react](https://github.com/openvinotoolkit/openvino_notebooks/assets/91237924/a83bdf7f-bb9d-4b1f-9a0a-3fe4a76ba1ae)\n",
    "\n",
    "A ReAct prompt consists of few-shot task-solving trajectories, with human-written text reasoning traces and actions, as well as environment observations in response to actions. ReAct prompting is intuitive and flexible to design, and achieves state-of-the-art few-shot performances across a variety of tasks, from question answering to online shopping!\n",
    "\n",
    "In an prompt template for agent, `agent_scratchpad` should be a sequence of messages that contains the previous agent tool invocations and the corresponding tool outputs.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "107f040a-e859-475c-9422-f980ac593fcf",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "\n",
    "prompt = PromptTemplate.from_template(\n",
    "    \"\"\"Answer the following questions as best you can. You have access to the following tools:\n",
    "\n",
    "    {tools}\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 [{tool_names}]\n",
    "    Action Input: the input to the action\\nObservation: 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!\n",
    "\n",
    "    Question: {input}\n",
    "    Thought:{agent_scratchpad}\"\"\"\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "259e1f0d",
   "metadata": {},
   "source": [
    "## Create LLM\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Large Language Models (LLMs) are a core component of LangChain. LangChain does not serve its own LLMs, but rather provides a standard interface for interacting with many different LLMs. In this example, we select `neural-chat-7b-v3-1` as LLM in agent pipeline.\n",
    "\n",
    "**neural-chat-7b-v3-1** - Mistral-7b model fine-tuned using Intel Gaudi. The model fine-tuned on the open source dataset [Open-Orca/SlimOrca](https://huggingface.co/datasets/Open-Orca/SlimOrca) and aligned with [Direct Preference Optimization (DPO) algorithm](https://arxiv.org/abs/2305.18290). More details can be found in [model card](https://huggingface.co/Intel/neural-chat-7b-v3-1) and [blog post](https://medium.com/@NeuralCompressor/the-practice-of-supervised-finetuning-and-direct-preference-optimization-on-habana-gaudi2-a1197d8a3cd3).\n",
    "\n",
    "### Download model\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "To run LLM locally, we have to download the model in the first step. It is possible to [export your model](https://github.com/huggingface/optimum-intel?tab=readme-ov-file#export) to the OpenVINO IR format with the CLI, and load the model from local folder.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "981df8fe-cfcf-455a-919e-dda36f3b5dfb",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "\n",
    "model_id = \"Intel/neural-chat-7b-v3-1\"\n",
    "model_path = \"neural-chat-7b-v3-1-ov-int4\"\n",
    "\n",
    "if not Path(model_path).exists():\n",
    "    !optimum-cli export openvino --model {model_id} --weight-format int4 {model_path}"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "6cfdbbae",
   "metadata": {},
   "source": [
    "### Select inference device for LLM\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a1ea3bdb-f97c-4374-880a-2b62abb5baaa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e58d3ba0789a48b997885d559a3f8e54",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Device:', options=('CPU', 'GPU.0', 'GPU.1', 'AUTO'), value='CPU')"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import openvino as ov\n",
    "import ipywidgets as widgets\n",
    "\n",
    "core = ov.Core()\n",
    "\n",
    "support_devices = core.available_devices\n",
    "if \"NPU\" in support_devices:\n",
    "    support_devices.remove(\"NPU\")\n",
    "\n",
    "device = widgets.Dropdown(\n",
    "    options=support_devices + [\"AUTO\"],\n",
    "    value=\"CPU\",\n",
    "    description=\"Device:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "device"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "77244c52",
   "metadata": {},
   "source": [
    "OpenVINO models can be run locally through the `HuggingFacePipeline` class in LangChain. To deploy a model with OpenVINO, you can specify the `backend=\"openvino\"` parameter to trigger OpenVINO as backend inference framework. For [more information](https://python.langchain.com/docs/integrations/llms/openvino/)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "abfaab28-fd5b-46cd-88ad-b60ea5a3cdd6",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2024-05-01 12:57:42.013703: I tensorflow/core/util/port.cc:110] oneDNN custom operations are on. You may see slightly different numerical results due to floating-point round-off errors from different computation orders. To turn them off, set the environment variable `TF_ENABLE_ONEDNN_OPTS=0`.\n",
      "2024-05-01 12:57:42.015389: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-05-01 12:57:42.049792: I tensorflow/tsl/cuda/cudart_stub.cc:28] Could not find cuda drivers on your machine, GPU will not be used.\n",
      "2024-05-01 12:57:42.050591: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
      "To enable the following instructions: AVX2 AVX512F AVX512_VNNI FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
      "2024-05-01 12:57:42.819557: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.\n",
      "  warn(\"The installed version of bitsandbytes was compiled without GPU support. \"\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/home/ea/work/my_optimum_intel/optimum_env/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32\n",
      "INFO:nncf:NNCF initialized successfully. Supported frameworks detected: torch, tensorflow, onnx, openvino\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "No CUDA runtime is found, using CUDA_HOME='/usr/local/cuda'\n",
      "WARNING[XFORMERS]: xFormers can't load C++/CUDA extensions. xFormers was built for:\n",
      "    PyTorch 2.0.1+cu118 with CUDA 1108 (you have 2.1.2+cpu)\n",
      "    Python  3.8.18 (you have 3.8.10)\n",
      "  Please reinstall xformers (see https://github.com/facebookresearch/xformers#installing-xformers)\n",
      "  Memory-efficient attention, SwiGLU, sparse and more won't be available.\n",
      "  Set XFORMERS_MORE_DETAILS=1 for more details\n",
      "Compiling the model to CPU ...\n"
     ]
    }
   ],
   "source": [
    "from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline\n",
    "\n",
    "ov_config = {\"PERFORMANCE_HINT\": \"LATENCY\", \"NUM_STREAMS\": \"1\", \"CACHE_DIR\": \"\"}\n",
    "\n",
    "ov_llm = HuggingFacePipeline.from_model_id(\n",
    "    model_id=model_path,\n",
    "    task=\"text-generation\",\n",
    "    backend=\"openvino\",\n",
    "    model_kwargs={\"device\": device.value, \"ov_config\": ov_config},\n",
    "    pipeline_kwargs={\"max_new_tokens\": 1024},\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d70905e2",
   "metadata": {},
   "source": [
    "You can get additional inference speed improvement with [Dynamic Quantization of activations and KV-cache quantization] on CPU(https://docs.openvino.ai/2024/learn-openvino/llm_inference_guide/llm-inference-hf.html#enabling-openvino-runtime-optimizations). These options can be enabled with `ov_config` as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "60653b85-2304-447e-a6fd-3a2ce9c69d75",
   "metadata": {},
   "outputs": [],
   "source": [
    "ov_config = {\n",
    "    \"KV_CACHE_PRECISION\": \"u8\",\n",
    "    \"DYNAMIC_QUANTIZATION_GROUP_SIZE\": \"32\",\n",
    "    \"PERFORMANCE_HINT\": \"LATENCY\",\n",
    "    \"NUM_STREAMS\": \"1\",\n",
    "    \"CACHE_DIR\": \"\",\n",
    "}"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "52a9a190",
   "metadata": {},
   "source": [
    "## Create agent\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Now that we have defined the tools, prompt template and LLM, we can create the agent_executor.\n",
    "\n",
    "The agent executor is the runtime for an agent. This is what actually calls the agent, executes the actions it chooses, passes the action outputs back to the agent, and repeats.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "4799540b-eee0-491f-a5b6-5bae68c22af9",
   "metadata": {},
   "outputs": [],
   "source": [
    "from custom_output_parser import ReActSingleInputOutputParser\n",
    "from langchain.agents import AgentExecutor, create_react_agent\n",
    "\n",
    "output_parser = ReActSingleInputOutputParser()\n",
    "\n",
    "agent = create_react_agent(ov_llm, tools, prompt, output_parser=output_parser)\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "038e76d1",
   "metadata": {},
   "source": [
    "## Run the agent\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "We can now run the agent with a math query. Before getting the final answer, a agent executor will also produce intermediate steps of reasoning and actions. The format of these messages will follow your prompt template.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "eebc8f67-8107-4a6b-90bf-ea9256c64ee5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mAnswer the following questions as best you can. You have access to the following tools:\n",
      "\n",
      "    multiply: multiply(first_int: int, second_int: int) -> int - Multiply two integers together.\n",
      "add: add(first_int: int, second_int: int) -> int - Add two integers.\n",
      "exponentiate: exponentiate(base: int, exponent: int) -> int - Exponentiate the base to the exponent power.\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 [multiply, add, exponentiate]\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!\n",
      "\n",
      "    Question: Take 3 to the fifth power and multiply that by the sum of twelve and three\n",
      "    Thought: We need to exponentiate 3 to the power of 5, then multiply the result by the sum of 12 and 3\n",
      "    Action: exponentiate\n",
      "    Action Input: base: 3, exponent: 5\n",
      "    Observation: 243\n",
      "    Action: add\n",
      "    Action Input: first_int: 12, second_int: 3\n",
      "    Observation: 15\n",
      "    Action: multiply\n",
      "    Action Input: first_int: 243, second_int: 15\n",
      "    Observation: 3645\n",
      "    Thought: I now know the final answer\n",
      "    Final Answer: 3645\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': 'Take 3 to the fifth power and multiply that by the sum of twelve and three',\n",
       " 'output': '3645'}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke({\"input\": \"Take 3 to the fifth power and multiply that by the sum of twelve and three\"})"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "688ced57",
   "metadata": {},
   "source": [
    "## Interactive Demo\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Let's create a interactive agent using [Gradio](https://www.gradio.app/).\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ce623516",
   "metadata": {},
   "source": [
    "### Use built-in tool\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "LangChain has provided a list of all [built-in tools](https://python.langchain.com/docs/integrations/tools/). In this example, we will use `Wikipedia` python package to query key words generated by agent.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "1f64b67c-1259-4fe6-bfc3-af317bfe04f6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "description of `wikipedia` tool: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.\n"
     ]
    }
   ],
   "source": [
    "from langchain.tools import WikipediaQueryRun\n",
    "from langchain_community.utilities import WikipediaAPIWrapper\n",
    "\n",
    "\n",
    "wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())\n",
    "print(f\"description of `wikipedia` tool: {wikipedia.description}\")\n",
    "\n",
    "tools = [wikipedia]\n",
    "\n",
    "agent = create_react_agent(ov_llm, tools, prompt, output_parser=output_parser)\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff5a60fb-e13e-4eaf-a2f3-999e4e3109bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "from threading import Thread\n",
    "import gradio as gr\n",
    "from transformers import TextIteratorStreamer\n",
    "\n",
    "examples = [\n",
    "    [\"What is OpenVINO ?\"],\n",
    "    [\"Who is 44th presedent of USA ?\"],\n",
    "    [\"what is Obama's first name and who is him ?\"],\n",
    "    [\"How many people live in Canada ?\"],\n",
    "    [\"How tall is the Eiffel Tower ?\"],\n",
    "]\n",
    "\n",
    "\n",
    "def partial_text_processor(partial_text, new_text):\n",
    "    \"\"\"\n",
    "    helper for updating partially generated answer, used by default\n",
    "\n",
    "    Params:\n",
    "      partial_text: text buffer for storing previosly generated text\n",
    "      new_text: text update for the current step\n",
    "    Returns:\n",
    "      updated text string\n",
    "\n",
    "    \"\"\"\n",
    "    new_text = new_text.replace(\"[INST]\", \"\").replace(\"[/INST]\", \"\")\n",
    "    partial_text += new_text\n",
    "    return partial_text\n",
    "\n",
    "\n",
    "def user(message, history):\n",
    "    \"\"\"\n",
    "    callback function for updating user messages in interface on submit button click\n",
    "\n",
    "    Params:\n",
    "      message: current message\n",
    "      history: conversation history\n",
    "    Returns:\n",
    "      None\n",
    "    \"\"\"\n",
    "    # Append the user's message to the conversation history\n",
    "    return \"\", history + [[message, \"\"]]\n",
    "\n",
    "\n",
    "def bot(history, temperature, top_p, top_k, repetition_penalty, return_intermediate_steps):\n",
    "    \"\"\"\n",
    "    callback function for running chatbot on submit button click\n",
    "\n",
    "    Params:\n",
    "      history: conversation history\n",
    "      temperature:  parameter for control the level of creativity in AI-generated text.\n",
    "                    By adjusting the `temperature`, you can influence the AI model's probability distribution, making the text more focused or diverse.\n",
    "      top_p: parameter for control the range of tokens considered by the AI model based on their cumulative probability.\n",
    "      top_k: parameter for control the range of tokens considered by the AI model based on their cumulative probability, selecting number of tokens with highest probability.\n",
    "      repetition_penalty: parameter for penalizing tokens based on how frequently they occur in the text.\n",
    "      return_intermediate_steps: whether return intermediate_steps of agent.\n",
    "\n",
    "    \"\"\"\n",
    "    streamer = TextIteratorStreamer(\n",
    "        ov_llm.pipeline.tokenizer,\n",
    "        timeout=60.0,\n",
    "        skip_prompt=True,\n",
    "        skip_special_tokens=True,\n",
    "    )\n",
    "\n",
    "    ov_llm.pipeline._forward_params = dict(\n",
    "        max_new_tokens=512,\n",
    "        temperature=temperature,\n",
    "        do_sample=temperature > 0.0,\n",
    "        top_p=top_p,\n",
    "        top_k=top_k,\n",
    "        repetition_penalty=repetition_penalty,\n",
    "        streamer=streamer,\n",
    "    )\n",
    "\n",
    "    t1 = Thread(target=agent_executor.invoke, args=({\"input\": history[-1][0]},))\n",
    "    t1.start()\n",
    "\n",
    "    # Initialize an empty string to store the generated text\n",
    "    partial_text = \"\"\n",
    "    final_answer = False\n",
    "\n",
    "    for new_text in streamer:\n",
    "        if \"Answer\" in new_text:\n",
    "            final_answer = True\n",
    "        if final_answer or return_intermediate_steps:\n",
    "            partial_text = partial_text_processor(partial_text, new_text)\n",
    "            history[-1][1] = partial_text\n",
    "            yield history\n",
    "\n",
    "\n",
    "def request_cancel():\n",
    "    ov_llm.pipeline.model.request.cancel()\n",
    "\n",
    "\n",
    "with gr.Blocks(\n",
    "    theme=gr.themes.Soft(),\n",
    "    css=\".disclaimer {font-variant-caps: all-small-caps;}\",\n",
    ") as demo:\n",
    "    gr.Markdown(f\"\"\"<h1><center>OpenVINO Agent for {wikipedia.name}</center></h1>\"\"\")\n",
    "    chatbot = gr.Chatbot(height=500)\n",
    "    with gr.Row():\n",
    "        with gr.Column():\n",
    "            msg = gr.Textbox(\n",
    "                label=\"Chat Message Box\",\n",
    "                placeholder=\"Chat Message Box\",\n",
    "                show_label=False,\n",
    "                container=False,\n",
    "            )\n",
    "        with gr.Column():\n",
    "            with gr.Row():\n",
    "                return_cot = gr.Checkbox(value=True, label=\"Return intermediate steps\")\n",
    "                submit = gr.Button(\"Submit\")\n",
    "                stop = gr.Button(\"Stop\")\n",
    "                clear = gr.Button(\"Clear\")\n",
    "    with gr.Row():\n",
    "        with gr.Accordion(\"Advanced Options:\", open=False):\n",
    "            with gr.Row():\n",
    "                with gr.Column():\n",
    "                    with gr.Row():\n",
    "                        temperature = gr.Slider(\n",
    "                            label=\"Temperature\",\n",
    "                            value=0.1,\n",
    "                            minimum=0.0,\n",
    "                            maximum=1.0,\n",
    "                            step=0.1,\n",
    "                            interactive=True,\n",
    "                            info=\"Higher values produce more diverse outputs\",\n",
    "                        )\n",
    "                with gr.Column():\n",
    "                    with gr.Row():\n",
    "                        top_p = gr.Slider(\n",
    "                            label=\"Top-p (nucleus sampling)\",\n",
    "                            value=1.0,\n",
    "                            minimum=0.0,\n",
    "                            maximum=1,\n",
    "                            step=0.01,\n",
    "                            interactive=True,\n",
    "                            info=(\n",
    "                                \"Sample from the smallest possible set of tokens whose cumulative probability \"\n",
    "                                \"exceeds top_p. Set to 1 to disable and sample from all tokens.\"\n",
    "                            ),\n",
    "                        )\n",
    "                with gr.Column():\n",
    "                    with gr.Row():\n",
    "                        top_k = gr.Slider(\n",
    "                            label=\"Top-k\",\n",
    "                            value=50,\n",
    "                            minimum=0.0,\n",
    "                            maximum=200,\n",
    "                            step=1,\n",
    "                            interactive=True,\n",
    "                            info=\"Sample from a shortlist of top-k tokens — 0 to disable and sample from all tokens.\",\n",
    "                        )\n",
    "                with gr.Column():\n",
    "                    with gr.Row():\n",
    "                        repetition_penalty = gr.Slider(\n",
    "                            label=\"Repetition Penalty\",\n",
    "                            value=1.1,\n",
    "                            minimum=1.0,\n",
    "                            maximum=2.0,\n",
    "                            step=0.1,\n",
    "                            interactive=True,\n",
    "                            info=\"Penalize repetition — 1.0 to disable.\",\n",
    "                        )\n",
    "    gr.Examples(examples, inputs=msg, label=\"Click on any example and press the 'Submit' button\")\n",
    "\n",
    "    submit_event = msg.submit(\n",
    "        fn=user,\n",
    "        inputs=[msg, chatbot],\n",
    "        outputs=[msg, chatbot],\n",
    "        queue=False,\n",
    "    ).then(\n",
    "        fn=bot,\n",
    "        inputs=[\n",
    "            chatbot,\n",
    "            temperature,\n",
    "            top_p,\n",
    "            top_k,\n",
    "            repetition_penalty,\n",
    "            return_cot,\n",
    "        ],\n",
    "        outputs=chatbot,\n",
    "        queue=True,\n",
    "    )\n",
    "    submit_click_event = submit.click(\n",
    "        fn=user,\n",
    "        inputs=[msg, chatbot],\n",
    "        outputs=[msg, chatbot],\n",
    "        queue=False,\n",
    "    ).then(\n",
    "        fn=bot,\n",
    "        inputs=[\n",
    "            chatbot,\n",
    "            temperature,\n",
    "            top_p,\n",
    "            top_k,\n",
    "            repetition_penalty,\n",
    "            return_cot,\n",
    "        ],\n",
    "        outputs=chatbot,\n",
    "        queue=True,\n",
    "    )\n",
    "    stop.click(\n",
    "        fn=request_cancel,\n",
    "        inputs=None,\n",
    "        outputs=None,\n",
    "        cancels=[submit_event, submit_click_event],\n",
    "        queue=False,\n",
    "    )\n",
    "    clear.click(lambda: None, None, chatbot, queue=False)\n",
    "\n",
    "# if you are launching remotely, specify server_name and server_port\n",
    "#  demo.launch(server_name='your server name', server_port='server port in int')\n",
    "# if you have any issue to launch on your platform, you can pass share=True to launch method:\n",
    "# demo.launch(share=True)\n",
    "# it creates a publicly shareable link for the interface. Read more in the docs: https://gradio.app/docs/\n",
    "demo.launch()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "680c8fcc-65d3-4194-b67f-763ad5267775",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# please run this cell for stopping gradio interface\n",
    "demo.close()"
   ]
  }
 ],
 "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.10.12"
  },
  "openvino_notebooks": {
   "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/assets/91237924/2abb2389-e612-4599-82c6-64cdac259120",
   "tags": {
    "categories": [
     "Model Demos",
     "AI Trends"
    ],
    "libraries": [],
    "other": [
     "LLM"
    ],
    "tasks": [
     "Text Generation"
    ]
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}