美文网首页
简单接入OpenAI的聊天和文生图API

简单接入OpenAI的聊天和文生图API

作者: dequal | 来源:发表于2024-08-06 11:17 被阅读0次

    这里是一个简单的HTML示例,包含JavaScript代码,用于封装OpenAI的聊天接口和文生图接口。这个示例包括两个模式:聊天模式和文生图模式。聊天模式支持流式响应。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>OpenAI Chat and Text-to-Image Demo</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 20px;
            }
            #output {
                white-space: pre-wrap;
                border: 1px solid #ccc;
                padding: 10px;
                margin-top: 10px;
            }
            #image {
                margin-top: 10px;
            }
            #controls {
                margin-bottom: 10px;
            }
        </style>
    </head>
    <body>
        <h1>OpenAI Chat and Text-to-Image Demo</h1>
        <div id="controls">
            <select id="mode">
                <option value="chat">Chat</option>
                <option value="image">Text-to-Image</option>
            </select>
            <br>
            <textarea id="input" rows="4" cols="50" placeholder="Enter your prompt here..."></textarea>
            <br>
            <button onclick="handleRequest()">Submit</button>
        </div>
        <div id="output"></div>
        <img id="image" style="display:none;" alt="Generated Image">
        
        <script>
            async function handleRequest() {
                const mode = document.getElementById('mode').value;
                const input = document.getElementById('input').value;
    
                if (mode === 'chat') {
                    await handleChatRequest(input);
                } else if (mode === 'image') {
                    await handleImageRequest(input);
                }
            }
    
            async function handleChatRequest(prompt) {
        const outputDiv = document.getElementById('output');
        outputDiv.innerHTML = 'Loading...';
    
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer sk-g6o******a8T`
            },
            body: JSON.stringify({
                model: 'gpt-4',
                messages: [{ role: 'user', content: prompt }],
                stream: true
            })
        });
    
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        outputDiv.innerHTML = '';
    
        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            const text = decoder.decode(value, { stream: true });
            const lines = text.split('\n').filter(line => line.trim() !== '');
            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    const json = JSON.parse(line.substring(6));
                    if (json.choices && json.choices[0].delta && json.choices[0].delta.content) {
                        outputDiv.innerHTML += json.choices[0].delta.content;
                    }
                }
            }
        }
    }
    
            async function handleImageRequest(prompt) {
                const outputDiv = document.getElementById('output');
                const image = document.getElementById('image');
                outputDiv.innerHTML = 'Generating image...';
                image.style.display = 'none';
    
                const response = await fetch('https://api.openai.com/v1/images/generations', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer sk-g6o******a8T`
                    },
                    body: JSON.stringify({
                        prompt: prompt,
                        n: 1,
                        size: '512x512'
                    })
                });
    
                const data = await response.json();
                if (data.data && data.data.length > 0) {
                    outputDiv.innerHTML = 'Image generated:';
                    image.src = data.data[0].url;
                    image.style.display = 'block';
                } else {
                    outputDiv.innerHTML = 'Failed to generate image.';
                }
            }
        </script>
    </body>
    </html>
    
    

    相关文章

      网友评论

          本文标题:简单接入OpenAI的聊天和文生图API

          本文链接:https://www.haomeiwen.com/subject/pmmfkjtx.html