84 | );
85 | }
86 |
87 | export default App;
88 |
--------------------------------------------------------------------------------
/src/components/PromptToLocation.jsx:
--------------------------------------------------------------------------------
1 | import PropTypes from "prop-types";
2 |
3 | const PromptToLocation = (prompt) => {
4 | const url = "https://api.openai.com/v1/chat/completions";
5 |
6 | const data = {
7 | model: "gpt-3.5-turbo-0613",
8 | messages: [{ role: "user", content: prompt }],
9 | functions: [
10 | {
11 | name: "displayData",
12 | description: "Get the current weather in a given location.",
13 | parameters: {
14 | type: "object",
15 | properties: {
16 | country: {
17 | type: "string",
18 | description: "Country name.",
19 | },
20 | countryCode: {
21 | type: "string",
22 | description: "Country code. Use ISO-3166",
23 | },
24 | USstate: {
25 | type: "string",
26 | description: "Full state name.",
27 | },
28 | state: {
29 | type: "string",
30 | description: "Two-letter state code.",
31 | },
32 | city: {
33 | type: "string",
34 | description: "City name.",
35 | },
36 | unit: {
37 | type: "string",
38 | description: "location unit: metric or imperial.",
39 | },
40 | },
41 | required: [
42 | "countryCode",
43 | "country",
44 | "USstate",
45 | "state",
46 | "city",
47 | "unit",
48 | ],
49 | },
50 | },
51 | ],
52 | function_call: "auto",
53 | };
54 |
55 | const params = {
56 | headers: {
57 | Authorization: `Bearer ${import.meta.env.VITE_OPENAI}`,
58 | "Content-Type": "application/json",
59 | },
60 | body: JSON.stringify(data),
61 | method: "POST",
62 | };
63 |
64 | return fetch(url, params)
65 | .then((response) => response.json())
66 | .then((data) => {
67 | const promptRes = JSON.parse(
68 | data.choices[0].message.function_call.arguments
69 | );
70 | console.log(promptRes);
71 |
72 | const locationString = () => {
73 | if (promptRes.countryCode === "US") {
74 | return `${promptRes.city},${promptRes.state},${promptRes.country}`;
75 | } else {
76 | return `${promptRes.city},${promptRes.country}`;
77 | }
78 | };
79 |
80 | const promptData = {
81 | locationString: locationString(),
82 | units: promptRes.unit,
83 | country: promptRes.country,
84 | USstate: promptRes.USstate
85 | }
86 |
87 | return promptData;
88 | })
89 | .catch((error) => {
90 | console.log("Error:", error);
91 | return Promise.reject(
92 | "Unable to identify a location from your question. Please try again."
93 | );
94 | });
95 | };
96 |
97 | PromptToLocation.propTypes = {
98 | prompt: PropTypes.string.isRequired,
99 | };
100 |
101 | export default PromptToLocation;
102 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Build a JavaScript AI App with React and the OpenAI API
2 | This is the repository for the LinkedIn Learning course Build a JavaScript AI App with React and the OpenAI API. The full course is available from [LinkedIn Learning][lil-course-url].
3 |
4 | ![Build a JavaScript AI App with React and the OpenAI API][lil-thumbnail-url]
5 |
6 | In this course, learn how to integrate the OpenAI API into a JavaScript-based web app. Join instructor Morten Rand-Hendriksen as he takes a React-based weather app, adds a heavy dose of AI, and creates an interactive experience that knows what location you want weather information from, explains the weather data in simple language, and even suggests what to wear. Through this project-based course, Morten teaches you about API integration, user-based authentication, storing user tokens in a ServiceWorker, task-based API configuration, and sending and receiving requests to the API.
7 |
8 | ## Instructions
9 | This repository has branches for each of the videos in the course. You can use the branch pop up menu in github to switch to a specific branch and take a look at the course at that stage, or you can add `/tree/BRANCH_NAME` to the URL to go to the branch you want to access.
10 |
11 | ## Branches
12 | The branches are structured to correspond to the videos in the course. The naming convention is `CHAPTER#_MOVIE#`. As an example, the branch named `02_03` corresponds to the second chapter and the third video in that chapter.
13 | Some branches will have a beginning and an end state. These are marked with the letters `b` for "beginning" and `e` for "end". The `b` branch contains the code as it is at the beginning of the movie. The `e` branch contains the code as it is at the end of the movie. The `main` branch holds the final state of the code when in the course.
14 |
15 | When switching from one exercise files branch to the next after making changes to the files, you may get a message like this:
16 |
17 | error: Your local changes to the following files would be overwritten by checkout: [files]
18 | Please commit your changes or stash them before you switch branches.
19 | Aborting
20 |
21 | To resolve this issue:
22 |
23 | Add changes to git using this command: git add .
24 | Commit changes using this command: git commit -m "some message"
25 |
26 | ## Installing
27 | 1. To use these exercise files, you must have the following installed:
28 | - Node.js
29 | 2. Clone this repository into your local machine using the terminal (Mac), CMD (Windows), or a GUI tool like SourceTree.
30 | 3. In terminal, run `npm install` to install all dependencies.
31 | 4. In terminal, run `npm run dev` to start the Vite dev server.
32 | 5. In terminal, type `o` to open the site in your browser.
33 | 6. In terminal, type `q` to stop the Vite dev server.
34 |
35 |
36 |
37 | ### Instructor
38 |
39 | Morten Rand-Hendriksen
40 |
41 | Developer and Senior Staff Instructor
42 |
43 |
44 |
45 | Check out my other courses on [LinkedIn Learning](https://www.linkedin.com/learning/instructors/morten-rand-hendriksen).
46 |
47 | [lil-course-url]: https://www.linkedin.com/learning/build-a-javascript-ai-app-with-react-and-the-openai-api?dApp=59033956&leis=LAA
48 | [lil-thumbnail-url]: https://media.licdn.com/dms/image/D560DAQGwwpM5Oem1Pw/learning-public-crop_288_512/0/1694808958256?e=2147483647&v=beta&t=8aOT86V8OE20qAcH8cwG-lc1LhmHB6fCRC0q4hmoVfk
49 | _See the readme file in the main branch for updated instructions and information._
50 |
51 |
--------------------------------------------------------------------------------
/src/assets/react.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/components/WeatherCard.jsx:
--------------------------------------------------------------------------------
1 | import PropTypes from "prop-types";
2 | import "./WeatherCard.css";
3 | import Loader from "./Loader";
4 |
5 | // Translate temperature from Kelvin to Celsius or Fahrenheit.
6 | const tempTranslator = (temp, unit) => {
7 | const allTemps = {
8 | k: {
9 | value: temp,
10 | unit: "°k",
11 | },
12 | c: {
13 | value: temp - 273,
14 | unit: "°C",
15 | },
16 | f: {
17 | value: 1.8 * (temp - 273) + 32,
18 | unit: "°F",
19 | },
20 | };
21 | if (unit === "metric") {
22 | return allTemps.c;
23 | } else if (unit === "imperial") {
24 | return allTemps.f;
25 | } else {
26 | return allTemps.k;
27 | }
28 | };
29 |
30 | // Translate wind speed from meters per second to feet per second.
31 | const speedTranslator = (speed, units) => {
32 | const allSpeeds = {
33 | metric: {
34 | value: speed,
35 | unit: "m/s",
36 | },
37 | imperial: {
38 | value: speed * 3.281,
39 | unit: "ft/s",
40 | },
41 | };
42 | if (units === "metric") {
43 | return allSpeeds.metric;
44 | } else if (units === "imperial") {
45 | return allSpeeds.imperial;
46 | } else {
47 | return allSpeeds.metric;
48 | }
49 | };
50 |
51 | const WeatherCard = ({
52 | isLoading,
53 | data,
54 | units,
55 | country,
56 | USstate,
57 | setUnits,
58 | }) => {
59 | // Display state if country is US.
60 | const stateDisplay = () => {
61 | if (data.sys.country === "US") {
62 | return `, ${USstate}`;
63 | } else {
64 | return "";
65 | }
66 | };
67 |
68 | // Handle unit change.
69 | const handleUnitChange = () => {
70 | if (units === "metric") {
71 | setUnits("imperial");
72 | } else {
73 | setUnits("metric");
74 | }
75 | };
76 |
77 | // Set wind direction.
78 | const windDirStyle = {
79 | transform: `rotate(${data.wind.deg + 90}deg)`,
80 | };
81 |
82 | return (
83 |
84 | {isLoading && }
85 |
116 |
117 | );
118 | };
119 |
120 | // default props
121 | WeatherCard.defaultProps = {
122 | data: {
123 | name: "--",
124 | sys: {
125 | country: "--",
126 | },
127 | main: {
128 | temp: 273,
129 | },
130 | wind: {
131 | speed: 0,
132 | deg: 0,
133 | },
134 | },
135 | units: "metric",
136 | setUnits: () => {},
137 | };
138 |
139 | // props validation
140 | WeatherCard.propTypes = {
141 | isLoading: PropTypes.bool,
142 | data: PropTypes.shape({
143 | name: PropTypes.string,
144 | sys: PropTypes.shape({
145 | country: PropTypes.string,
146 | }),
147 | main: PropTypes.shape({
148 | temp: PropTypes.number,
149 | }),
150 | wind: PropTypes.shape({
151 | speed: PropTypes.number,
152 | deg: PropTypes.number,
153 | }),
154 | }),
155 | units: PropTypes.string,
156 | country: PropTypes.string,
157 | USstate: PropTypes.string,
158 | setUnits: PropTypes.func,
159 | };
160 |
161 | export default WeatherCard;
162 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | LinkedIn Learning Exercise Files License Agreement
2 | ==================================================
3 |
4 | This License Agreement (the "Agreement") is a binding legal agreement
5 | between you (as an individual or entity, as applicable) and LinkedIn
6 | Corporation (“LinkedIn”). By downloading or using the LinkedIn Learning
7 | exercise files in this repository (“Licensed Materials”), you agree to
8 | be bound by the terms of this Agreement. If you do not agree to these
9 | terms, do not download or use the Licensed Materials.
10 |
11 | 1. License.
12 | - a. Subject to the terms of this Agreement, LinkedIn hereby grants LinkedIn
13 | members during their LinkedIn Learning subscription a non-exclusive,
14 | non-transferable copyright license, for internal use only, to 1) make a
15 | reasonable number of copies of the Licensed Materials, and 2) make
16 | derivative works of the Licensed Materials for the sole purpose of
17 | practicing skills taught in LinkedIn Learning courses.
18 | - b. Distribution. Unless otherwise noted in the Licensed Materials, subject
19 | to the terms of this Agreement, LinkedIn hereby grants LinkedIn members
20 | with a LinkedIn Learning subscription a non-exclusive, non-transferable
21 | copyright license to distribute the Licensed Materials, except the
22 | Licensed Materials may not be included in any product or service (or
23 | otherwise used) to instruct or educate others.
24 |
25 | 2. Restrictions and Intellectual Property.
26 | - a. You may not to use, modify, copy, make derivative works of, publish,
27 | distribute, rent, lease, sell, sublicense, assign or otherwise transfer the
28 | Licensed Materials, except as expressly set forth above in Section 1.
29 | - b. Linkedin (and its licensors) retains its intellectual property rights
30 | in the Licensed Materials. Except as expressly set forth in Section 1,
31 | LinkedIn grants no licenses.
32 | - c. You indemnify LinkedIn and its licensors and affiliates for i) any
33 | alleged infringement or misappropriation of any intellectual property rights
34 | of any third party based on modifications you make to the Licensed Materials,
35 | ii) any claims arising from your use or distribution of all or part of the
36 | Licensed Materials and iii) a breach of this Agreement. You will defend, hold
37 | harmless, and indemnify LinkedIn and its affiliates (and our and their
38 | respective employees, shareholders, and directors) from any claim or action
39 | brought by a third party, including all damages, liabilities, costs and
40 | expenses, including reasonable attorneys’ fees, to the extent resulting from,
41 | alleged to have resulted from, or in connection with: (a) your breach of your
42 | obligations herein; or (b) your use or distribution of any Licensed Materials.
43 |
44 | 3. Open source. This code may include open source software, which may be
45 | subject to other license terms as provided in the files.
46 |
47 | 4. Warranty Disclaimer. LINKEDIN PROVIDES THE LICENSED MATERIALS ON AN “AS IS”
48 | AND “AS AVAILABLE” BASIS. LINKEDIN MAKES NO REPRESENTATION OR WARRANTY,
49 | WHETHER EXPRESS OR IMPLIED, ABOUT THE LICENSED MATERIALS, INCLUDING ANY
50 | REPRESENTATION THAT THE LICENSED MATERIALS WILL BE FREE OF ERRORS, BUGS OR
51 | INTERRUPTIONS, OR THAT THE LICENSED MATERIALS ARE ACCURATE, COMPLETE OR
52 | OTHERWISE VALID. TO THE FULLEST EXTENT PERMITTED BY LAW, LINKEDIN AND ITS
53 | AFFILIATES DISCLAIM ANY IMPLIED OR STATUTORY WARRANTY OR CONDITION, INCLUDING
54 | ANY IMPLIED WARRANTY OR CONDITION OF MERCHANTABILITY OR FITNESS FOR A
55 | PARTICULAR PURPOSE, AVAILABILITY, SECURITY, TITLE AND/OR NON-INFRINGEMENT.
56 | YOUR USE OF THE LICENSED MATERIALS IS AT YOUR OWN DISCRETION AND RISK, AND
57 | YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE THAT RESULTS FROM USE OF THE
58 | LICENSED MATERIALS TO YOUR COMPUTER SYSTEM OR LOSS OF DATA. NO ADVICE OR
59 | INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM US OR THROUGH OR
60 | FROM THE LICENSED MATERIALS WILL CREATE ANY WARRANTY OR CONDITION NOT
61 | EXPRESSLY STATED IN THESE TERMS.
62 |
63 | 5. Limitation of Liability. LINKEDIN SHALL NOT BE LIABLE FOR ANY INDIRECT,
64 | INCIDENTAL, SPECIAL, PUNITIVE, CONSEQUENTIAL OR EXEMPLARY DAMAGES, INCLUDING
65 | BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA OR OTHER
66 | INTANGIBLE LOSSES . IN NO EVENT WILL LINKEDIN'S AGGREGATE LIABILITY TO YOU
67 | EXCEED $100. THIS LIMITATION OF LIABILITY SHALL:
68 | - i. APPLY REGARDLESS OF WHETHER (A) YOU BASE YOUR CLAIM ON CONTRACT, TORT,
69 | STATUTE, OR ANY OTHER LEGAL THEORY, (B) WE KNEW OR SHOULD HAVE KNOWN ABOUT
70 | THE POSSIBILITY OF SUCH DAMAGES, OR (C) THE LIMITED REMEDIES PROVIDED IN THIS
71 | SECTION FAIL OF THEIR ESSENTIAL PURPOSE; AND
72 | - ii. NOT APPLY TO ANY DAMAGE THAT LINKEDIN MAY CAUSE YOU INTENTIONALLY OR
73 | KNOWINGLY IN VIOLATION OF THESE TERMS OR APPLICABLE LAW, OR AS OTHERWISE
74 | MANDATED BY APPLICABLE LAW THAT CANNOT BE DISCLAIMED IN THESE TERMS.
75 |
76 | 6. Termination. This Agreement automatically terminates upon your breach of
77 | this Agreement or termination of your LinkedIn Learning subscription. On
78 | termination, all licenses granted under this Agreement will terminate
79 | immediately and you will delete the Licensed Materials. Sections 2-7 of this
80 | Agreement survive any termination of this Agreement. LinkedIn may discontinue
81 | the availability of some or all of the Licensed Materials at any time for any
82 | reason.
83 |
84 | 7. Miscellaneous. This Agreement will be governed by and construed in
85 | accordance with the laws of the State of California without regard to conflict
86 | of laws principles. The exclusive forum for any disputes arising out of or
87 | relating to this Agreement shall be an appropriate federal or state court
88 | sitting in the County of Santa Clara, State of California. If LinkedIn does
89 | not act to enforce a breach of this Agreement, that does not mean that
90 | LinkedIn has waived its right to enforce this Agreement. The Agreement does
91 | not create a partnership, agency relationship, or joint venture between the
92 | parties. Neither party has the power or authority to bind the other or to
93 | create any obligation or responsibility on behalf of the other. You may not,
94 | without LinkedIn’s prior written consent, assign or delegate any rights or
95 | obligations under these terms, including in connection with a change of
96 | control. Any purported assignment and delegation shall be ineffective. The
97 | Agreement shall bind and inure to the benefit of the parties, their respective
98 | successors and permitted assigns. If any provision of the Agreement is
99 | unenforceable, that provision will be modified to render it enforceable to the
100 | extent possible to give effect to the parties’ intentions and the remaining
101 | provisions will not be affected. This Agreement is the only agreement between
102 | you and LinkedIn regarding the Licensed Materials, and supersedes all prior
103 | agreements relating to the Licensed Materials.
104 |
105 | Last Updated: March 2019
106 |
--------------------------------------------------------------------------------