OpenAI的ChatGPT入门使用
ChatGPT,全称聊天生成预训练转换器[2](英语:Chat Generative Pre-trained Transformer[3]),是OpenAI开发的人工智能聊天机器人程序,于2022年12月推出。该程序使用基于GPT-3.5、GPT-4、GPT-4o架构的大型语言模型并以强化学习训练。ChatGPT目前仍以文字方式交互,而除了可以用人类自然对话方式来交互,还可以用于甚为复杂的语言工作,包括自动生成文本、自动问答、自动摘要等多种任务。
1 安装python
使用anaconda进行python版本的管理
2 获取api key
注册OpenAI账号,获取专属API Key 点击
3 使用 API 接口.
3.1 python
import openai
# 设置 API 密钥
openai.api_key = "YOUR_API_KEY"
# 发送请求
response = openai.Completion.create(
model="text-davinci-003", # 使用的模型版本
prompt="Hello, how are you?",
max_tokens=50
)
print(response.choices[0].text.strip())
使用 pip install openai 安装官方库
3.2 Go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ChatCompletionRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
User string `json:"user,omitempty"`
Stream bool `json:"stream,omitempty"`
Functions []interface{} `json:"functions,omitempty"`
}
type ChatCompletionResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Model string `json:"model"`
Choices []Choice `json:"choices"`
Usage Usage `json:"usage"`
}
type Choice struct {
Index int `json:"index"`
Message Message `json:"message"`
FinishReason string `json:"finish_reason"`
Delta Delta `json:"delta,omitempty"`
Functions []Function `json:"functions,omitempty"`
}
type Delta struct {
Role string `json:"role"`
Content string `json:"content"`
}
type Function struct {
Name string `json:"name"`
}
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}
func main() {
apiKey := "YOUR_API_KEY" // 替换为你的 API 密钥
url := "https://api.openai.com/v1/chat/completions"
messages := []Message{
{Role: "user", Content: "Hello!"},
{Role: "assistant", Content: "Hi there! How can I assist you today?"},
{Role: "user", Content: "What is the weather like in San Francisco today?"},
}
request := ChatCompletionRequest{
Model: "gpt-3.5-turbo",
Messages: messages,
}
jsonData, err := json.Marshal(request)
if err != nil {
fmt.Println("Error marshaling request:", err)
return
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error making request:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
var chatResp ChatCompletionResponse
err = json.Unmarshal(body, &chatResp)
if err != nil {
fmt.Println("Error unmarshaling response:", err)
return
}
for _, choice := range chatResp.Choices {
fmt.Printf("Response: %s\n", choice.Message.Content)
}
}
3.3 JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ChatGPT API Example</title>
</head>
<body>
<script>
async function fetchChatGPT(message) {
const apiKey = 'YOUR_API_KEY'; // 替换为你的 API 密钥
const url = 'https://api.openai.com/v1/chat/completions';
const data = {
model: 'gpt-3.5-turbo',
messages: [
{ role: 'user', content: message },
],
};
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.json();
console.log(result);
const assistantMessage = result.choices[0].message.content;
console.log('Assistant:', assistantMessage);
} catch (error) {
console.error('Error fetching ChatGPT API:', error);
}
}
// 调用函数
fetchChatGPT('What is the weather like in San Francisco today?');
</script>
</body>
</html>