Тёмный

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

1littlecoder
Подписаться 84 тыс.
Просмотров 30 тыс.
50% 1

Опубликовано:

 

17 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 76   
@reputable.academy
@reputable.academy Год назад
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.
@kmfnj
@kmfnj Год назад
This video tutorial is an absolute game changer. TYVM 🙏 I am also very interested in more content about Chat GPT parameters. Subscribed! 🙌
@victormultanen1981
@victormultanen1981 Год назад
such a generous explanation on integrating open ai API to Google docs.
@BobbyTomMathew
@BobbyTomMathew 7 месяцев назад
Great content. Do you have a Pateron?
@DangRenBo
@DangRenBo Год назад
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 Год назад
Thank yo so much, Great to hear such a feedback!
@gyhuj1235
@gyhuj1235 Год назад
New to programming. Which IDE are you using to make this happen? How did it connect to the google doc UI?
@aranyagupta8588
@aranyagupta8588 Год назад
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? 🙃
@Memecointech
@Memecointech Год назад
Commenting before watching, keep it up bruh❤️
@1littlecoder
@1littlecoder Год назад
Appreciate it bro :)
@SachinKumar-rr4lk
@SachinKumar-rr4lk Год назад
You forced me to subscribe your channel. It was helpful. Thank You.
@1littlecoder
@1littlecoder Год назад
That's good to hear :)
@sfl1986
@sfl1986 Год назад
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
@ninacohea1907
@ninacohea1907 Год назад
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 Год назад
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?
@ratral
@ratral Год назад
Thank you!, I guess the same can be done on Google Sheets, where I could imagine another type of application.
@RevitaNariswaty
@RevitaNariswaty Год назад
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!
@akellman
@akellman Год назад
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?
@Serifinity
@Serifinity Год назад
Thank you for creating and sharing this 👍
@1littlecoder
@1littlecoder Год назад
My pleasure! :)
@divinusnobilite
@divinusnobilite Год назад
I am curious how we could integrate it with tabular data, like from Google sheets. This is great. Thank you!
@taxesen5
@taxesen5 Год назад
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 Год назад
@@taxesen5 LLM + Python Interpreter works fine with tabular data
@luzcamacho2050
@luzcamacho2050 Год назад
Do you have video on chatgpt integrated with Microsoft office applications?
@changchuntang1106
@changchuntang1106 Год назад
hi, how come your Google docs have this ChatGPT icon, while I don't ? is this service exclusive to some kind of users?
@Julianchuk
@Julianchuk Год назад
ty for the video, but for noobs, how to deploy to keep the CHATGPT button available everytime we open a G doc?
@RohanAttravanam
@RohanAttravanam Год назад
My man! Super impressed with this.
@1littlecoder
@1littlecoder Год назад
Thank you This has got extended to Google Slides now - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-jsXeWxELjZU.html
@RohanAttravanam
@RohanAttravanam Год назад
@@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
@AnnaRose-gl7ob
@AnnaRose-gl7ob Год назад
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.
@lhr65
@lhr65 Год назад
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
@iamtheone9242
@iamtheone9242 Год назад
Love your content Man keep up
@1littlecoder
@1littlecoder Год назад
Glad you enjoy it!
@ZylerKade
@ZylerKade Год назад
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
@albertogaragnani5688
@albertogaragnani5688 Год назад
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
@VijayJadhav-q4h
@VijayJadhav-q4h Год назад
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?
@nic-ori
@nic-ori Год назад
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 Год назад
yes, or if you havea free trial going on.
@kaledith6546
@kaledith6546 Год назад
SIGN AND GIVE ALL THE APROVALS TO YOUR ORGANS jokes, thanks for the tutorial :)
@SalarKhan45
@SalarKhan45 8 месяцев назад
Please use python as it widely used in AI.
@ahmadzaimhilmi
@ahmadzaimhilmi Год назад
What if I want to use python instead? Is there a workaround?
@m.moustaphathiam8308
@m.moustaphathiam8308 Год назад
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
@gowthamdora6146
@gowthamdora6146 Год назад
If we pay 2$ for one time then we can integrate this chat gpt for all the time ?
@emmcode3414
@emmcode3414 10 месяцев назад
This channel should be called Chad Coder
@1littlecoder
@1littlecoder 10 месяцев назад
Is that a compliment or a complaint 😕
@emmcode3414
@emmcode3414 10 месяцев назад
Completely a compliment! thank you for your work @@1littlecoder
@bipolarniba5537
@bipolarniba5537 Месяц назад
@@1littlecoder compliment
@gigibodwin6480
@gigibodwin6480 Год назад
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 Год назад
We would need to deploy this appscript then, I'll explore the possibilities
@gigibodwin6480
@gigibodwin6480 Год назад
@@1littlecoder Thanks. I look forward to it
@1littlecoder
@1littlecoder Год назад
Also I've extended this series with Google Sheets and Slides, please check it out - ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-jsXeWxELjZU.html
@JohnLordViking
@JohnLordViking Год назад
congrats. excellent video!
@missionadventureswithserena
@missionadventureswithserena 7 месяцев назад
I just want to paste info from chatgpt to docs... how do I fix the format 😭😭😭😭
@thscnh
@thscnh Год назад
Its amazing! Thanks for sharing.
@1littlecoder
@1littlecoder Год назад
Glad you like it!
@mingtech5670
@mingtech5670 Год назад
You're awesome. Thank you!
@senthilnayagam5139
@senthilnayagam5139 Год назад
please do a video on google sheet integration
@Kalease54
@Kalease54 Год назад
Another gem!
@rajeshkannanmj
@rajeshkannanmj Год назад
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 Год назад
7,500 words = 2 cents
@MikeFilsaime-com
@MikeFilsaime-com Год назад
1 million words would cost approximately $2.67
@shubhamverma9148
@shubhamverma9148 Год назад
​@@MikeFilsaime-com are cost count only for prompt token input ? or applied input+output token?
@doppelgangster
@doppelgangster Год назад
Solid to pre
@agdgassociates4655
@agdgassociates4655 Год назад
Its not giving same response which we get on web ChatGPT
@serta5727
@serta5727 Год назад
It’s cool thanks :)
@Ryan-yj4sd
@Ryan-yj4sd Год назад
Could you make a chatbot in streamlit?
@cinemaworld4644
@cinemaworld4644 Год назад
how do i add the chatgpt menu?
@cinemaworld4644
@cinemaworld4644 Год назад
ok. ı correct. :)
@cinemaworld4644
@cinemaworld4644 Год назад
solved :)
@julianswebbelearningcentre
@julianswebbelearningcentre Год назад
there's chrome extensions now that work first time... why mess around with this when you can have success quickly
@Kyrana4102
@Kyrana4102 Год назад
Why are people afraid to write with chat gbt, as if it is not true writing :(
@WeioManderson-zq5fv
@WeioManderson-zq5fv Год назад
Template of letter
@childsavedmylife
@childsavedmylife Год назад
Great content, so helpful. Newbie here, wanted to ask how many more functions and commands can we add to the original two? Thanks!
@julianswebbelearningcentre
@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 Год назад
same here
@kingloufassa
@kingloufassa Год назад
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.
Далее
New OpenAI Chat Playground powered by ChatGPT Model
9:17
Wildest 10 SECONDS OF HIS LIFE 🤯 @TomIsted
00:14
Просмотров 4,8 млн
Don't Use ChatGPT Until You Watch This Video
13:40
Просмотров 1,7 млн
Create a Custom AI Assistant + API in 10 Mins
10:28
Просмотров 114 тыс.
Wildest 10 SECONDS OF HIS LIFE 🤯 @TomIsted
00:14
Просмотров 4,8 млн