智API:请求代码示例(多种语言)

使用技巧3个月前更新
32 0

在当今快速发展的技术世界中,应用程序接口(API)成为连接不同软件系统的重要工具。智API,以其智能化和高效能,正在改变开发人员与数据互动的方式。无论是初创公司还是大型企业,能够有效地调用和集成API,是在数字化时代中获得竞争优势的关键之一。然而,对于许多开发者而言,如何构建正确的API请求仍然是一项挑战。本文将通过提供一系列易于理解的代码示例,帮助开发者详细了解智API的使用方法及其在实际应用中的操作步骤。探索这些示例将使您能够轻松地掌握智API的精髓,推动您的项目开发进入新的高度。

流式与非流的修改

非流修改:
    "stream": false,
流式修改:
    "stream": true,

Curl请求代码示例

curl https://api.zhiapi.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-xxx" \
  -d '{
    "model": "gpt-3.5-turbo",
    "stream": false,
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "say 1"} 
    ]
  }'

Python (SDK)请求代码示例

from openai import OpenAI

client = OpenAI(api_key="sk-xxx", base_url="https://api.zhiapi.com/v1")

completion = client.chat.completions.create(
    model="gpt-3.5-turbo",
    stream=False,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "say 1"}
    ]
)

print(completion.choices[0].message)

Python (requests)请求代码示例

import requests
import json

url = "https://api.zhiapi.com/v1/chat/completions"
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer sk-xxx"
}
data = {
    "model": "gpt-3.5-turbo",
    "stream": False,
    "messages": [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "say 1"}
    ]
}

response = requests.post(url, headers=headers, json=data)

if response.status_code == 200:
    if False:
        for line in response.iter_lines():
            if line:
                chunk = json.loads(line.decode('utf-8'))
                if chunk['choices'][0].get('delta', {}).get('content'):
                    print(chunk['choices'][0]['delta']['content'], end='')
    else:
        print(response.json()['choices'][0]['message']['content'])
else:
    print(f"Error: {response.status_code}, {response.text}")

Node.js请求代码示例

import OpenAI from "openai";

const openai = new OpenAI({
    apiKey: "sk-xxx",
    baseURL: "https://api.zhiapi.com/v1"
});

async function main() {
    const completion = await openai.chat.completions.create({
        model: "gpt-3.5-turbo",
        stream: false,
        messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "say 1" }
        ]
    });

    console.log(completion.choices[0].message);
}

main();

Java请求代码示例

import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;

import java.util.Arrays;

public class OpenAIExample {
    public static void main(String[] args) {
        String token = "sk-xxx";
        OpenAiService service = new OpenAiService(token);

        ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
            .model("gpt-3.5-turbo")
            .messages(Arrays.asList(
                new ChatMessage("system", "You are a helpful assistant."),
                new ChatMessage("user", "say 1")
            ))
            .build();

        service.createChatCompletion(completionRequest).getChoices().forEach(choice -> {
            System.out.println(choice.getMessage().getContent());
        });
    }
}

C#请求代码示例

using OpenAI_API;
using OpenAI_API.Chat;

class Program
{
    static async Task Main(string[] args)
    {
        var api = new OpenAIAPI("sk-xxx");
        api.ApiBase = "https://api.zhiapi.com/v1";

        var chat = api.Chat.CreateConversation();
        chat.AppendSystemMessage("You are a helpful assistant.");
        chat.AppendUserInput("say 1");

        string response = await chat.GetResponseFromChatbotAsync();
        Console.WriteLine(response);
    }
}

Ruby请求代码示例

require 'openai'

client = OpenAI::Client.new(access_token: 'sk-xxx', uri_base: 'https://api.zhiapi.com/v1')

response = client.chat(
    parameters: {
        model: "gpt-3.5-turbo",
        messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "say 1" }
        ],
        stream: false
    }
)

puts response.dig("choices", 0, "message", "content")

Go请求代码示例

package main

import (
    "context"
    "fmt"
    "github.com/sashabaranov/go-openai"
)

