How to integrate ChatGPT API with Google Docs - AI Content Writer

Sdílet
Vložit
  • čas přidán 28. 08. 2024
  • In this Tutorial, We will learn how to build your own AI Content Writer with ChatGPT API on Google Docs.
    This video covers the following tutorials:
    1. How to get OpenAI API Key
    2. Apps Script of Google Docs
    3. Code Walkthrough of ChatGPT Apps Script
    4. Final Demo of ChatGPT inside Google Docs
    Create ChatGPT API Key here - platform.opena...
    Full Code github.com/amr...
    ❤️ If you want to support the channel ❤️
    Support here:
    Patreon - / 1littlecoder
    Ko-Fi - ko-fi.com/1lit...

Komentáře • 75

  • @reputable.academy
    @reputable.academy Před rokem

    I spent hours trying to find someone who could make it simple. Thank you so much for making the video and being so generous with your sharing of the script.

  • @victormultanen1981
    @victormultanen1981 Před rokem +2

    such a generous explanation on integrating open ai API to Google docs.

  • @kmfnj
    @kmfnj Před rokem +2

    This video tutorial is an absolute game changer. TYVM 🙏 I am also very interested in more content about Chat GPT parameters. Subscribed! 🙌

  • @DangRenBo
    @DangRenBo Před rokem +2

    This video is a godsend. I suck as a programmer, but I was beginning to investigate how to do exactly this for a curriculum project I'm working on. Thank you. Subscribed!

    • @1littlecoder
      @1littlecoder  Před rokem

      Thank yo so much, Great to hear such a feedback!

  • @BobbyTomMathew
    @BobbyTomMathew Před 6 měsíci +2

    Great content. Do you have a Pateron?

  • @SachinKumar-rr4lk
    @SachinKumar-rr4lk Před rokem +1

    You forced me to subscribe your channel. It was helpful. Thank You.

  • @Memecointech
    @Memecointech Před rokem +1

    Commenting before watching, keep it up bruh❤️

  • @emmcode3414
    @emmcode3414 Před 8 měsíci

    This channel should be called Chad Coder

    • @1littlecoder
      @1littlecoder  Před 8 měsíci

      Is that a compliment or a complaint 😕

    • @emmcode3414
      @emmcode3414 Před 8 měsíci +1

      Completely a compliment! thank you for your work @@1littlecoder

  • @Serifinity
    @Serifinity Před rokem +3

    Thank you for creating and sharing this 👍

  • @ratral
    @ratral Před rokem +1

    Thank you!, I guess the same can be done on Google Sheets, where I could imagine another type of application.

  • @RohanAttravanam
    @RohanAttravanam Před rokem +1

    My man! Super impressed with this.

    • @1littlecoder
      @1littlecoder  Před rokem

      Thank you This has got extended to Google Slides now - czcams.com/video/jsXeWxELjZU/video.html

    • @RohanAttravanam
      @RohanAttravanam Před rokem

      @@1littlecoder the script is local to the doc? How can make sure it persists whenever I open any new file/doc. I’ll check out the slides video also

  • @iamtheone9242
    @iamtheone9242 Před rokem +2

    Love your content Man keep up

  • @divinusnobilite
    @divinusnobilite Před rokem +3

    I am curious how we could integrate it with tabular data, like from Google sheets. This is great. Thank you!

    • @taxesen5
      @taxesen5 Před rokem

      In general, LLMs are not good to work on tabular data, only natural language. You could translate this data into natural language and feee it to the LLM.

    • @isaakmwangi4618
      @isaakmwangi4618 Před rokem

      @@taxesen5 LLM + Python Interpreter works fine with tabular data

  • @sfl1986
    @sfl1986 Před rokem +2

    How to create a function that would prompt to summarizea long article (5k plus words) as input and would use chunking to read the whole article and give one output

  • @kaledith6546
    @kaledith6546 Před rokem +2

    SIGN AND GIVE ALL THE APROVALS TO YOUR ORGANS
    jokes, thanks for the tutorial :)

  • @thscnh
    @thscnh Před rokem +1

    Its amazing! Thanks for sharing.

  • @SalarKhan45
    @SalarKhan45 Před 6 měsíci +1

    Please use python as it widely used in AI.

  • @ninacohea1907
    @ninacohea1907 Před rokem +1

    I was able to implement this code and I really like it. I was wondering how I would be able to edit it to use Chat GPT 4, and/or preferably, be able to connect it to my paid GPT account and to a specific chat I have open with Chat GPT. I'm trying to have Chat GPT analyze a fiction work I'm writing, but with the text limit, it forgets what happens in the story all the time. I was hoping using this extension would solve the issue, but there's still a text limit. Is there any way to get around these issues?

    • @ninacohea1907
      @ninacohea1907 Před rokem +1

      So I attempted to fix this issue with this code:
      // Constants
      const API_KEY = "sk-xxxx";
      const MODEL_TYPE = "gpt-3.5-turbo";
      // Creates a custom menu in Google Docs
      function onOpen() {
      DocumentApp.getUi().createMenu("ChatGPT")
      .addItem("Generate Prompt", "generatePrompt")
      .addItem("Review Section", "generateIdeas")
      .addItem("Update ChatGPT on Story", "main")
      .addItem("Analyze and Provide Suggestions", "analyzeAndProvideSuggestions")
      .addItem("Generate Continuation Prompt", "generateContinuationPrompt")
      .addToUi();
      }
      // Function to get Google Doc content starting from "Chapter 1" and log element types
      function getDocContent() {
      const doc = DocumentApp.getActiveDocument();
      const body = doc.getBody();
      const totalElements = body.getNumChildren();
      let content = "";
      let foundStartChapter = false;
      for (let i = 0; i < totalElements; ++i) {
      const element = body.getChild(i);
      const elementType = element.getType();
      Logger.log("Element Type: " + elementType); // Log the element type
      if (element.getText) {
      Logger.log("Element Content: " + element.getText()); // Log content if it has a getText method
      }
      if (element.getText && element.getText().includes("Chapter 1")) {
      foundStartChapter = true;
      }
      if (foundStartChapter) {
      if (element.getText) {
      content += element.getText() + "
      ";
      }
      }
      }
      Logger.log("Content obtained: " + (content || "None")); // Log the content
      return content;
      }
      // Function to split the content into smaller segments
      function splitContent(content) {
      const maxLength = 900;
      const segments = [];
      let start = 0;
      while (start < content.length) {
      const segment = content.substring(start, start + maxLength);
      segments.push(segment);
      start += maxLength;
      }
      return segments;
      }
      // Function to send a segment to ChatGPT
      function sendSegmentToChatGPT(segment, context = "") {
      const prompt = context + segment;
      const temperature = 0;
      const maxTokens = 2000;
      const requestBody = {
      model: MODEL_TYPE,
      messages: [{role: "user", content: prompt}],
      temperature,
      max_tokens: maxTokens,
      };
      const requestOptions = {
      method: "POST",
      headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + API_KEY,
      },
      payload: JSON.stringify(requestBody),
      };
      const response = UrlFetchApp.fetch("api.openai.com/v1/chat/completions", requestOptions);
      const responseText = response.getContentText();
      const json = JSON.parse(responseText);
      const generatedText = json['choices'][0]['message']['content'];
      Logger.log(generatedText);
      }
      function main() {
      const context = "Your high-level synopsis or sticky notes here.";
      const content = getDocContent();
      const doc = DocumentApp.getActiveDocument();
      const body = doc.getBody();
      if (content === "") {
      body.appendParagraph("No content found starting from 'Chapter 1'.");
      return;
      }
      body.appendParagraph("Found content, proceeding to split and send to GPT-3.");
      const segments = splitContent(content);
      const scriptProperties = PropertiesService.getScriptProperties();
      let lastProcessedIndex = scriptProperties.getProperty('lastProcessedIndex');
      body.appendParagraph("LastProcessedIndex before: " + lastProcessedIndex);
      if (!lastProcessedIndex) {
      lastProcessedIndex = 0;
      } else {
      lastProcessedIndex = parseInt(lastProcessedIndex);
      }
      const maxIterations = 5;
      for (let i = lastProcessedIndex; i < Math.min(lastProcessedIndex + maxIterations, segments.length); i++) {
      body.appendParagraph(`Processing segment ${i + 1} of ${segments.length}`);
      sendSegmentToChatGPT(segments[i], context);
      scriptProperties.setProperty('lastProcessedIndex', i + 1);
      }
      body.appendParagraph("LastProcessedIndex after: " + scriptProperties.getProperty('lastProcessedIndex'));
      if (lastProcessedIndex + maxIterations >= segments.length) {
      scriptProperties.deleteProperty('lastProcessedIndex');
      Logger.log("Processing completed.");
      } else {
      Logger.log("Partial processing completed. Run the script again to continue.");
      }
      Logger.log("Last processed index after update: " + scriptProperties.getProperty('lastProcessedIndex'));
      }
      function analyzeAndProvideSuggestions() {
      const doc = DocumentApp.getActiveDocument();
      const body = doc.getBody();
      // Get the content of the entire story
      const content = getDocContent();
      // Set up the prompt with story context
      const prompt = "Analyze the following story and provide suggestions:

      " + content;
      const temperature = 0.7; // Adjust the temperature for creativity
      const maxTokens = 200; // You can adjust the max tokens based on the desired response length
      const requestBody = {
      model: MODEL_TYPE,
      messages: [{ role: "user", content: prompt }],
      temperature,
      max_tokens: maxTokens,
      };
      const requestOptions = {
      method: "POST",
      headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + API_KEY,
      },
      payload: JSON.stringify(requestBody),
      };
      const response = UrlFetchApp.fetch(
      "api.openai.com/v1/chat/completions",
      requestOptions
      );
      const responseText = response.getContentText();
      const json = JSON.parse(responseText);
      const generatedText = json["choices"][0]["message"]["content"];
      // Append suggestions to the end of the document
      body.appendParagraph("Suggestions for improving your story:");
      body.appendParagraph(generatedText);
      // Return the generated suggestions
      return generatedText;
      }
      // Create a function to generate prompts for continuing the story
      function generateContinuationPrompt() {
      const doc = DocumentApp.getActiveDocument();
      const body = doc.getBody();
      const selectedText = doc.getSelection().getRangeElements()[0].getElement().asText().getText();
      // Get the context for the prompt
      const context = getDocContent(selectedText);
      // Get suggestions for continuing the story
      const suggestions = analyzeAndProvideSuggestions(context);
      // Append the suggestions to the document
      body.appendParagraph("Suggestions for continuing the story:");
      body.appendParagraph(suggestions);
      }
      // Placeholder for your existing functions
      function generatePrompt() {
      const doc = DocumentApp.getActiveDocument();
      const selectedText = doc.getSelection().getRangeElements()[0].getElement().asText().getText();
      const body = doc.getBody();
      const prompt = "Generate an essay on " + selectedText;
      const temperature = 0;
      const maxTokens = 2060;
      const requestBody = {
      model: MODEL_TYPE,
      messages: [{role: "user", content: prompt}],
      temperature,
      max_tokens: maxTokens,
      };
      const requestOptions = {
      method: "POST",
      headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + API_KEY,
      },
      payload: JSON.stringify(requestBody),
      };
      const response = UrlFetchApp.fetch("api.openai.com/v1/chat/completions", requestOptions);
      const responseText = response.getContentText();
      const json = JSON.parse(responseText);
      const generatedText = json['choices'][0]['message']['content'];
      Logger.log(generatedText);
      body.appendParagraph(generatedText.toString());
      }
      function generateIdeas() {
      const doc = DocumentApp.getActiveDocument();
      const selectedText = doc.getSelection().getRangeElements()[0].getElement().asText().getText();
      const body = doc.getBody();
      const prompt = "Help me come up with ideas for this text based on the story so far. This is the text:" + selectedText;
      const temperature = 0;
      const maxTokens = 2060;
      const requestBody = {
      model: MODEL_TYPE,
      messages: [{role: "user", content: prompt}],
      temperature,
      max_tokens: maxTokens,
      };
      const requestOptions = {
      method: "POST",
      headers: {
      "Content-Type": "application/json",
      Authorization: "Bearer " + API_KEY,
      },
      payload: JSON.stringify(requestBody),
      };
      const response = UrlFetchApp.fetch("api.openai.com/v1/chat/completions", requestOptions);
      const responseText = response.getContentText();
      const json = JSON.parse(responseText);
      const generatedText = json['choices'][0]['message']['content'];
      Logger.log(generatedText);
      body.appendParagraph(generatedText.toString());
      }
      But I'm having a lot of issues with it. It keeps looping through my document and the Analyze function doesn't seem to be able to get the information from the document to use as context. Any advice?

  • @JohnLordViking
    @JohnLordViking Před rokem

    congrats. excellent video!

  • @aranyagupta8588
    @aranyagupta8588 Před rokem +1

    Thanks for this tutorial on my request. But I have a doubt..... Do I need to write this code for each time for google doc opening?
    🙃

  • @gyhuj1235
    @gyhuj1235 Před rokem

    New to programming. Which IDE are you using to make this happen? How did it connect to the google doc UI?

  • @mingtech5670
    @mingtech5670 Před rokem

    You're awesome. Thank you!

  • @childsavedmylife
    @childsavedmylife Před rokem

    Great content, so helpful. Newbie here, wanted to ask how many more functions and commands can we add to the original two? Thanks!

  • @Kalease54
    @Kalease54 Před rokem

    Another gem!

  • @user-vs1tj6ct2p
    @user-vs1tj6ct2p Před rokem

    Thank you for the video, super helpful. I wonder, can we train the ChatGPT with specific link (ex: Company's FAQ knowledge based) so when we try to generate articles, the source of the GPT is coming from that "specific link"? pardon for the noob question!

  • @luzcamacho2050
    @luzcamacho2050 Před rokem

    Do you have video on chatgpt integrated with Microsoft office applications?

  • @ZylerKade
    @ZylerKade Před rokem

    This is incredible, absolutely love it!! Thank you. I tweaked the code a bit to suit my own purposes, but only running into one minor issue. It seems like the 2nd option I added in ignores the selected text and just covers the entire text, not sure why. My first option is used to generate a blog outline based on the highlighted text, and my 2nd option is supposed to generate body content for the blog based on the section I highlight from the outline. But when I run the body generator, it just generates body sections for the entire blog outline instead of only my highlighted section. Any suggestions? :) -- either way, this is a gamechanger! Thanks again

  • @Julianchuk
    @Julianchuk Před rokem

    ty for the video, but for noobs, how to deploy to keep the CHATGPT button available everytime we open a G doc?

  • @m.moustaphathiam8308
    @m.moustaphathiam8308 Před rokem

    You are Awesome, I would like to see how you would go with NLP a and Arabic Handwriting Recognition from Old pictures In Pdf. Tried but no success

  • @AnnaRose-gl7ob
    @AnnaRose-gl7ob Před rokem

    Hello, Thank you for this amazing tutorial. How can I make it works for several lines / short paragraphs ? It seems that it stops working/sending the text as soon as it reaches a line break.

  • @akellman
    @akellman Před rokem

    Thank you, helpful video! Is there a way to tweak the code so that the history of the conversation is passed to chatgpt when I call it using the api?

  • @lhr65
    @lhr65 Před rokem

    This is very helpful. I'm copying your code. But I get a syntax error pointing to "headers" and won't let me save. Pls guide. Thanks

  • @albertogaragnani5688
    @albertogaragnani5688 Před rokem

    any tips on how to deal with texts that exceed the character limit? I want to use chat gpt to summarise podcast episodes giving the transcript as input

  • @user-kk1li5mk7q
    @user-kk1li5mk7q Před rokem

    I was able to successfully add the extension. However next time when I went to the google docs, the extension was not present. I had to reconfigure it again. How can I save this permanently?

  • @senthilnayagam5139
    @senthilnayagam5139 Před rokem

    please do a video on google sheet integration

  • @serta5727
    @serta5727 Před rokem

    It’s cool thanks :)

  • @rajeshkannanmj
    @rajeshkannanmj Před rokem

    Very nice bro. Now, If only I know how to code, I think I can make a lot of tools for many small business people.
    BTW, how much does it cost to generate 2000 words in chatGPT?

    • @MikeFilsaime-com
      @MikeFilsaime-com Před rokem

      7,500 words = 2 cents

    • @MikeFilsaime-com
      @MikeFilsaime-com Před rokem +1

      1 million words would cost approximately $2.67

    • @shubhamverma9148
      @shubhamverma9148 Před rokem

      ​@@MikeFilsaime-com are cost count only for prompt token input ? or applied input+output token?

  • @doppelgangster
    @doppelgangster Před rokem

    Solid to pre

  • @changchuntang1106
    @changchuntang1106 Před rokem

    hi, how come your Google docs have this ChatGPT icon, while I don't ? is this service exclusive to some kind of users?

  • @nic-ori
    @nic-ori Před rokem +1

    Do I understand correctly that this only works with the paid plan? My answer is "You have exceeded your current quota, please check your plan and billing information".

    • @rheavictor7
      @rheavictor7 Před rokem

      yes, or if you havea free trial going on.

  • @serenamojela
    @serenamojela Před 5 měsíci

    I just want to paste info from chatgpt to docs... how do I fix the format 😭😭😭😭

  • @ahmadzaimhilmi
    @ahmadzaimhilmi Před rokem

    What if I want to use python instead? Is there a workaround?

  • @agdgassociates4655
    @agdgassociates4655 Před rokem

    Its not giving same response which we get on web ChatGPT

  • @gowthamdora6146
    @gowthamdora6146 Před rokem

    If we pay 2$ for one time then we can integrate this chat gpt for all the time ?

  • @gigibodwin6480
    @gigibodwin6480 Před rokem

    Thank you so much for this. One question, the ChatGPT menu item disappears when I open a new doc. Is there a way to stop that from happening?

    • @1littlecoder
      @1littlecoder  Před rokem +1

      We would need to deploy this appscript then, I'll explore the possibilities

    • @gigibodwin6480
      @gigibodwin6480 Před rokem

      @@1littlecoder Thanks. I look forward to it

    • @1littlecoder
      @1littlecoder  Před rokem +2

      Also I've extended this series with Google Sheets and Slides, please check it out - czcams.com/video/jsXeWxELjZU/video.html

  • @Ryan-yj4sd
    @Ryan-yj4sd Před rokem

    Could you make a chatbot in streamlit?

  • @julianswebbelearningcentre

    there's chrome extensions now that work first time... why mess around with this when you can have success quickly

  • @Kyrana4102
    @Kyrana4102 Před rokem

    Why are people afraid to write with chat gbt, as if it is not true writing :(

  • @WeioManderson-zq5fv
    @WeioManderson-zq5fv Před 11 měsíci

    Template of letter

  • @cinemaworld4644
    @cinemaworld4644 Před rokem

    how do i add the chatgpt menu?

  • @julianswebbelearningcentre

    Hi, thanks for that BUT all I did was add my API key into your code, saved and ran but I get the error:
    10:38:54 AM Error
    Exception: Cannot call DocumentApp.getUi() from this context.
    onOpen @ Code.gs:7
    only added my API into your code, I didn't change anything else, can you please tell me what's wrong? Thank you

    • @kingloufassa
      @kingloufassa Před rokem

      same here

    • @kingloufassa
      @kingloufassa Před rokem

      I figured it out. Don't delete the function when you first come to the code. You have to paste his code INSIDE the function {} brackets that already exist and it will work.