多语言调用示例
任何能发 HTTP 请求的语言都可以调用。只有 Python 和 Node.js 有 OpenAI 和 Anthropic 的官方 SDK,其他语言直接按 HTTP 接口调用,请求头、请求体、返回格式都是一样的。
下面以 deepseek-flash 为例,完整代码可以在模型广场对应模型的「接口接入」里按语言生成。
Go
go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
body, _ := json.Marshal(map[string]any{
"model": "deepseek-flash",
"messages": []map[string]string{
{"role": "user", "content": "你好"},
},
})
req, _ := http.NewRequest("POST", "https://gateway.hihapi.com/v1/chat/completions", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("HIHAI_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
fmt.Println("请求失败:", resp.StatusCode, string(data))
return
}
var result struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
json.Unmarshal(data, &result)
fmt.Println(result.Choices[0].Message.Content)
}Java
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "deepseek-flash",
"messages": [{"role": "user", "content": "你好"}]
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://gateway.hihapi.com/v1/chat/completions"))
.header("Authorization", "Bearer " + System.getenv("HIHAI_API_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}PHP
php
<?php
$payload = json_encode([
'model' => 'deepseek-flash',
'messages' => [['role' => 'user', 'content' => '你好']],
]);
$ch = curl_init('https://gateway.hihapi.com/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('HIHAI_API_KEY'),
'Content-Type: application/json',
],
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
echo $data['choices'][0]['message']['content'];C#
csharp
using System.Net.Http.Headers;
using System.Text;
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("HIHAI_API_KEY"));
var body = """
{ "model": "deepseek-flash", "messages": [ { "role": "user", "content": "你好" } ] }
""";
var content = new StringContent(body, Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://gateway.hihapi.com/v1/chat/completions", content);
Console.WriteLine(await response.Content.ReadAsStringAsync());Ruby
ruby
require 'net/http'
require 'json'
uri = URI('https://gateway.hihapi.com/v1/chat/completions')
request = Net::HTTP::Post.new(uri)
request['Authorization'] = "Bearer #{ENV['HIHAI_API_KEY']}"
request['Content-Type'] = 'application/json'
request.body = {
model: 'deepseek-flash',
messages: [{ role: 'user', content: '你好' }]
}.to_json
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
puts JSON.parse(response.body).dig('choices', 0, 'message', 'content')流式输出
其他语言的流式处理和 Node.js 一样,按行读取 SSE:每个 data: 开头的行为一个 JSON 数据块,读到 data: [DONE] 结束。��意关闭 HTTP 客户端的响应缓冲,否则内容会攒到最后一起返回。
错误处理
所有语言的错误格式一致,按响应体的 reason 判断:
json
{ "code": 100002, "reason": "COMMON_UNAUTHENTICATED", "message": "Authentication failed", "request_id": "..." }只在 reason 属于可重试的类型时才重试,见错误码。
SDK 和框架
Python、Node.js 用 OpenAI 或 Anthropic 的官方 SDK 最省事。LangChain、LlamaIndex、Dify、Spring AI 这类框架都支持自定义 OpenAI 兼容地址,把接口地址设为 https://gateway.hihapi.com/v1,填上令牌密钥和模型 ID 即可。