Skip to content
Open
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
37 changes: 25 additions & 12 deletions app/components/APIKeyInput.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Icon, useBreakpoint, useEditor, useValue } from '@tldraw/tldraw'
import { ChangeEvent, useCallback, useState } from 'react'
import { ChangeEvent, useCallback, useEffect, useState } from 'react'
import { useOpenRouter } from '../hooks/useOpenRouter'

export function APIKeyInput() {
const breakpoint = useBreakpoint()
const [cool, setCool] = useState(false)
const { apiKey, getCode, removeApiKey } = useOpenRouter()

const editor = useEditor()
const isFocusMode = useValue('is focus mode', () => editor.getInstanceState().isFocusMode, [
Expand All @@ -28,7 +30,7 @@ export function APIKeyInput() {
}, [])

const handleQuestionClick = useCallback(() => {
const message = `Sorry, this is weird. The OpenAI APIs that we use are very new. If you have an OpenAI developer key, you can put it in this input and we'll use it. We don't save / store / upload these.\n\nSee https://platform.openai.com/api-keys to get a key.\n\nThis app's source code: https://github.com/tldraw/draw-a-ui`
const message = `OpenRouter lets app leverage AI without breaking the developer's bank - users pay for what they use!\n\nThis app's source code: https://github.com/tldraw/draw-a-ui`
window.alert(message)
}, [])

Expand All @@ -37,16 +39,27 @@ export function APIKeyInput() {
return (
<div className={`your-own-api-key ${breakpoint < 6 ? '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}
onKeyDown={handleKeyDown}
spellCheck={false}
autoCapitalize="off"
/>
</div>
{!apiKey ? (
<button
onClick={getCode}
className="rounded w-full bg-indigo-500 hover:bg-indigo-600 transition-all text-white"
>
Access AI via OpenRouter
</button>
) : (
<div className="rounded w-full flex gap-2 items-center px-2">
<span className="text-xs">
OpenRouter <b>Connected</b>
</span>
<button
onClick={removeApiKey}
className="rounded w-full bg-indigo-500 hover:bg-indigo-600 transition-all text-white h-full"
>
Remove AI Access
</button>
</div>
)}

<button className="question__button" onClick={handleQuestionClick}>
<Icon icon={cool ? 'check' : 'question'} />
</button>
Expand Down
9 changes: 4 additions & 5 deletions app/hooks/useMakeReal.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
import { useEditor, useToasts } from '@tldraw/tldraw'
import { useCallback } from 'react'
import { useCallback, useEffect } from 'react'
import { makeReal } from '../lib/makeReal'
import { track } from '@vercel/analytics/react'
import { useOpenRouter } from './useOpenRouter'

export function useMakeReal() {
const editor = useEditor()
const toast = useToasts()
const { apiKey } = useOpenRouter()

return useCallback(async () => {
const input = document.getElementById('openai_key_risky_but_cool') as HTMLInputElement
const apiKey = input?.value ?? null

track('make_real', { timestamp: Date.now() })

try {
Expand All @@ -34,5 +33,5 @@ export function useMakeReal() {
],
})
}
}, [editor, toast])
}, [apiKey, editor, toast])
}
43 changes: 43 additions & 0 deletions app/hooks/useOpenRouter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useEffect, useState } from 'react'

const LOCAL_STORAGE_KEY = 'make-real:openrouter-api-key'

export function useOpenRouter() {
const [apiKey, setApiKey] = useState<string>(localStorage.getItem(LOCAL_STORAGE_KEY))

useEffect(() => {
if (window.location.search.includes('code=')) {
const params = new URLSearchParams(window.location.search)
const code = params.get('code')
if (code) {
fetch('https://openrouter.ai/api/v1/auth/keys', {
method: 'POST',
body: JSON.stringify({
code,
}),
})
.then((res) => res.json())
.then((res) => {
localStorage.setItem(LOCAL_STORAGE_KEY, res.key)
setApiKey(res.key)
window.location.search = ''
})
}
}
}, [])

const getCode = () => {
window.open(`https://openrouter.ai/auth?callback_url=${window.location.href}`, '_self')
}

const removeApiKey = () => {
localStorage.removeItem(LOCAL_STORAGE_KEY)
setApiKey('')
}

return {
apiKey,
getCode,
removeApiKey,
}
}
6 changes: 4 additions & 2 deletions app/lib/getHtmlFromOpenAI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function getHtmlFromOpenAI({
theme?: string
previousPreviews?: PreviewShape[]
}) {
if (!apiKey) throw Error('You need to provide an API key (sorry)')
if (!apiKey) throw Error('You need to connect with an AI provider')

const messages: GPT4VCompletionRequest['messages'] = [
{
Expand Down Expand Up @@ -100,11 +100,13 @@ export async function getHtmlFromOpenAI({
let json = null

try {
const resp = await fetch('https://api.openai.com/v1/chat/completions', {
const resp = await fetch('https://openrouter.ai/api/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
'HTTP-Referer': `https://makereal.tldraw.com/`,
'X-Title': `tldraw: make-real`,
},
body: JSON.stringify(body),
})
Expand Down
1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.