File size: 28,161 Bytes
e150328
 
 
 
 
0bfedbd
 
e150328
 
0bfedbd
e150328
 
 
 
 
 
0bfedbd
 
 
 
e150328
 
 
be5df4e
e150328
be5df4e
 
 
0bfedbd
e2e30e0
e150328
be5df4e
 
 
0bfedbd
be5df4e
e2e30e0
 
 
 
be5df4e
 
 
 
e150328
0bfedbd
e150328
 
 
 
0bfedbd
 
 
 
 
e150328
 
 
0bfedbd
e2e30e0
0bfedbd
e150328
 
 
 
 
0bfedbd
 
 
 
e150328
 
 
0bfedbd
 
 
 
 
e150328
 
 
 
 
 
0bfedbd
e150328
 
 
 
 
0bfedbd
 
 
 
e150328
 
 
 
 
0bfedbd
 
 
 
e150328
 
 
0bfedbd
e150328
 
 
0bfedbd
 
 
 
 
 
 
 
e150328
 
 
0bfedbd
e150328
 
 
 
0bfedbd
5fa4e55
e150328
 
 
 
0bfedbd
e150328
 
 
 
 
 
 
 
5fa4e55
 
e150328
 
5fa4e55
 
e150328
 
5fa4e55
 
e150328
 
5fa4e55
 
e150328
 
5fa4e55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e150328
 
0bfedbd
 
 
e150328
 
 
 
 
 
0bfedbd
 
 
 
e150328
 
 
0bfedbd
e150328
 
 
0bfedbd
 
 
 
 
 
 
 
e150328
 
 
0bfedbd
e150328
 
 
 
5fa4e55
 
e150328
 
 
 
0bfedbd
e150328
 
 
5fa4e55
e150328
5fa4e55
e150328
 
 
 
 
 
 
5fa4e55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e150328
5fa4e55
 
e150328
5fa4e55
 
 
e150328
5fa4e55
 
 
e150328
5fa4e55
e150328
5fa4e55
 
e150328
5fa4e55
 
e150328
5fa4e55
e150328
5fa4e55
e150328
 
 
5fa4e55
e150328
5fa4e55
 
e150328
5fa4e55
 
e150328
5fa4e55
e150328
5fa4e55
e150328
5fa4e55
 
 
 
e150328
5fa4e55
e150328
5fa4e55
 
e150328
5fa4e55
 
 
e150328
5fa4e55
 
 
e150328
5fa4e55
 
 
e150328
5fa4e55
 
 
 
 
 
 
 
 
 
e150328
5fa4e55
 
e150328
5fa4e55
 
 
e150328
 
 
 
5fa4e55
 
e150328
 
5fa4e55
e150328
 
 
 
 
 
5fa4e55
e150328
 
 
 
 
 
0bfedbd
 
 
e150328
 
 
 
 
 
0bfedbd
 
 
 
e150328
 
 
0bfedbd
e150328
 
 
0bfedbd
 
 
 
 
 
 
 
 
 
 
 
 
e150328
 
 
0bfedbd
e150328
 
 
 
 
 
 
 
 
 
0bfedbd
e150328
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0bfedbd
 
 
e150328
 
be5df4e
 
 
 
0bfedbd
 
 
 
be5df4e
e150328
 
0bfedbd
 
 
 
 
be5df4e
 
 
 
 
0bfedbd
 
 
 
 
 
 
 
be5df4e
 
 
0bfedbd
be5df4e
 
 
 
 
1def9d5
be5df4e
 
 
 
0bfedbd
be5df4e
 
 
 
0bfedbd
 
 
be5df4e
 
 
 
0bfedbd
be5df4e
 
 
0bfedbd
 
 
 
 
 
 
 
 
 
 
be5df4e
 
 
0bfedbd
be5df4e
 
 
 
 
 
 
 
 
 
0bfedbd
be5df4e
 
 
 
0bfedbd
 
 
be5df4e
e2e30e0
 
 
0bfedbd
e2e30e0
 
 
0bfedbd
 
 
 
 
 
 
 
 
 
 
 
 
 
e2e30e0
 
 
0bfedbd
e2e30e0
 
 
 
 
1def9d5
e2e30e0
 
 
 
