refactor: generate code viewer

This commit is contained in:
jialin
2024-12-09 15:28:18 +08:00
parent a76560c38a
commit acf99a6a9e
20 changed files with 490 additions and 1708 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 658 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 644 KiB

@@ -145,7 +145,7 @@ const SpeechItem: React.FC<SpeechContentProps> = (props) => {
<div className="speech-item">
<div
className="wrapper"
style={{ height: 82, width: '100%' }}
style={{ height: 120, width: '100%' }}
ref={wrapper}
>
<AudioPlayer
@@ -164,7 +164,7 @@ const SpeechItem: React.FC<SpeechContentProps> = (props) => {
maxBarCount={100}
amplitude={60}
fixedHeight={true}
height={82}
height={120}
width={800}
analyserData={audioChunks}
></AudioAnimation>
@@ -31,14 +31,14 @@ import {
} from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import { handleEmbedding } from '../apis';
import { OpenAIViewCode } from '../config';
import { ParamsSchema } from '../config/types';
import '../style/ground-left.less';
import '../style/rerank.less';
import { generateEmbeddingCode } from '../view-code/embedding';
import DynamicParams from './dynamic-params';
import FileList from './file-list';
import InputList from './input-list';
import ViewCodeModal from './view-code-modal';
import ViewCommonCode from './view-common-code';
interface MessageProps {
modelList: Global.BaseOption<string>[];
@@ -123,6 +123,19 @@ const GroundEmbedding: React.FC<MessageProps> = forwardRef((props, ref) => {
};
});
const viewCodeContent = useMemo(() => {
return generateEmbeddingCode({
api: '/v1-openai/embeddings',
parameters: {
...parameters,
input: [
...textList.map((item) => item.text).filter((item) => item),
...fileList.map((item) => item.text).filter((item) => item)
]
}
});
}, [parameters, textList, fileList]);
const inputEmpty = useMemo(() => {
const list = [...textList, ...fileList];
return list.length < 2;
@@ -660,22 +673,12 @@ const GroundEmbedding: React.FC<MessageProps> = forwardRef((props, ref) => {
/>
</div>
</div>
<ViewCodeModal
{...OpenAIViewCode.embeddings}
<ViewCommonCode
open={show}
payload={{
input: [
...textList.map((item) => item.text).filter((item) => item),
...fileList.map((item) => item.text).filter((item) => item)
]
}}
parameters={{
...parameters
}}
viewCodeContent={viewCodeContent}
onCancel={handleCloseViewCode}
title={intl.formatMessage({ id: 'playground.viewcode' })}
></ViewCodeModal>
></ViewCommonCode>
</div>
);
});
@@ -26,7 +26,7 @@ import React, {
useState
} from 'react';
import { CREAT_IMAGE_API } from '../apis';
import { OpenAIViewCode, promptList } from '../config';
import { promptList } from '../config';
import {
ImageAdvancedParamsConfig,
ImageCustomSizeConfig,
@@ -36,9 +36,9 @@ import {
import { MessageItem, ParamsSchema } from '../config/types';
import '../style/ground-left.less';
import '../style/system-message-wrap.less';
import { generateImageCode, generateOpenaiImageCode } from '../view-code/image';
import DynamicParams from './dynamic-params';
import MessageInput from './message-input';
import ViewCodeModal from './view-code-modal';
import ViewCommonCode from './view-common-code';
interface MessageProps {
@@ -165,6 +165,25 @@ const GroundImages: React.FC<MessageProps> = forwardRef((props, ref) => {
};
}, [parameters]);
const viewCodeContent = useMemo(() => {
if (isOpenaiCompatible) {
return generateOpenaiImageCode({
api: '/v1-openai/images/generations',
parameters: {
...finalParameters,
prompt: currentPrompt
}
});
}
return generateImageCode({
api: '/v1-openai/images/generations',
parameters: {
...finalParameters,
prompt: currentPrompt
}
});
}, [finalParameters, currentPrompt, parameters.size]);
const setMessageId = () => {
messageId.current = messageId.current + 1;
return messageId.current;
@@ -603,34 +622,12 @@ const GroundImages: React.FC<MessageProps> = forwardRef((props, ref) => {
/>
</div>
</div>
{isOpenaiCompatible ? (
<ViewCodeModal
{...OpenAIViewCode.images}
open={show}
payload={{
prompt: currentPrompt
}}
parameters={{
...finalParameters
}}
onCancel={handleCloseViewCode}
title={intl.formatMessage({ id: 'playground.viewcode' })}
></ViewCodeModal>
) : (
<ViewCommonCode
{...OpenAIViewCode.imageAdvanced}
open={show}
payload={{
prompt: currentPrompt
}}
parameters={{
...finalParameters
}}
onCancel={handleCloseViewCode}
title={intl.formatMessage({ id: 'playground.viewcode' })}
></ViewCommonCode>
)}
<ViewCommonCode
open={show}
viewCodeContent={viewCodeContent}
onCancel={handleCloseViewCode}
title={intl.formatMessage({ id: 'playground.viewcode' })}
></ViewCommonCode>
</div>
);
});
@@ -19,16 +19,17 @@ import {
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState
} from 'react';
import { useHotkeys } from 'react-hotkeys-hook';
import { rerankerQuery } from '../apis';
import { OpenAIViewCode } from '../config';
import { MessageItem, ParamsSchema } from '../config/types';
import '../style/ground-left.less';
import '../style/rerank.less';
import '../style/system-message-wrap.less';
import { generateRerankCode } from '../view-code/rerank';
import DynamicParams from './dynamic-params';
import InputList from './input-list';
import ViewCommonCode from './view-common-code';
@@ -122,7 +123,7 @@ const GroundReranker: React.FC<MessageProps> = forwardRef((props, ref) => {
}
]);
const [sortIndexMap, setSortIndexMap] = useState<number[]>([]);
const queryValueRef = useRef<string>('');
const [queryValue, setQueryValue] = useState<string>('');
const { initialize, updateScrollerPosition: updateDocumentScrollerPosition } =
useOverlayScroller();
@@ -140,6 +141,19 @@ const GroundReranker: React.FC<MessageProps> = forwardRef((props, ref) => {
};
});
const viewCodeContent = useMemo(() => {
return generateRerankCode({
api: '/v1/rerank',
parameters: {
...parameters,
query: queryValue,
documents: [...textList, ...fileList]
.map((item) => item.text)
.filter((text) => text)
}
});
}, [parameters, queryValue, textList, fileList]);
// [0.1, 1.0]
const normalizValue = (data: { min: number; max: number; value: number }) => {
const range = [0.5, 1.0];
@@ -222,7 +236,7 @@ const GroundReranker: React.FC<MessageProps> = forwardRef((props, ref) => {
{
model: parameters.model,
top_n: parameters.top_n,
query: queryValueRef.current,
query: queryValue,
documents: [
...textList.map((item) => item.text),
...fileList.map((item) => item.text)
@@ -312,7 +326,7 @@ const GroundReranker: React.FC<MessageProps> = forwardRef((props, ref) => {
};
const handleQueryChange = (e: any) => {
queryValueRef.current = e.target.value;
setQueryValue(e.target.value);
};
const handleCloseViewCode = () => {
@@ -420,7 +434,7 @@ const GroundReranker: React.FC<MessageProps> = forwardRef((props, ref) => {
HotKeys.SUBMIT,
(e: any) => {
e.preventDefault();
handleSearch(queryValueRef.current);
handleSearch(queryValue);
},
{
enabled: !loading,
@@ -601,19 +615,9 @@ const GroundReranker: React.FC<MessageProps> = forwardRef((props, ref) => {
/>
</div>
</div>
<ViewCommonCode
{...OpenAIViewCode.rerank}
open={show}
payload={{
documents: [...textList, ...fileList]
.map((item) => item.text)
.filter((text) => text)
}}
parameters={{
...parameters,
query: queryValueRef.current
}}
viewCodeContent={viewCodeContent}
onCancel={handleCloseViewCode}
title={intl.formatMessage({ id: 'playground.viewcode' })}
></ViewCommonCode>
+15 -8
View File
@@ -18,6 +18,7 @@ import {
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState
} from 'react';
@@ -26,9 +27,10 @@ import { RealtimeParamsConfig as paramsConfig } from '../config/params-config';
import '../style/ground-left.less';
import '../style/speech-to-text.less';
import '../style/system-message-wrap.less';
import { speechToTextCode } from '../view-code/audio';
import AudioInput from './audio-input';
import DynamicParams from './dynamic-params';
import ViewSTTCode from './view-stt-code';
import ViewCommonCode from './view-common-code';
interface MessageProps {
modelList: Global.BaseOption<string>[];
@@ -89,6 +91,15 @@ const GroundLeft: React.FC<MessageProps> = forwardRef((props, ref) => {
messageId.current = messageId.current + 1;
};
const viewCodeContent = useMemo(() => {
return speechToTextCode({
api: '/v1-openai/audio/transcriptions',
parameters: {
...parameters
}
});
}, [parameters]);
const handleStopConversation = () => {
cancelRequest();
setLoading(false);
@@ -449,16 +460,12 @@ const GroundLeft: React.FC<MessageProps> = forwardRef((props, ref) => {
/>
</div>
</div>
<ViewSTTCode
<ViewCommonCode
open={show}
payload={{}}
api="audio/transcriptions"
clientType="audio.transcriptions.create"
parameters={parameters}
viewCodeContent={viewCodeContent}
onCancel={handleCloseViewCode}
title={intl.formatMessage({ id: 'playground.viewcode' })}
></ViewSTTCode>
></ViewCommonCode>
</div>
);
});
+15 -10
View File
@@ -24,9 +24,10 @@ import { TTSParamsConfig as paramsConfig } from '../config/params-config';
import { MessageItem, ParamsSchema } from '../config/types';
import '../style/ground-left.less';
import '../style/system-message-wrap.less';
import { TextToSpeechCode } from '../view-code/audio';
import DynamicParams from './dynamic-params';
import MessageInput from './message-input';
import ViewTTSCode from './view-tts-code';
import ViewCommonCode from './view-common-code';
interface MessageProps {
modelList: Global.BaseOption<string>[];
@@ -92,6 +93,16 @@ const GroundLeft: React.FC<MessageProps> = forwardRef((props, ref) => {
};
});
const viewCodeContent = useMemo(() => {
return TextToSpeechCode({
api: '/v1-openai/audio/speech',
parameters: {
...parameters,
input: currentPrompt
}
});
}, [parameters, currentPrompt]);
const sortVoiceList = useCallback(
(locale: string, voiceDataList: Global.BaseOption<string>[]) => {
const lang = locale === 'en-US' ? 'english' : 'chinese';
@@ -449,18 +460,12 @@ const GroundLeft: React.FC<MessageProps> = forwardRef((props, ref) => {
/>
</div>
</div>
<ViewTTSCode
<ViewCommonCode
open={show}
payload={{
input: currentPrompt
}}
api="audio/speech"
clientType="audio.speech.create"
parameters={parameters}
viewCodeContent={viewCodeContent}
onCancel={handleCloseViewCode}
title={intl.formatMessage({ id: 'playground.viewcode' })}
></ViewTTSCode>
></ViewCommonCode>
</div>
);
});
@@ -3,15 +3,16 @@ import HighlightCode from '@/components/highlight-code';
import { BulbOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Button, Modal } from 'antd';
import React, { useEffect, useState } from 'react';
import React, { useMemo, useState } from 'react';
type ViewModalProps = {
parameters: any;
title: string;
open: boolean;
api: string;
payload?: Record<string, any>;
logcommand: Record<string, any>;
viewCodeContent: {
curlCode: string;
pythonCode: string;
nodeJsCode: string;
};
onCancel: () => void;
};
@@ -24,61 +25,27 @@ const langMap = {
const langOptions = [
{ label: 'Curl', value: langMap.shell },
{ label: 'Python', value: langMap.python },
{ label: 'JavaScript', value: langMap.javascript }
{ label: 'Nodejs', value: langMap.javascript }
];
const ViewCodeModal: React.FC<ViewModalProps> = (props) => {
const {
title,
open,
onCancel,
payload,
parameters = {},
api,
logcommand
} = props || {};
const { title, open, onCancel, viewCodeContent } = props || {};
const intl = useIntl();
const [codeValue, setCodeValue] = useState('');
const [lang, setLang] = useState(langMap.shell);
const BaseURL = `${window.location.origin}${api}`;
const generateCode = () => {
const codeValue = useMemo(() => {
if (lang === langMap.shell) {
const code = `curl ${window.location.origin}${api} \\\n-H "Content-Type: application/json" \\\n-H "Authorization: Bearer $\{YOUR_GPUSTACK_API_KEY}" \\\n-d '${JSON.stringify(
{
...parameters,
...payload
},
null,
2
)}'`;
setCodeValue(code);
} else if (lang === langMap.javascript) {
const data = {
...parameters,
...payload
};
const headers = {
'Content-type': 'application/json',
Authorization: `Bearer $\{YOUR_GPUSTACK_API_KEY}`
};
const code = `import axios from 'axios';\n\nconst url = "${BaseURL}";\n\nconst headers = ${JSON.stringify(headers, null, 2)};\n\nconst data = ${JSON.stringify(data, null, 2)};\n\naxios.post(url, data, { headers }).then((response) => {\n console.log(response.${logcommand.node});\n});`;
setCodeValue(code);
} else if (lang === langMap.python) {
let data = {
...parameters,
...payload
};
const headers = {
'Content-type': 'application/json',
Authorization: `Bearer $\{YOUR_GPUSTACK_API_KEY}`
};
const code = `import requests\n\nurl="${BaseURL}"\n\nheaders = ${JSON.stringify(headers, null, 2)}\n\ndata=${JSON.stringify(data, null, 2).replace(/null/g, 'None')}\n\nresponse = requests.post(url, headers=headers, json=data)\n\nprint(response.${logcommand.python})`;
setCodeValue(code);
return viewCodeContent?.curlCode;
}
};
if (lang === langMap.javascript) {
return viewCodeContent?.nodeJsCode;
}
if (lang === langMap.python) {
return viewCodeContent?.pythonCode;
}
return '';
}, [lang, viewCodeContent]);
const handleOnChangeLang = (value: string) => {
setLang(value);
@@ -89,10 +56,6 @@ const ViewCodeModal: React.FC<ViewModalProps> = (props) => {
onCancel();
};
useEffect(() => {
generateCode();
}, [lang, parameters, payload]);
return (
<>
<Modal
@@ -123,13 +86,20 @@ const ViewCodeModal: React.FC<ViewModalProps> = (props) => {
}
}}
>
<HighlightCode
height={380}
theme="dark"
code={codeValue}
lang={lang}
copyable={false}
></HighlightCode>
<div
style={{
paddingRight: 2,
paddingBottom: 2
}}
>
<HighlightCode
height={380}
theme="dark"
code={codeValue}
lang={lang}
copyable={false}
></HighlightCode>
</div>
</EditorWrap>
<div
style={{ marginTop: 10, display: 'flex', alignItems: 'baseline' }}
@@ -165,4 +135,4 @@ const ViewCodeModal: React.FC<ViewModalProps> = (props) => {
);
};
export default ViewCodeModal;
export default React.memo(ViewCodeModal);
@@ -1,201 +0,0 @@
import EditorWrap from '@/components/editor-wrap';
import HighlightCode from '@/components/highlight-code';
import { BulbOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Button, Modal } from 'antd';
import _ from 'lodash';
import React, { useMemo, useState } from 'react';
type ViewModalProps = {
systemMessage?: string;
messageList?: any[];
payload: Record<string, any>;
parameters: any;
title: string;
api: string;
clientType: string;
logcommand?: string;
open: boolean;
onCancel: () => void;
};
const langMap = {
shell: 'bash',
python: 'python',
javascript: 'javascript'
};
const langOptions = [
{ label: 'Curl', value: langMap.shell },
{ label: 'Python', value: langMap.python },
{ label: 'Nodejs', value: langMap.javascript }
];
const ViewCodeModal: React.FC<ViewModalProps> = (props) => {
const {
title,
open,
api,
clientType,
logcommand,
onCancel,
payload,
parameters = {}
} = props || {};
const intl = useIntl();
const [lang, setLang] = useState(langMap.shell);
const BaseURL = `${window.location.origin}/v1-openai`;
const formatPyParams = (params: any) => {
return _.keys(params).reduce((acc: string, key: string) => {
if (params[key] === null) {
return acc;
}
const value =
typeof params[key] === 'object'
? JSON.stringify(params[key], null, 2)
: `"${params[key]}"`;
return acc + ` ${key}=${value},\n`;
}, ' file=audio_file\n');
};
const codeValue = useMemo(() => {
const consoleLog = `console.log(response.text);\n`;
const printLog = logcommand ? `print(response.${logcommand})` : '';
if (lang === langMap.shell) {
const code = `curl ${window.location.origin}/v1-openai/${api} \\\n-H "Content-Type: multipart/form-data" \\\n-H "Authorization: Bearer $\{YOUR_GPUSTACK_API_KEY}" \\\n-F file="@/path/to/file/audio.mp3;type=audio/mpeg" \\\n-F model="${parameters.model}" \\\n-F language="${parameters.language}"`;
return code;
}
if (lang === langMap.javascript) {
const paramStr = JSON.stringify(
{
...parameters,
...payload,
file: `fs.createReadStream(audio.mp3)`
},
null,
4
);
const params = paramStr.replace(
/"fs.createReadStream\(audio.mp3\)"/g,
'fs.createReadStream("audio.mp3")'
);
const code = `const fs = require("fs")\nconst OpenAI = require("openai");\n\nconst openai = new OpenAI({\n "apiKey": "YOUR_GPUSTACK_API_KEY",\n "baseURL": "${BaseURL}"\n});\n\nasync function main(){\n const params = ${params};\nconst response = await openai.${clientType}(params);\n ${consoleLog}}\nmain();`;
return code;
}
if (lang === langMap.python) {
const formattedParams = _.keys(parameters).reduce(
(acc: string, key: string) => {
if (parameters[key] === null) {
return acc;
}
const value =
typeof parameters[key] === 'string'
? `"${parameters[key]}"`
: parameters[key];
return acc + ` ${key}=${value},\n`;
},
''
);
const params = formatPyParams(payload);
const code = `from openai import OpenAI\n\naudio_file = open("audio.mp3", "rb")\nclient = OpenAI(\n base_url="${BaseURL}", \n api_key="YOUR_GPUSTACK_API_KEY"\n)\n\nresponse = client.${clientType}(\n${formattedParams}${params})\nprint('response:', response.text)`;
return code;
}
return '';
}, [lang, payload, parameters, api, clientType, logcommand]);
const handleOnChangeLang = (value: string) => {
setLang(value);
};
const handleClose = () => {
setLang(langMap.shell);
onCancel();
};
return (
<>
<Modal
title={title}
open={open}
centered={true}
onCancel={handleClose}
destroyOnClose={true}
closeIcon={true}
maskClosable={false}
keyboard={false}
width={600}
footer={null}
>
<div style={{ marginBottom: '10px' }}>
{intl.formatMessage({ id: 'playground.viewcode.info' })}
</div>
<div>
<EditorWrap
copyText={codeValue}
langOptions={langOptions}
defaultValue={langMap.shell}
showHeader={true}
onChangeLang={handleOnChangeLang}
styles={{
wrapper: {
backgroundColor: 'var(--color-editor-dark)'
}
}}
>
<div
style={{
paddingRight: 2,
paddingBottom: 2
}}
>
<HighlightCode
height={380}
theme="dark"
code={codeValue}
lang={lang}
copyable={false}
></HighlightCode>
</div>
</EditorWrap>
<div
style={{ marginTop: 10, display: 'flex', alignItems: 'baseline' }}
>
<BulbOutlined className="m-r-8" />
<span>
{intl.formatMessage(
{ id: 'playground.viewcode.tips' },
{
here: (
<Button
type="link"
size="small"
href="#/api-keys"
target="_blank"
style={{ paddingInline: 2 }}
>
<span>
{' '}
{intl.formatMessage({
id: 'playground.viewcode.here'
})}
</span>
</Button>
)
}
)}
</span>
</div>
</div>
</Modal>
</>
);
};
export default React.memo(ViewCodeModal);
@@ -1,207 +0,0 @@
import EditorWrap from '@/components/editor-wrap';
import HighlightCode from '@/components/highlight-code';
import { BulbOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Button, Modal } from 'antd';
import _ from 'lodash';
import React, { useMemo, useState } from 'react';
type ViewModalProps = {
systemMessage?: string;
messageList?: any[];
payload: Record<string, any>;
parameters: any;
title: string;
api: string;
clientType: string;
logcommand?: string;
open: boolean;
onCancel: () => void;
};
const langMap = {
shell: 'bash',
python: 'python',
javascript: 'javascript'
};
const langOptions = [
{ label: 'Curl', value: langMap.shell },
{ label: 'Python', value: langMap.python },
{ label: 'Nodejs', value: langMap.javascript }
];
const ViewCodeModal: React.FC<ViewModalProps> = (props) => {
const {
title,
open,
api,
clientType,
logcommand,
onCancel,
payload,
parameters = {}
} = props || {};
const intl = useIntl();
const [lang, setLang] = useState(langMap.shell);
const BaseURL = `${window.location.origin}/v1-openai`;
const formatPyParams = (params: any) => {
return _.keys(params).reduce((acc: string, key: string) => {
if (params[key] === null) {
return acc;
}
const value =
typeof params[key] === 'object'
? JSON.stringify(params[key], null, 2)
: `"${params[key]}"`;
return acc + ` ${key}=${value},\n`;
}, '');
};
const codeValue = useMemo(() => {
const consoleLog = logcommand
? `console.log(response.${logcommand});`
: `console.log(ouptFile);\n const buffer = Buffer.from(await response.arrayBuffer());\n await fs.promises.writeFile(ouptFile, buffer);\n`;
const printLog = logcommand ? `print(response.${logcommand})` : '';
if (lang === langMap.shell) {
const code = `curl ${window.location.origin}/v1-openai/${api} \\\n-H "Content-Type: application/json" \\\n-H "Authorization: Bearer $\{YOUR_GPUSTACK_API_KEY}" \\\n-d '${JSON.stringify(
{
...parameters,
...payload
},
null,
2
)}' \\\n--output output.${parameters.response_format}`;
return code;
}
if (lang === langMap.javascript) {
const code = `const fs = require("fs");\nconst path = require("path");\nconst OpenAI = require("openai");\n\nconst ouptFile = path.resolve("./output.${parameters.response_format}");\n\nconst openai = new OpenAI({\n "apiKey": "YOUR_GPUSTACK_API_KEY",\n "baseURL": "${BaseURL}"\n});\n\nasync function main(){\n const params = ${JSON.stringify(
{
...parameters,
...payload
},
null,
4
)};\nconst response = await openai.${clientType}(params);\n ${consoleLog}}\nmain();`;
return code;
}
if (lang === langMap.python) {
const formattedParams = _.keys(parameters).reduce(
(acc: string, key: string) => {
if (parameters[key] === null) {
return acc;
}
const value =
typeof parameters[key] === 'string'
? `"${parameters[key]}"`
: parameters[key];
return acc + ` ${key}=${value},\n`;
},
''
);
const params = formatPyParams(payload);
const code = `from pathlib import Path\nfrom openai import OpenAI\n\nclient = OpenAI(\n base_url="${BaseURL}", \n api_key="YOUR_GPUSTACK_API_KEY"\n)\n\noutput_file_path = Path(__file__).parent / "output.${parameters.response_format}"\nresponse = client.${clientType}(\n${formattedParams}${params})\n${printLog}\nwith open(output_file_path, "wb") as f:
for chunk in response.iter_bytes():
f.write(chunk)
print(f"Audio saved to {output_file_path}")`;
return code;
}
return '';
}, [lang, payload, parameters, api, clientType, logcommand]);
const handleOnChangeLang = (value: string) => {
setLang(value);
};
const handleClose = () => {
setLang(langMap.shell);
onCancel();
};
return (
<>
<Modal
title={title}
open={open}
centered={true}
onCancel={handleClose}
destroyOnClose={true}
closeIcon={true}
maskClosable={false}
keyboard={false}
width={600}
footer={null}
>
<div style={{ marginBottom: '10px' }}>
{intl.formatMessage({ id: 'playground.viewcode.info' })}
</div>
<div>
<EditorWrap
copyText={codeValue}
langOptions={langOptions}
defaultValue={langMap.shell}
showHeader={true}
onChangeLang={handleOnChangeLang}
styles={{
wrapper: {
backgroundColor: 'var(--color-editor-dark)'
}
}}
>
<div
style={{
paddingRight: 2,
paddingBottom: 2
}}
>
<HighlightCode
height={380}
theme="dark"
code={codeValue}
lang={lang}
copyable={false}
></HighlightCode>
</div>
</EditorWrap>
<div
style={{ marginTop: 10, display: 'flex', alignItems: 'baseline' }}
>
<BulbOutlined className="m-r-8" />
<span>
{intl.formatMessage(
{ id: 'playground.viewcode.tips' },
{
here: (
<Button
type="link"
size="small"
href="#/api-keys"
target="_blank"
style={{ paddingInline: 2 }}
>
<span>
{' '}
{intl.formatMessage({
id: 'playground.viewcode.here'
})}
</span>
</Button>
)
}
)}
</span>
</div>
</div>
</Modal>
</>
);
};
export default React.memo(ViewCodeModal);
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

-44
View File
@@ -1,44 +0,0 @@
// import Img01 from '@/assets/images/img_01.png';
import Img02 from '@/assets/images/img_02.png';
export default [
{
// dataUrl:
// 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
dataUrl: Img02,
height: 1024,
width: 512,
uid: 0,
span: 24,
loading: false,
progress: 30
}
// {
// // dataUrl:
// // 'https://gw.alipayobjects.com/zos/antfincdn/LlvErxo8H9/photo-1503185912284-5271ff81b9a8.webp',
// dataUrl: Img02,
// height: 1024,
// width: 512,
// uid: 1,
// span: 12,
// progress: 15
// }
// {
// dataUrl:
// 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
// height: 'auto',
// width: 'auto',
// uid: 3,
// span: 12,
// progress: 10
// },
// {
// dataUrl:
// 'https://gw.alipayobjects.com/zos/antfincdn/LlvErxo8H9/photo-1503185912284-5271ff81b9a8.webp',
// height: 'auto',
// width: 'auto',
// uid: 4,
// span: 12,
// progress: 15
// }
];
-61
View File
@@ -1,61 +0,0 @@
import _ from 'lodash';
const formatCurlArgs = (args: Record<string, any>, isFormdata?: boolean) => {
if (isFormdata) {
return _.keys(args).reduce((acc: string, key: string) => {
const value = args[key];
return acc + `-F ${key}="${value}" \\\n`;
}, '');
}
return `-d "${JSON.stringify(args)}" \\\n`;
};
const formatPyParams = (params: Record<string, any>) => {};
export const speechToTextCode = ({
payload,
api,
parameters
}: Record<string, any>) => {
const host = window.location.origin;
const curlCode = `curl ${host}}${api} \
-H "Content-Type: multipart/form-data" \
-H "Authorization: Bearer $\{YOUR_GPUSTACK_API_KEY}" \
-F file="@/path/to/file/audio.mp3;type=audio/mpeg" \
-F model="${parameters.model}" \
-F language="${parameters.language}"`;
const pythonCode = `from openai import OpenAI
audio_file = open("audio.mp3", "rb")
client = OpenAI(
base_url="${host}/v1-openai",
api_key="YOUR_GPUSTACK_API_KEY"
)
response = client.audio.transcriptions.create(
model="${parameters.model}",
language="${parameters.language}",
file=audio_file
)
print('response:', response.text)`;
const nodeJsCode = `const fs = require("fs")
const OpenAI = require("openai");
const openai = new OpenAI({
"apiKey": "YOUR_GPUSTACK_API_KEY",
"baseURL": "${host}/v1-openai"
});
async function main(){
const params = {
"model": "faster-whisper-large-v3",
"language": "auto",
"file": fs.createReadStream("audio.mp3")
};
const response = await openai.audio.transcriptions.create(params);
console.log(response.text);
}
main();`;
};
+122
View File
@@ -0,0 +1,122 @@
import { fomatNodeJsParams, formatCurlArgs, formatPyParams } from './utils';
export const speechToTextCode = ({ api, parameters }: Record<string, any>) => {
const host = window.location.origin;
// ========================= Curl =========================
const curlCode = `
curl ${host}${api} \\
-H "Content-Type: multipart/form-data" \\
-H "Authorization: Bearer $\{YOUR_GPUSTACK_API_KEY}" \\
-F file="@/path/to/file/audio.mp3;type=audio/mpeg" \\
${formatCurlArgs(parameters, true)}`
.trim()
.replace(/\\$/g, '');
// ========================= Python =========================
const pythonCode = `
from openai import OpenAI\n
audio_file = open("audio.mp3", "rb")
client = OpenAI(
base_url="${host}/v1-openai",
api_key="YOUR_GPUSTACK_API_KEY"
)
response = client.audio.transcriptions.create(\n${formatPyParams({
...parameters,
file: 'audio_file'
}).replace(/"audio_file"/, 'audio_file')})\n
print('response:', response.text)`.trim();
// ========================= Node.js =========================
const jsonParams = fomatNodeJsParams({
...parameters,
file: `fs.createReadStream(audio.mp3)`
});
const params = jsonParams.replace(
/"fs.createReadStream\(audio.mp3\)"/g,
'fs.createReadStream("audio.mp3")'
);
const nodeJsCode = `
const fs = require("fs")
const OpenAI = require("openai");
const openai = new OpenAI({
"apiKey": "YOUR_GPUSTACK_API_KEY",
"baseURL": "${host}/v1-openai"
});
async function main() {
const params = ${params};
const response = await openai.audio.transcriptions.create(params);
console.log(response.text);
}
main();`.trim();
return {
curlCode,
pythonCode,
nodeJsCode
};
};
export const TextToSpeechCode = ({ api, parameters }: Record<string, any>) => {
const host = window.location.origin;
// ========================= Curl =========================
const curlCode = `
curl ${host}${api} \\
-H "Content-Type: multipart/form-data" \\
-H "Authorization: Bearer $\{YOUR_GPUSTACK_API_KEY}" \\
${formatCurlArgs(parameters, false)} \\\n--output output.${parameters.response_format}`.trim();
// ========================= Python =========================
const pythonCode = `
from pathlib import Path
from openai import OpenAI\n
output_file_path = Path(__file__).parent / "output.mp3"
client = OpenAI(
base_url="${host}/v1-openai",
api_key="YOUR_GPUSTACK_API_KEY"
)
response = client.audio.speech.create(\n${formatPyParams({ ...parameters })})\n
with open(output_file_path, "wb") as f:
for chunk in response.iter_bytes():
f.write(chunk)
print(f"Audio saved to {output_file_path}")`.trim();
// ========================= Node.js =========================
const params = fomatNodeJsParams({
...parameters
});
const nodeJsCode = `
const fs = require("fs");
const path = require("path");
const OpenAI = require("openai");
const ouptFile = path.resolve("./output.mp3");
const openai = new OpenAI({
"apiKey": "YOUR_GPUSTACK_API_KEY",
"baseURL": "${host}/v1-openai"
});
async function main() {
const params = ${params};
const response = await openai.audio.speech.create(params);
console.log(ouptFile);
const buffer = Buffer.from(await response.arrayBuffer());
await fs.promises.writeFile(ouptFile, buffer);
}
main();`.trim();
return {
curlCode,
pythonCode,
nodeJsCode
};
};
@@ -0,0 +1,52 @@
import { fomatNodeJsParams, formatCurlArgs, formatPyParams } from './utils';
export const generateEmbeddingCode = ({
api,
parameters
}: Record<string, any>) => {
const host = window.location.origin;
// ========================= Curl =========================
const curlCode = `
curl ${host}${api} \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer $\{YOUR_GPUSTACK_API_KEY}" \\
${formatCurlArgs(parameters, false)}`.trim();
// ========================= Python =========================
const pythonCode = `
from openai import OpenAI\n
client = OpenAI(
base_url="${host}/v1-openai",
api_key="YOUR_GPUSTACK_API_KEY"
)
response = client.embeddings.create(\n${formatPyParams({ ...parameters })})\n
print(response.data[0].embedding)`.trim();
// ========================= Node.js =========================
const params = fomatNodeJsParams({
...parameters
});
const nodeJsCode = `
const OpenAI = require("openai");
const openai = new OpenAI({
"apiKey": "YOUR_GPUSTACK_API_KEY",
"baseURL": "${host}/v1-openai"
});
async function main() {
const params = ${params};
const response = await openai.embeddings.create(params);
console.log(response.data[0].embedding);
}
main();`.trim();
return {
curlCode,
pythonCode,
nodeJsCode
};
};
+96
View File
@@ -0,0 +1,96 @@
import { fomatNodeJsParams, formatCurlArgs, formatPyParams } from './utils';
export const generateImageCode = ({ api, parameters }: Record<string, any>) => {
const host = window.location.origin;
// ========================= Curl =========================
const curlCode = `
curl ${host}${api} \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer $\{YOUR_GPUSTACK_API_KEY}" \\
${formatCurlArgs(parameters, false)}`.trim();
// ========================= Python =========================
const pythonCode = `
import requests\n
url="${host}${api}"
headers = {
"Content-type": "application/json",
"Authorization": "Bearer $\{YOUR_GPUSTACK_API_KEY}"
}
data = ${JSON.stringify(parameters, null, 2).replace(/null/g, 'None')}\n
response = requests.post(url, headers=headers, json=data)
print(response.json()['data'][0]['b64_json'])`.trim();
// ========================= Node.js =========================
const nodeJsCode = `
const axios = require('axios');
const url = "http://localhost/v1-openai/images/generations";
const headers = {
"Content-type": "application/json",
"Authorization": "Bearer $\{YOUR_GPUSTACK_API_KEY}"
};
const data = ${fomatNodeJsParams(parameters)};
axios.post(url, data, { headers }).then((response) => {
console.log(response.data.data[0].b64_json);
});`.trim();
return {
curlCode,
pythonCode,
nodeJsCode
};
};
export const generateOpenaiImageCode = ({
api,
parameters
}: Record<string, any>) => {
const host = window.location.origin;
// ========================= Curl =========================
const curlCode = `
curl ${host}${api} \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer $\{YOUR_GPUSTACK_API_KEY}" \\
${formatCurlArgs(parameters, false)}`.trim();
// ========================= Python =========================
const pythonCode = `
from openai import OpenAI\n
client = OpenAI(
base_url="${host}/v1-openai",
api_key="YOUR_GPUSTACK_API_KEY"
)
response = client.images.generate(\n${formatPyParams({ ...parameters })})\n
print(response.data[0].b64_json)`.trim();
// ========================= Node.js =========================
const params = fomatNodeJsParams({
...parameters
});
const nodeJsCode = `
const OpenAI = require("openai");
const openai = new OpenAI({
"apiKey": "YOUR_GPUSTACK_API_KEY",
"baseURL": "${host}/v1-openai"
});
async function main() {
const params = ${params};
const response = await openai.images.generate(params);
console.log(response.data[0].b64_json);
}
main();`.trim();
return {
curlCode,
pythonCode,
nodeJsCode
};
};
+48
View File
@@ -0,0 +1,48 @@
import { formatCurlArgs } from './utils';
export const generateRerankCode = ({
api,
parameters
}: Record<string, any>) => {
const host = window.location.origin;
// ========================= Curl =========================
const curlCode = `
curl ${host}${api} \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer $\{YOUR_GPUSTACK_API_KEY}" \\
${formatCurlArgs(parameters, false)}`.trim();
// ========================= Python =========================
const pythonCode = `
import requests\n
url="${host}${api}"
headers = {
"Content-type": "application/json",
"Authorization": "Bearer $\{YOUR_GPUSTACK_API_KEY}"
}
data = ${JSON.stringify(parameters, null, 2)}\n
response = requests.post(url, headers=headers, json=data)
print(response.json())`.trim();
// ========================= Node.js =========================
const nodeJsCode = `
const axios = require('axios');
const url = "${host}${api}";
const headers = {
"Content-type": "application/json",
"Authorization": "Bearer $\{YOUR_GPUSTACK_API_KEY}"
};
const data = ${JSON.stringify(parameters, null, 2)};
axios.post(url, data, { headers }).then((response) => {
console.log(response.data);
});`.trim();
return {
curlCode,
pythonCode,
nodeJsCode
};
};
+42
View File
@@ -0,0 +1,42 @@
import _ from 'lodash';
// curl format
export const formatCurlArgs = (
parameters: Record<string, any>,
isFormdata?: boolean
) => {
if (isFormdata) {
return _.keys(parameters).reduce((acc: string, key: string) => {
const val = parameters[key];
const value =
typeof val === 'object' ? JSON.stringify(val, null, 2) : `${val}`;
return acc + `-F ${key}="${value}" \\\n`;
}, '');
}
return `-d '${JSON.stringify(parameters, null, 2)}'`;
};
// python format
export const formatPyParams = (parameters: Record<string, any>) => {
return _.keys(parameters).reduce((acc: string, key: string) => {
if (parameters[key] === null || parameters[key] === undefined) {
return acc;
}
const value =
typeof parameters[key] === 'object'
? JSON.stringify(parameters[key], null, 2)
: `"${parameters[key]}"`;
return acc + ` ${key}=${value},\n`;
}, '');
};
// node format
export const fomatNodeJsParams = (parameters: Record<string, any>) => {
return JSON.stringify(
{
...parameters
},
null,
4
);
};