func main() {
    client := openai.NewClient("sk-xxx")
    client.BaseURL = "https://api.zhiapi.com/v1"

    resp, err := client.CreateChatCompletion(
        context.Background(),
        openai.ChatCompletionRequest{
            Model: "gpt-3.5-turbo",
            Messages: []openai.ChatCompletionMessage{
                {
                    Role:    openai.ChatMessageRoleSystem,
                    Content: "You are a helpful assistant.",
                },
                {
                    Role:    openai.ChatMessageRoleUser,
                    Content: "say 1",
                },
            },
        },
    )

    if err != nil {
        fmt.Printf("ChatCompletion error: %v
", err)
        return
    }

    fmt.Println(resp.Choices[0].Message.Content)
}

PHP请求代码示例

<?php

require_once 'vendor/autoload.php';

$client = OpenAI::client('sk-xxx');

$result = $client->chat()->create([
    'model' => 'gpt-3.5-turbo',
    'messages' => [
        ['role' => 'system', 'content' => 'You are a helpful assistant.'],
        ['role' => 'user', 'content' => 'say 1'],
    ],
]);

echo $result->choices[0]->message->content;

Rust请求代码示例

use reqwest::Client;
use serde_json::{json, Value};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();
    let response = client.post("https://api.zhiapi.com/v1/chat/completions")
        .header("Authorization", "Bearer sk-xxx")
        .json(&json!({
            "model": "gpt-3.5-turbo",
            "messages": [
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": "say 1"}
            ]
        }))
        .send()
        .await?;

    let body: Value = response.json().await?;
    println!("{}", body["choices"][0]["message"]["content"]);

    Ok(())
}

C请求代码示例

#include <stdio.h>
#include <curl/curl.h>
#include <string.h>

size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) {
    printf("%.*s", (int)(size * nmemb), ptr);
    return size * nmemb;
}

int main(void) {
    CURL *curl;
    CURLcode res;
    struct curl_slist *headers = NULL;
    char *data = "{"
        ""model": "gpt-3.5-turbo","
        ""messages": ["
            "{"role": "system", "content": "You are a helpful assistant."},"
            "{"role": "user", "content": "say 1"}"
        "]"
    "}";

    curl = curl_easy_init();
    if(curl) {
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, "Authorization: Bearer sk-xxx");

        curl_easy_setopt(curl, CURLOPT_URL, "https://api.zhiapi.com/v1/chat/completions");
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

        res = curl_easy_perform(curl);
        if(res != CURLE_OK)
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));

        curl_easy_cleanup(curl);
        curl_slist_free_all(headers);
    }
    return 0;
}

C++请求代码示例

#include <iostream>
#include <curl/curl.h>
#include <string>

size_t WriteCallback(void *contents, size_t size, size_t nmemb, std::string *s) {
    size_t newLength = size * nmemb;
    s->append((char*)contents, newLength);
    return newLength;
}

int main() {
    CURL *curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if(curl) {
        std::string url = "https://api.zhiapi.com/v1/chat/completions";
        std::string data = R"({
            "model": "gpt-3.5-turbo",
            "messages": [
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": "say 1"}
            ]
        })";

        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, "Authorization: Bearer sk-xxx");

        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        res = curl_easy_perform(curl);
        curl_easy_cleanup(curl);

        if(res != CURLE_OK)
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        else
            std::cout << readBuffer << std::endl;
    }

    return 0;
}

Dart请求代码示例

import 'package:http/http.dart' as http;
import 'dart:convert';

void main() async {
  final url = Uri.parse('https://api.zhiapi.com/v1/chat/completions');
  final response = await http.post(
    url,
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer sk-xxx',
    },
    body: jsonEncode({
      'model': 'gpt-3.5-turbo',
      'messages': [
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': 'say 1'},
      ],
    }),
  );

  if (response.statusCode == 200) {
    final jsonResponse = jsonDecode(response.body);
    print(jsonResponse['choices'][0]['message']['content']);
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}

更多Python调用OpenAI API的教程可以去官网查看:https://platform.openai.com/docs/quickstart

© 版权声明

相关文章