0bfedbd
e2e30e0
1def9d5
e2e30e0
1def9d5
e2e30e0
 
 
 
 
 
0bfedbd
 
 
e2e30e0
 
 
 
0bfedbd
e2e30e0
 
 
0bfedbd
 
e150328
0bfedbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "view-in-github"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/towardsai/ai-tutor-rag-system/blob/main/notebooks/Prompting_101.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "DMXyyXD0xix9"
      },
      "source": [
        "# Install Packages and Setup Variables\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "o4Q0N2omkAoZ",
        "outputId": "6bc470f0-2efe-4cd8-d3e3-1b20593ad968"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m320.6/320.6 kB\u001b[0m \u001b[31m2.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m75.6/75.6 kB\u001b[0m \u001b[31m4.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m77.9/77.9 kB\u001b[0m \u001b[31m3.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m58.3/58.3 kB\u001b[0m \u001b[31m3.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h"
          ]
        }
      ],
      "source": [
        "!pip install -q openai==1.37.0"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "xxK7EAAvr2aT"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "# Set the following API Keys in the Python environment. Will be used later.\n",
        "os.environ[\"OPENAI_API_KEY\"] = \"[OPENAI_API_KEY]\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "68RbStS-xpbL"
      },
      "source": [
        "# Load the API client\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "La8hdWqJkFkh"
      },
      "outputs": [],
      "source": [
        "from openai import OpenAI\n",
        "\n",
        "# Defining the \"client\" object that enables\n",
        "# us to connect to OpenAI API endpoints.\n",
        "client = OpenAI()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CC-sa_uv6J2C"
      },
      "source": [
        "# Query the API\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tCgIt1OJH8-M"
      },
      "source": [
        "## Bad Prompt\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_gSnVAvE0tGN"
      },
      "outputs": [],
      "source": [
        "response = client.chat.completions.create(\n",
        "    model=\"gpt-4o\",\n",
        "    temperature=0.0,\n",
        "    messages=[{\"role\": \"user\", \"content\": \"How AI can help my project?\"}],\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ET_l06LiojaN",
        "outputId": "72207c84-8d4f-4e5c-bfda-2d850b4b4a5b"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "AI can significantly enhance your project in various ways, depending on the nature and goals of your project. Here are some general areas where AI can be beneficial:\n",
            "\n",
            "### 1. **Data Analysis and Insights**\n",
            "- **Predictive Analytics:** AI can analyze historical data to predict future trends, helping you make informed decisions.\n",
            "- **Pattern Recognition:** AI algorithms can identify patterns and correlations in large datasets that might be missed by human analysis.\n",
            "\n",
            "### 2. **Automation**\n",
            "- **Task Automation:** Automate repetitive tasks such as data entry, scheduling, and customer service.\n",
            "- **Process Optimization:** AI can streamline workflows and improve efficiency by optimizing processes.\n",
            "\n",
            "### 3. **Personalization**\n",
            "- **Customer Experience:** Use AI to personalize user experiences, such as recommending products or content based on user behavior.\n",
            "- **Targeted Marketing:** AI can help segment your audience and create targeted marketing campaigns.\n",
            "\n",
            "### 4. **Natural Language Processing (NLP)**\n",
            "- **Chatbots:** Implement AI-driven chatbots to handle customer inquiries, providing instant support and freeing up human resources.\n",
            "- **Sentiment Analysis:** Analyze customer feedback and social media to gauge public sentiment about your project or product.\n",
            "\n",
            "### 5. **Image and Video Analysis**\n",
            "- **Computer Vision:** Use AI to analyze images and videos for various applications, such as quality control, security, and content moderation.\n",
            "- **Facial Recognition:** Implement facial recognition for security or personalized user experiences.\n",
            "\n",
            "### 6. **Decision Support**\n",
            "- **Recommendation Systems:** AI can provide recommendations based on data analysis, helping you make better decisions.\n",
            "- **Risk Assessment:** AI can evaluate risks and provide insights to mitigate them.\n",
            "\n",
            "### 7. **Development and Testing**\n",
            "- **Code Generation:** AI tools can assist in writing and debugging code, speeding up the development process.\n",
            "- **Automated Testing:** Use AI to automate software testing, ensuring higher quality and faster release cycles.\n",
            "\n",
            "### 8. **Resource Management**\n",
            "- **Supply Chain Optimization:** AI can optimize inventory management, demand forecasting, and logistics.\n",
            "- **Human Resources:** AI can assist in talent acquisition, performance evaluation, and employee engagement.\n",
            "\n",
            "### 9. **Innovation and Creativity**\n",
            "- **Idea Generation:** AI can help brainstorm new ideas by analyzing existing data and trends.\n",
            "- **Content Creation:** Use AI to generate content, such as articles, reports, or even creative writing.\n",
            "\n",
            "### 10. **Security**\n",
            "- **Fraud Detection:** AI can identify unusual patterns that may indicate fraudulent activity.\n",
            "- **Cybersecurity:** AI can help detect and respond to security threats in real-time.\n",
            "\n",
            "### Steps to Implement AI in Your Project\n",
            "1. **Identify Needs:** Determine which aspects of your project could benefit from AI.\n",
            "2. **Data Collection:** Gather the necessary data that AI will need to function effectively.\n",
            "3. **Choose the Right Tools:** Select AI tools and platforms that fit your project requirements.\n",
            "4. **Develop and Train Models:** Develop AI models and train them using your data.\n",
            "5. **Integration:** Integrate AI solutions into your existing systems and workflows.\n",
            "6. **Monitor and Optimize:** Continuously monitor the performance of AI systems and make adjustments as needed.\n",
            "\n",
            "By leveraging AI, you can enhance efficiency, improve decision-making, and create more personalized and effective solutions for your project.\n"
          ]
        }
      ],
      "source": [
        "print(response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_Pyd2dmOH51S"
      },
      "source": [
        "## Good Prompt\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gHXHXUG09d4q"
      },
      "outputs": [],
      "source": [
        "response = client.chat.completions.create(\n",
        "    model=\"gpt-4o\",\n",
        "    temperature=0.0,\n",
        "    messages=[{\"role\": \"user\", \"content\": \"How can I do summarization using AI?\"}],\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "0PfYfRCbuFiK",
        "outputId": "dcd51828-493f-4a09-9803-be7c0cdf12f4"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Summarization using AI involves using machine learning models to condense a large body of text into a shorter version while retaining the key information and main ideas. There are two main types of summarization techniques: extractive and abstractive.\n",
            "\n",
            "1. **Extractive Summarization**: This method involves selecting important sentences, phrases, or sections directly from the source text and concatenating them to create a summary. It doesn't generate new sentences but rather extracts and combines parts of the original text.\n",
            "\n",
            "2. **Abstractive Summarization**: This method involves generating new sentences that convey the main ideas of the source text. It is more complex as it requires understanding the context and rephrasing the content in a coherent manner.\n",
            "\n",
            "Here are some steps and tools you can use to perform summarization using AI:\n",
            "\n",
            "### Using Pre-trained Models and Libraries\n",
            "\n",
            "1. **Hugging Face Transformers**:\n",
            "   - Hugging Face provides a library called `transformers` which includes pre-trained models for both extractive and abstractive summarization.\n",
            "   - Models like BART, T5, and Pegasus are popular for abstractive summarization.\n",
            "\n",
            "   ```python\n",
            "   from transformers import pipeline\n",
            "\n",
            "   # Load the summarization pipeline\n",
            "   summarizer = pipeline(\"summarization\")\n",
            "\n",
            "   # Input text\n",
            "   text = \"\"\"\n",
            "   Your long text goes here...\n",
            "   \"\"\"\n",
            "\n",
            "   # Generate summary\n",
            "   summary = summarizer(text, max_length=150, min_length=30, do_sample=False)\n",
            "   print(summary[0]['summary_text'])\n",
            "   ```\n",
            "\n",
            "2. **spaCy and Sumy**:\n",
            "   - `spaCy` is a popular NLP library that can be used in conjunction with `Sumy` for extractive summarization.\n",
            "\n",
            "   ```python\n",
            "   import spacy\n",
            "   from sumy.parsers.plaintext import PlaintextParser\n",
            "   from sumy.nlp.tokenizers import Tokenizer\n",
            "   from sumy.summarizers.lsa import LsaSummarizer\n",
            "\n",
            "   # Load spaCy model\n",
            "   nlp = spacy.load('en_core_web_sm')\n",
            "\n",
            "   # Input text\n",
            "   text = \"\"\"\n",
            "   Your long text goes here...\n",
            "   \"\"\"\n",
            "\n",
            "   # Parse the text\n",
            "   parser = PlaintextParser.from_string(text, Tokenizer(\"english\"))\n",
            "\n",
            "   # Summarize using LSA\n",
            "   summarizer = LsaSummarizer()\n",
            "   summary = summarizer(parser.document, 3)  # Summarize to 3 sentences\n",
            "\n",
            "   for sentence in summary:\n",
            "       print(sentence)\n",
            "   ```\n",
            "\n",
            "### Using Online Services\n",
            "\n",
            "1. **OpenAI GPT-3**:\n",
            "   - OpenAI's GPT-3 can be used for summarization tasks. You can access it via the OpenAI API.\n",
            "\n",
            "   ```python\n",
            "   import openai\n",
            "\n",
            "   openai.api_key = 'your-api-key'\n",
            "\n",
            "   response = openai.Completion.create(\n",
            "       engine=\"text-davinci-003\",\n",
            "       prompt=\"Summarize the following text:\\n\\nYour long text goes here...\",\n",
            "       max_tokens=150\n",
            "   )\n",
            "\n",
            "   print(response.choices[0].text.strip())\n",
            "   ```\n",
            "\n",
            "2. **Google Cloud Natural Language API**:\n",
            "   - Google Cloud offers a Natural Language API that includes features for text analysis and summarization.\n",
            "\n",
            "### Custom Models\n",
            "\n",
            "If you have specific requirements or a unique dataset, you might want to train your own summarization model. This involves:\n",
            "\n",
            "1. **Data Collection**: Gather a large dataset of documents and their corresponding summaries.\n",
            "2. **Preprocessing**: Clean and preprocess the text data.\n",
            "3. **Model Training**: Use frameworks like TensorFlow or PyTorch to train a model. You can start with a pre-trained model and fine-tune it on your dataset.\n",
            "4. **Evaluation**: Evaluate the model using metrics like ROUGE to ensure it generates high-quality summaries.\n",
            "\n",
            "### Example of Fine-Tuning a Model\n",
            "\n",
            "```python\n",
            "from transformers import T5Tokenizer, T5ForConditionalGeneration, Trainer, TrainingArguments\n",
            "\n",
            "# Load pre-trained model and tokenizer\n",
            "model = T5ForConditionalGeneration.from_pretrained('t5-small')\n",
            "tokenizer = T5Tokenizer.from_pretrained('t5-small')\n",
            "\n",
            "# Prepare dataset (example)\n",
            "train_texts = [\"Your training texts...\"]\n",
            "train_summaries = [\"Your training summaries...\"]\n",
            "\n",
            "# Tokenize data\n",
            "train_encodings = tokenizer(train_texts, truncation=True, padding=True, max_length=512)\n",
            "train_labels = tokenizer(train_summaries, truncation=True, padding=True, max_length=150)\n",
            "\n",
            "# Create dataset\n",
            "class SummarizationDataset(torch.utils.data.Dataset):\n",
            "    def __init__(self, encodings, labels):\n",
            "        self.encodings = encodings\n",
            "        self.labels = labels\n",
            "\n",
            "    def __getitem__(self, idx):\n",
            "        item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}\n",
            "        item['labels'] = torch.tensor(self.labels['input_ids'][idx])\n",
            "        return item\n",
            "\n",
            "    def __len__(self):\n",
            "        return len(self.encodings['input_ids'])\n",
            "\n",
            "train_dataset = SummarizationDataset(train_encodings, train_labels)\n",
            "\n",
            "# Training arguments\n",
            "training_args = TrainingArguments(\n",
            "    output_dir='./results',\n",
            "    num_train_epochs=3,\n",
            "    per_device_train_batch_size=4,\n",
            "    save_steps=10_000,\n",
            "    save_total_limit=2,\n",
            ")\n",
            "\n",
            "# Trainer\n",
            "trainer = Trainer(\n",
            "    model=model,\n",
            "    args=training_args,\n",
            "    train_dataset=train_dataset,\n",
            ")\n",
            "\n",
            "# Train model\n",
            "trainer.train()\n",
            "```\n",
            "\n",
            "By following these steps and using the appropriate tools, you can effectively perform text summarization using AI.\n"
          ]
        }
      ],
      "source": [
        "print(response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "p8MBdV_aH2Dq"
      },
      "source": [
        "## Failed Edge Case\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "r7By9Sy498p9"
      },
      "outputs": [],
      "source": [
        "response = client.chat.completions.create(\n",
        "    model=\"gpt-4o\",\n",
        "    temperature=0.0,\n",
        "    messages=[\n",
        "        {\n",
        "            \"role\": \"user\",\n",
        "            \"content\": \"How can I do summarization multiple documents using Google Gemini model?\",\n",
        "        }\n",
        "    ],\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "QyIsGPp4AnVY",
        "outputId": "0fc515ef-2e5a-4146-ca57-2147d5a04610"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "As of my last update in October 2023, Google Gemini is a suite of AI models developed by Google, which includes capabilities for natural language understanding and generation. If you want to use Google Gemini for summarizing multiple documents, you would typically follow these steps:\n",
            "\n",
            "1. **Access the Model**: Ensure you have access to the Google Gemini model. This might be through an API provided by Google Cloud or another platform where the model is hosted.\n",
            "\n",
            "2. **Prepare Your Documents**: Gather the documents you want to summarize. Ensure they are in a format that can be processed by the model (e.g., plain text, PDF, etc.).\n",
            "\n",
            "3. **Preprocess the Documents**: Depending on the input requirements of the Gemini model, you might need to preprocess your documents. This could involve cleaning the text, removing unnecessary formatting, or splitting the documents into manageable chunks if they are too large.\n",
            "\n",
            "4. **API Integration**: Use the API provided by Google to interact with the Gemini model. You will need to authenticate your requests, typically using an API key or OAuth token.\n",
            "\n",
            "5. **Send Requests**: Send the documents to the model for summarization. This might involve sending each document individually or batching them together if the API supports it.\n",
            "\n",
            "6. **Handle Responses**: Collect the summaries returned by the model. You might need to post-process these summaries to combine them or format them as needed.\n",
            "\n",
            "Here is a simplified example using Python pseudocode to illustrate the process:\n",
            "\n",
            "```python\n",
            "import requests\n",
            "\n",
            "# Define your API endpoint and API key\n",
            "api_endpoint = \"https://api.google.com/gemini/summarize\"\n",
            "api_key = \"YOUR_API_KEY\"\n",
            "\n",
            "# Function to summarize a single document\n",
            "def summarize_document(document_text):\n",
            "    headers = {\n",
            "        \"Authorization\": f\"Bearer {api_key}\",\n",
            "        \"Content-Type\": \"application/json\"\n",
            "    }\n",
            "    data = {\n",
            "        \"document\": document_text\n",
            "    }\n",
            "    response = requests.post(api_endpoint, headers=headers, json=data)\n",
            "    if response.status_code == 200:\n",
            "        return response.json().get(\"summary\")\n",
            "    else:\n",
            "        raise Exception(f\"Error: {response.status_code}, {response.text}\")\n",
            "\n",
            "# List of documents to summarize\n",
            "documents = [\n",
            "    \"Document 1 text...\",\n",
            "    \"Document 2 text...\",\n",
            "    \"Document 3 text...\"\n",
            "]\n",
            "\n",
            "# Summarize each document\n",
            "summaries = []\n",
            "for doc in documents:\n",
            "    summary = summarize_document(doc)\n",
            "    summaries.append(summary)\n",
            "\n",
            "# Combine summaries if needed\n",
            "combined_summary = \"\\n\".join(summaries)\n",
            "\n",
            "print(\"Combined Summary:\")\n",
            "print(combined_summary)\n",
            "```\n",
            "\n",
            "### Important Considerations:\n",
            "- **API Limits**: Be aware of any rate limits or usage quotas associated with the API.\n",
            "- **Document Size**: Large documents might need to be split into smaller parts before summarization.\n",
            "- **Post-Processing**: Depending on the quality of the summaries, you might need to do some post-processing to ensure coherence and readability.\n",
            "\n",
            "### Alternative Approaches:\n",
            "- **Batch Processing**: If the API supports batch processing, you can send multiple documents in a single request to improve efficiency.\n",
            "- **Custom Models**: If you have specific requirements, consider fine-tuning a model on your dataset using Google Cloud's AI Platform.\n",
            "\n",
            "Always refer to the latest documentation provided by Google for the most accurate and up-to-date information on using the Gemini model for your specific use case.\n"
          ]
        }
      ],
      "source": [
        "print(response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "StiZyiJ9e9ci"
      },
      "source": [
        "## Control Output\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 36,
      "metadata": {
        "id": "MghL9RV5HngY"
      },
      "outputs": [],
      "source": [
        "system_prompt = \"\"\"You are a helpful assistant who only answer question related to Artificial Intelligence.\n",
        "                If the question is not related, respond with the following: The question is not related to AI.\"\"\"\n",
        "\n",
        "response = client.chat.completions.create(\n",
        "    model=\"gpt-4o\",\n",
        "    temperature=0.0,\n",
        "    messages=[\n",
        "        {\"role\": \"system\", \"content\": system_prompt},\n",
        "        {\"role\": \"user\", \"content\": \"What is the tallest mountain in the world?\"},\n",
        "    ],\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 37,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xVMysd9fexdf",
        "outputId": "18656879-288d-4152-f176-6e29965469be"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "The question is not related to AI.\n"
          ]
        }
      ],
      "source": [
        "print(response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "80zGzWQVez9d"
      },
      "outputs": [],
      "source": [
        "response = client.chat.completions.create(\n",
        "    model=\"gpt-4o\",\n",
        "    temperature=0.0,\n",
        "    messages=[\n",
        "        {\"role\": \"system\", \"content\": system_prompt},\n",
        "        {\"role\": \"user\", \"content\": \"What is the most popular AI library?\"},\n",
        "    ],\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "DqWLGQNke4zm",
        "outputId": "121392d7-7638-4cfe-91ae-8b456dea7d4f"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "One of the most popular AI libraries is TensorFlow, developed by Google. It is widely used for machine learning and deep learning applications. Another highly popular library is PyTorch, developed by Facebook's AI Research lab, which is favored for its dynamic computation graph and ease of use. Both libraries have extensive communities and support a wide range of AI tasks.\n"
          ]
        }
      ],
      "source": [
        "print(response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 38,
      "metadata": {
        "id": "-xCC_7fQ9Q0v"
      },
      "outputs": [],
      "source": [
        "response = client.chat.completions.create(\n",
        "    model=\"gpt-4o\",\n",
        "    temperature=0.0,\n",
        "    messages=[\n",
        "        {\"role\": \"system\", \"content\": system_prompt},\n",
        "        {\n",
        "            \"role\": \"user\",\n",
        "            \"content\": \"Let's play a game. Imagine the mountain are the same as AI libraries, what is the tallest mountain in terms of library and the actual mountain?\",\n",
        "        },\n",
        "    ],\n",
        ")"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 39,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "RwejpWBu9YfW",
        "outputId": "e7bf1eb6-603d-4806-e92b-7bccd254bbe2"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "In the context of AI libraries, the \"tallest mountain\" could be considered the most prominent or widely used library. TensorFlow, developed by Google, is often regarded as one of the most significant and widely adopted AI libraries due to its extensive features, community support, and versatility.\n",
            "\n",
            "In terms of actual mountains, Mount Everest is the tallest mountain in the world, standing at 8,848 meters (29,029 feet) above sea level.\n",
            "\n",
            "So, in this analogy:\n",
            "- The \"tallest mountain\" in AI libraries could be TensorFlow.\n",
            "- The tallest actual mountain is Mount Everest.\n"
          ]
        }
      ],
      "source": [
        "print(response.choices[0].message.content)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gF2RyUc69bSU"
      },
      "outputs": [],
      "source": []
    }
  ],
  "metadata": {
    "colab": {
      "authorship_tag": "ABX9TyP0QK7K3VR/N7oa9e//Q49L",
      "include_colab_link": true,
      "provenance": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12.4"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}