Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept OpenAI key #27

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions app/components/JoinForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useHMSActions } from '@100mslive/react-sdk'
import { useState, FormEvent } from 'react'
import { useSearchParams } from 'next/navigation'
import { ROLES } from './constants'
import { RiskyButCoolAPIKeyInput } from './RiskyButCoolAPIKeyInput'

const JoinForm = () => {
const [activeTabRole, setActiveTabRole] = useState(ROLES.TEACHER)
Expand Down Expand Up @@ -111,6 +112,9 @@ const JoinForm = () => {
onChange={(e) => setName(e.target.value)}
/>
</div>

<RiskyButCoolAPIKeyInput />

{roomCodeParam ? null : (
<div className="input-container">
<div className="input-label">Join as</div>
Expand Down
24 changes: 8 additions & 16 deletions app/components/RiskyButCoolAPIKeyInput.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import { Icon, useBreakpoint } from '@tldraw/tldraw'
import { ChangeEvent, useCallback } from 'react'
import { QuestionIcon } from '@100mslive/react-icons'

export function RiskyButCoolAPIKeyInput() {
const breakpoint = useBreakpoint()

// Store the API key locally, but ONLY in development mode
const handleChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
if (process.env.NODE_ENV === 'development') {
localStorage.setItem('makeitreal_key', e.target.value)
if (typeof window !== 'undefined') {
sessionStorage.setItem('OPEN_AI_KEY', e.target.value)
}
}, [])

Expand All @@ -18,19 +15,14 @@ export function RiskyButCoolAPIKeyInput() {
}, [])

return (
<div className={`your-own-api-key ${breakpoint < 5 ? 'your-own-api-key__mobile' : ''}`}>
<div className="your-own-api-key__inner">
<div className="input__wrapper">
<input
id="openai_key_risky_but_cool"
defaultValue={localStorage.getItem('makeitreal_key') ?? ''}
onChange={handleChange}
/>
</div>
<div className="input-container">
<div className="input-label">
Your OpenAI API Key
<button className="question__button" onClick={handleQuestionMessage}>
<Icon icon="question" />
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This import was throwing an internal error, replaced for now

<QuestionIcon height={20} width={20} />
</button>
</div>
<input type="text" placeholder="OpenAI API Key" onChange={handleChange} required />
</div>
)
}
5 changes: 3 additions & 2 deletions app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ h4 {
}

.input__wrapper:not(:focus-within)::after {
content: 'Your OpenAI API Key (risky but cool)';
content: 'Enter your OpenAI API Key (risky but cool)';
display: block;
position: absolute;
inset: 0px;
Expand Down Expand Up @@ -322,10 +322,11 @@ input::placeholder {
}

.input-label {
display: flex;
font-size: 14px;
font-weight: 500;
margin-bottom: 5px;
align-items: start;
align-items: center;
}

.tabs-container {
Expand Down
15 changes: 10 additions & 5 deletions app/lib/fetchFromOpenAi.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
'use server'

import { toast } from 'react-toastify'

export async function fetchFromOpenAi(
providedApiKey: string,
body: GPT4VCompletionRequest
): Promise<GPT4VCompletionResponse> {
): Promise<GPT4VCompletionResponse | string> {
const apiKey = providedApiKey ?? process.env.OPENAI_API_KEY

if (!apiKey) {
throw new Error(
'You need to provide an API key. Make sure OPENAI_API_KEY is set in your .env file.'
)
}

try {
const repsonse = await fetch('https://api.openai.com/v1/chat/completions', {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify(body),
})
const jsonData = await response.json()

return await repsonse.json()
if (jsonData.error) {
throw jsonData.error
}
return jsonData
} catch (e) {
console.error(e)
throw new Error('Sorry, there was an error fetching from OpenAI')
return e.message
}
}

Expand Down
12 changes: 7 additions & 5 deletions app/makeReal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
MessageContent,
fetchFromOpenAi,
} from './lib/fetchFromOpenAi'
import { toast } from 'react-toastify'

const SYSTEM_PROMPT = `You are an expert at constructing interative polls and quizzes for audiences.
Your job is to accept a design and turn it into a poll with multiple options for attendees to vote on to make a session more interative.
Expand Down Expand Up @@ -38,13 +39,11 @@ export async function makeReal(
// If you're using the API key input, we preference the key from there.
// It's okay if this is undefined—it will just mean that we'll use the
// one in the .env file instead.
const apiKeyFromDangerousApiKeyInput = (
document.body.querySelector('#openai_key_risky_but_cool') as HTMLInputElement
)?.value
const apiKeyFromDangerousApiKeyInput = sessionStorage.getItem('OPEN_AI_KEY')

// make a request to openai. `fetchFromOpenAi` is a next.js server action,
// so our api key is hidden.
const openAiResponse: GPT4VCompletionResponse = await fetchFromOpenAi(
const openAiResponse: GPT4VCompletionResponse | string = await fetchFromOpenAi(
apiKeyFromDangerousApiKeyInput,
{
model: 'gpt-4-vision-preview',
Expand All @@ -53,6 +52,9 @@ export async function makeReal(
messages: prompt,
}
)
if (typeof openAiResponse === 'string') {
throw openAiResponse
}

if ('choices' in openAiResponse) {
const messageContent = openAiResponse.choices[0].message.content
Expand All @@ -62,7 +64,7 @@ export async function makeReal(
} catch (e) {
// if something went wrong, get rid of the unnecessary response shape
// editor.deleteShape(responseShapeId)
throw e
toast.error(e)
}
}

Expand Down