1# OpenAI ChatGPT helper function
2
3This val uses your OpenAI token if you have one, and the @std/openai if not, so it provides limited OpenAI usage for free.
4
5```ts
6import { chat } from "https://esm.town/v/stevekrouse/openai";
7
8const { content } = await chat("Hello, GPT!");
11
12```ts
13import { chat } from "https://esm.town/v/stevekrouse/openai";
14
15const { content } = await chat(
1import type { ChatCompletion, ChatCompletionCreateParamsNonStreaming, Message } from "npm:@types/openai";
2
3async function getOpenAI() {
4 // if you don't have a key, use our std library version
5 if (Deno.env.get("OPENAI_API_KEY") === undefined) {
6 const { OpenAI } = await import("https://esm.town/v/std/openai");
7 return new OpenAI();
8 } else {
9 const { OpenAI } = await import("npm:openai");
10 return new OpenAI();
11 }
12}
13
14/**
15 * Initiates a chat conversation with OpenAI's GPT model and retrieves the content of the first response.
16 * This function can handle both single string inputs and arrays of message objects.
17 * It supports various GPT models, allowing for flexibility in choosing the model based on the application's needs.
25 options?: Omit<ChatCompletionCreateParamsNonStreaming, "messages">,
26): Promise<ChatCompletion & { content: string }> {
27 const openai = await getOpenAI();
28 const messages = Array.isArray(input) ? input : [{ role: "user", content: input }];
29 const createParams: ChatCompletionCreateParamsNonStreaming = {
33 messages,
34 };
35 const completion = await openai.chat.completions.create(createParams);
36
37 return { ...completion, content: completion.choices[0].message.content };
13* and activity (befriends aliens, goes to the doctor, rides a rollercoaster, bakes a cake for friends)
14
15It uses OpenAI to write a children's bedtime story
16
17* title
21for a "fantastical story about a green whale who rides the bus" or the "spooky story about the tomato fox who explores a cave".
22
23Then using the summary, OpenAI geenrates another prompt to describe the instructions to generate a children's story book image.
24
25That's sent to Fal to generate an image.
15import { generateOpenGraphTags, OpenGraphData } from "https://esm.town/v/dthyresson/generateOpenGraphTags";
16import { ValTownLink } from "https://esm.town/v/dthyresson/viewOnValTownComponent";
17import { chat } from "https://esm.town/v/stevekrouse/openai";
18import * as fal from "npm:@fal-ai/serverless-client";
19
1// This calendar app will allow users to upload a PDF, extract events from it using OpenAI's GPT model,
2// and display them on a big calendar. We'll use react-big-calendar for the calendar component,
3// and pdf.js for PDF parsing. The server will handle PDF processing and event extraction.
121
122async function server(request: Request): Promise<Response> {
123 const { OpenAI } = await import("https://esm.town/v/std/openai");
124 const pdfExtractText = await import("https://esm.town/v/pdebieamzn/pdfExtractText");
125
136 const fullText = await pdfExtractText.default(arrayBuffer);
137
138 const openai = new OpenAI();
139 const completion = await openai.chat.completions.create({
140 messages: [
141 { role: "system", content: "You are a helpful assistant that extracts event information from text. Extract events with their titles, start times, and end times. Format the response as a valid JSON array of objects with 'title', 'start', and 'end' properties. Use ISO 8601 format for dates. Do not include any explanatory text outside the JSON array. Do not use markdown code fences or JSON labels. Consider the provided context when extracting events." },
158 events = JSON.parse(content);
159 } catch (error) {
160 console.error('Error parsing OpenAI response:', error);
161 console.log('Raw response:', completion.choices[0].message.content);
162 return new Response(JSON.stringify({ error: 'Error processing events' }), { status: 500, headers: { 'Content-Type': 'application/json' } });
164
165 if (!Array.isArray(events)) {
166 console.error('Unexpected response format from OpenAI');
167 return new Response(JSON.stringify({ error: 'Unexpected response format' }), { status: 500, headers: { 'Content-Type': 'application/json' } });
168 }
1// This calendar app will allow users to upload a PDF, extract events from it using OpenAI's GPT model,
2// and display them on a big calendar. We'll use react-big-calendar for the calendar component,
3// and pdf.js for PDF parsing. The server will handle PDF processing and event extraction.
82
83async function server(request: Request): Promise<Response> {
84 const { OpenAI } = await import("https://esm.town/v/std/openai");
85 const pdfExtractText = await import("https://esm.town/v/pdebieamzn/pdfExtractText");
86
96 const fullText = await pdfExtractText.default(arrayBuffer);
97
98 const openai = new OpenAI();
99 const completion = await openai.chat.completions.create({
100 messages: [
101 { role: "system", content: "You are a helpful assistant that extracts event information from text. Extract events with their titles, start times, and end times. Format the response as a valid JSON array of objects with 'title', 'start', and 'end' properties. Use ISO 8601 format for dates. Do not include any explanatory text outside the JSON array. Do not use markdown code fences or JSON labels." },
118 events = JSON.parse(content);
119 } catch (error) {
120 console.error('Error parsing OpenAI response:', error);
121 console.log('Raw response:', completion.choices[0].message.content);
122 return new Response(JSON.stringify({ error: 'Error processing events' }), { status: 500, headers: { 'Content-Type': 'application/json' } });
124
125 if (!Array.isArray(events)) {
126 console.error('Unexpected response format from OpenAI');
127 return new Response(JSON.stringify({ error: 'Unexpected response format' }), { status: 500, headers: { 'Content-Type': 'application/json' } });
128 }
6* Fork this val to your own profile.
7* Make a folder for the temporary vals that get generated, take the ID from the URL, and put it in `tempValsParentFolderId`.
8* If you want to use OpenAI models you need to set the `OPENAI_API_KEY` [env var](https://www.val.town/settings/environment-variables).
9* If you want to use Anthropic models you need to set the `ANTHROPIC_API_KEY` [env var](https://www.val.town/settings/environment-variables).
10* Create a [Val Town API token](https://www.val.town/settings/api), open the browser preview of this val, and use the API token as the password to log in.
1import { email } from "https://esm.town/v/std/email?v=11";
2import { OpenAI } from "npm:openai";
3
4let location = "Perth WA";
8).then(r => r.json());
9
10const openai = new OpenAI();
11let chatCompletion = await openai.chat.completions.create({
12 messages: [{
13 role: "user",
6* Fork this val to your own profile.
7* Make a folder for the temporary vals that get generated, take the ID from the URL, and put it in `tempValsParentFolderId`.
8* If you want to use OpenAI models you need to set the `OPENAI_API_KEY` [env var](https://www.val.town/settings/environment-variables).
9* If you want to use Anthropic models you need to set the `ANTHROPIC_API_KEY` [env var](https://www.val.town/settings/environment-variables).
10* Create a [Val Town API token](https://www.val.town/settings/api), open the browser preview of this val, and use the API token as the password to log in.
6* Fork this val to your own profile.
7* Make a folder for the temporary vals that get generated, take the ID from the URL, and put it in `tempValsParentFolderId`.
8* If you want to use OpenAI models you need to set the `OPENAI_API_KEY` [env var](https://www.val.town/settings/environment-variables).
9* If you want to use Anthropic models you need to set the `ANTHROPIC_API_KEY` [env var](https://www.val.town/settings/environment-variables).
10* Create a [Val Town API token](https://www.val.town/settings/api), open the browser preview of this val, and use the API token as the password to log in.