├── LICENSE
├── Chapter08
└── Structure OCR text with GPT-3.5
└── README.md
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Packt
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Chapter08/Structure OCR text with GPT-3.5:
--------------------------------------------------------------------------------
1 | // This function handles HTTP POST requests.
2 | function doPost(e) {
3 | return handleRequest(e);
4 | }
5 |
6 | // This function processes the incoming POST request.
7 | function handleRequest(e) {
8 | // Create a text output to be returned as the HTTP response.
9 | const output = ContentService.createTextOutput();
10 |
11 | // Extract the JSON string from the POST data.
12 | const jsonString = e.postData.contents;
13 |
14 | // Parse the JSON string into a JavaScript object.
15 | const jsonData = JSON.parse(jsonString);
16 |
17 | // Extract specific data from the parsed JSON.
18 | const txt = jsonData.txt;
19 |
20 | const json = {
21 | "invoiceNumber": "string",
22 | "date": "string",
23 | "dueDate": "string",
24 | "invoiceTo": {
25 | "name": "string",
26 | "company": "string",
27 | },
28 | "project": "string",
29 | "subtotal": "number",
30 | "tax": "number",
31 | "adjustments": "number",
32 | "total": "number"
33 | }
34 |
35 |
36 | // Call the 'ai' function with the extracted data.
37 | const result = ai(txt, json);
38 |
39 | // Check if a callback parameter is provided in the request.
40 | const callback = e.parameters.callback;
41 | if (callback === undefined) {
42 | // If no callback is provided, return the result as JSON.
43 | output.setContent(JSON.stringify(result));
44 | } else {
45 | // If a callback is provided, return the result wrapped in the callback function.
46 | output.setContent(callback + "(" + JSON.stringify(result) + ")");
47 | }
48 |
49 | // Set the MIME type of the response as JSON.
50 | output.setMimeType(ContentService.MimeType.JSON);
51 |
52 | // Return the response.
53 | return output;
54 | }
55 |
56 | // This function performs some AI-related processing.
57 | function ai(txt, json) {
58 | // GPT-3.5 and GPT-4 and other LLMs use text as inputs. Thus, we need to stringify the json object.
59 | const jsonString = JSON.stringify(json)
60 |
61 | // Generate a prompt based on the input data.
62 | let prompt = "use the [text] extracted from an invoice using OCR. Structure it as a JSON object with the structure shown in the [JSON model].\n[text]=" + txt + "\n[JSON model] = "+ jsonString + "n\keep the same structure of the JSON as in the model, including the same keys.";
63 |
64 | // Create a data object with the specified parameters.
65 | const data = {
66 | "model": "gpt-3.5-turbo-16k-0613", //"gpt-4-0613", //
67 | "messages": [{"role": "user", "content": prompt}],
68 | "temperature": .9
69 | };
70 |
71 | // Configure options for making an HTTP POST request to an API.
72 | const options = {
73 | 'method': 'post',
74 | 'headers': { 'Authorization': 'Bearer OPENAI_API_KEY' },
75 | 'contentType': 'application/json',
76 | 'payload': JSON.stringify(data),
77 | 'muteHttpExceptions': true
78 | };
79 |
80 | // Define the URL for the API endpoint.
81 | const url = "https://api.openai.com/v1/chat/completions";
82 |
83 | try {
84 | // Make an HTTP POST request to the API.
85 | const response = UrlFetchApp.fetch(url, options);
86 |
87 | // Parse the response JSON.
88 | const res = JSON.parse(response.getContentText());
89 | console.log(res)
90 |
91 | // Check for and handle any errors in the response.
92 | if (res.error) {
93 | console.log("Error: " + res.error.type + " message: " + res.error.message);
94 | return res.error;
95 | }
96 |
97 | // Extract and trim the AI-generated content.
98 | output = res.choices[0].message.content.trim();
99 |
100 | // Return the AI-generated output.
101 |
102 | console.log(JSON.parse(output))
103 | return JSON.parse(output);
104 | } catch (error) {
105 | console.log("Error: " + error);
106 | return "An error occurred: " + error;
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Unlocking the Secrets of Prompt Engineering
2 | Unlocking the Secrets of Prompt Engineering, published by Packt
3 |
4 | This is the code repository for [Unlocking the Secretes of Prompt Engineering.](https://www.packtpub.com/product/unlocking-the-secrets-of-prompt-engineering/978183508383), published by Packt.
5 |
6 | ## What is this book about?
7 | This book is for a wide audience, including writers, marketing and business professionals, researchers, students, tech enthusiasts, and creative individuals. Anyone looking for strategies and examples for using AI co-writing tools like ChatGPT effectively in domains such as content creation, drafting emails, and inspiring artistic works, will find this book especially useful. If you are interested in AI, NLP, and innovative software for personal or professional use, this is the book for you.
8 |
9 | This book covers the following exciting features:
10 | * Explore the different types of prompts, their strengths, and weaknesses
11 | * Understand the AI agent's knowledge and mental model
12 | * Enhance your creative writing with AI insights for fiction and poetry
13 | * Develop advanced skills in AI chatbot creation and deployment
14 | * Discover how AI will transform industries such as education, legal, and others
15 | * Integrate LLMs with various tools to boost productivity
16 | * Understand AI ethics and best practices, and navigate limitations effectively
17 | * Experiment and optimize AI techniques for best results
18 |
19 | If you feel this book is for you, get your [copy]([https://www.amazon.com/Essential-Guide-Creating-Multiplayer-Games-ebook/dp/B0C8TGXWXR](https://www.amazon.com/Unlocking-Secrets-Prompt-Engineering-generation-ebook/dp/B0CL4V6ZZK)https://www.amazon.com/Unlocking-Secrets-Prompt-Engineering-generation-ebook/dp/B0CL4V6ZZK) today!
20 |
21 | ## Instructions and Navigations
22 | All of the files is organized into folders. For example, Chapter8.
23 |
24 | Unlocking the Secrets of Prompt Engineering is your key to mastering the art of AI-driven writing. This book propels you into the world of large language models (LLMs), empowering you to create and apply prompts effectively for diverse applications, from revolutionizing content creation and chatbots to coding assistance.
25 |
26 | With the following software and hardware list you can run all code files present in the book.
27 |
28 | ### Software and Hardware List
29 | | Software required | OS required |
30 | | ------------------------------------ | ----------------------------------- |
31 | | OpenAI ChatGPT, GPT-3.5, and GPT-4 | Windows, macOS, or Linux |
32 | | Anthropic Claude 2 | |
33 | | Google Bard | |
34 |
35 |
36 | ### Related products
37 | * Building AI Applications with ChatGPT APIs [[Packt]](https://www.packtpub.com/product/building-ai-applications-with-chatgpt-apis/9781805127567) [Amazon](https://www.amazon.com/Building-Applications-ChatGPT-APIs-DALL/dp/180512756X)
38 |
39 | * Modern Generative AI with ChatGPT and OpenAI Models [[Packt]](https://www.packtpub.com/product/modern-generative-ai-with-chatgpt-and-openai-models/9781805123330) [Amazon](https://www.amazon.com/Modern-Generative-ChatGPT-OpenAI-Models/dp/1805123335)
40 |
41 | ## Get to Know the Author
42 | **Gilbert Mizrahi** is an accomplished professional with a diverse background and a passion for product strategy innovation, interactive data visualization, and AI. He holds an MS in Operations Research from Stanford University and a BS in Industrial Engineering. Gilbert founded three companies in digital cartography, high-end computer graphics integration, and commercial printing. He worked as a senior research engineer at Aptima, where he managed and contributed to projects funded by NASA, DARPA, The US Air Force, the NIH, and others. Gilbert has held multiple leadership roles, including CEO, president, and VP. As a co-founder at Twnel, he is currently the head of product R&D and is exploring AI-based solutions for clients.
43 |
44 |
45 |
--------------------------------------------------------------------------------