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

add base_url #32

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
55 changes: 39 additions & 16 deletions app/components/APIKeyInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,17 @@ import { ChangeEvent, useCallback, useState } from 'react'
export function APIKeyInput() {
const breakpoint = useBreakpoint()
const [cool, setCool] = useState(false)
const [baseUrl, setBaseUrl] = useState(localStorage.getItem('makeitreal_baseUrl') ?? '') // 新增状态

//BaseURL
const handleBaseUrlChange = useCallback((e: ChangeEvent<HTMLInputElement>) => { // 新增处理函数
if (process.env.NODE_ENV === 'development') {
localStorage.setItem('makeitreal_baseUrl', e.target.value)
setBaseUrl(e.target.value) // 更新状态
}
}, [])


const editor = useEditor()
const isFocusMode = useValue('is focus mode', () => editor.getInstanceState().isFocusMode, [
editor,
Expand Down Expand Up @@ -34,23 +44,36 @@ export function APIKeyInput() {

if (isFocusMode) return null


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>
<button className="question__button" onClick={handleQuestionClick}>
<Icon icon={cool ? 'check' : 'question'} />
</button>
<div className="your-own-api-key__inner">
<div className="input__wrapper">
<input
id="openai_key"
defaultValue={localStorage.getItem('makeitreal_key') ?? ''}
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder="Your OpenAI API Key " // 添加placeholder
spellCheck={false}
autoCapitalize="off"
/>
</div>
<div className="input__wrapper"> {/* 新增baseUrl输入字段 */}
<input
id="openai_baseUrl"
// value={baseUrl}
onChange={handleChange}
placeholder="Your OpenAI Base URL" // 添加placeholder
spellCheck={false}
autoCapitalize="off"
/>
</div>
<button className="question__button" onClick={handleQuestionClick}>
<Icon icon={cool ? 'check' : 'question'} />
</button>
</div>
</div>
)
}
)
}

2 changes: 1 addition & 1 deletion app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
}

.input__wrapper:not(:focus-within)::after {
content: 'Your OpenAI API Key (risky but cool)';
content: '';
display: block;
position: absolute;
inset: 0px;
Expand Down
11 changes: 9 additions & 2 deletions app/hooks/useMakeReal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,20 @@ export function useMakeReal() {
const toast = useToasts()

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

// 获取 Base URL
const baseUrlInput = document.getElementById('openai_baseUrl') as HTMLInputElement;
const baseUrl = baseUrlInput?.value;

console.log('API Key:', apiKey); // 调试输出 API Key
console.log('Base URL:', baseUrl); // 调试输出 Base URL

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

try {
await makeReal(editor, apiKey)
await makeReal(editor, apiKey, baseUrl)
} catch (e: any) {
track('no_luck', { timestamp: Date.now() })

Expand Down
6 changes: 4 additions & 2 deletions app/lib/getHtmlFromOpenAI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ export async function getHtmlFromOpenAI({
image,
html,
apiKey,
baseUrl, //添加作为可选参数,并且设置默认值
text,
theme = 'light',
includesPreviousDesign,
}: {
image: string
html: string
apiKey: string
baseUrl?: string
text: string
theme?: string
includesPreviousDesign?: boolean
Expand Down Expand Up @@ -56,13 +58,13 @@ export async function getHtmlFromOpenAI({
},
],
}

let json = null
if (!apiKey) {
throw Error('You need to provide an API key (sorry)')
}
try {
const resp = await fetch('https://api.openai.com/v1/chat/completions', {
const resp = await fetch(`${baseUrl}/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down
4 changes: 2 additions & 2 deletions app/lib/hosts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const env =
export const LINK_HOST = {
production: 'makereal.tldraw.link',
preview: `link---${process.env.NEXT_PUBLIC_VERCEL_URL}`,
development: 'makereal-link.localhost:3000',
development: 'www.kimi.asia',
}[env]

export const APP_HOST = {
Expand All @@ -17,4 +17,4 @@ export const APP_HOST = {
development: 'localhost:3000',
}[env]

export const PROTOCOL = env === 'development' ? 'http://' : 'https://'
export const PROTOCOL = env === 'development' ? 'http://' : 'https://'
4 changes: 3 additions & 1 deletion app/lib/makeReal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { sql } from '@vercel/postgres'
import { nanoid } from 'nanoid'
import { uploadLink } from './uploadLink'

export async function makeReal(editor: Editor, apiKey: string) {
export async function makeReal(editor: Editor, apiKey: string, baseUrl: string) {
const newShapeId = createShapeId()
const selectedShapes = editor.getSelectedShapes()

Expand Down Expand Up @@ -61,6 +61,7 @@ export async function makeReal(editor: Editor, apiKey: string) {
image: dataUrl,
html: previousHtml,
apiKey,
baseUrl,
text: textFromShapes,
includesPreviousDesign: previousPreviews.length > 0,
theme: editor.user.getUserPreferences().isDarkMode ? 'dark' : 'light',
Expand All @@ -70,6 +71,7 @@ export async function makeReal(editor: Editor, apiKey: string) {
throw Error(`${json.error.message?.slice(0, 100)}...`)
}

console.log('Response:', json)
console.log(`Response: ${json.choices[0].message.content}`)

const message = json.choices[0].message.content
Expand Down
6 changes: 5 additions & 1 deletion middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ export function middleware(req: NextRequest) {
const rewrittenUrl = new URL(url.toString())

if (host === LINK_HOST) {
console.log(`host === LINK_HOST->LINK_HOST: ${LINK_HOST}, Request Host: ${host}`);
// rewrite requests on the link host to the link site:
rewrittenUrl.pathname = `/makereal.tldraw.link${rewrittenUrl.pathname}`
if( rewrittenUrl.pathname){
rewrittenUrl.pathname = `/makereal.tldraw.link${rewrittenUrl.pathname}`;
}
} else {
console.log(`host !== LINK_HOST->LINK_HOST: ${LINK_HOST}, Request Host: ${host}`);
// rewrite everything else to the main site:
rewrittenUrl.pathname = `/makereal.tldraw.com${rewrittenUrl.pathname}`
}
Expand Down