UIUIAPI聚合平台API通用代码教程
API 站点使用教程
API快速使用工具推荐 🔥
1.1 API 接口地址填写
请勿将 API Key 泄露给他人,一旦泄露,请立即删除并创建新的 API Key
修改原则:修改应用 BASE_URL 为其中一个中转接口调用地址接口即可,例如:
修改原则
https://api.openai.com
↓
https://sg.uiuiapi.com
(如果原来接口地址需要加 /v1 的话我们的接口地址也需要在后面加 /v1)
出现回复缓慢的情况,请检查 API 调用日志,若日志正常,则自行调整网络。
Base Url
不同客户端适配的接口地址格式不同,通常为以下三种:
1.2 Python 接入示例
所有对话模型均使用 OpenAI 格式,替换AI模型即可
Python 流式
from openai import OpenAI
api_key = "sk-HTdmSI6B2cNt************************************"
api_base = "https://sg.uiuiapi.com/v1"
client = OpenAI(api_key=api_key, base_url=api_base)
completion = client.chat.completions.create(
model="claude-3-opus-20240229",
stream: True,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
]
)
for chunk in completion:
print(chunk.choices[0].delta)
Python 非流
from openai import OpenAI
api_key = "sk-HTdmSI6B2cNt************************************"
api_base = "https://sg.uiuiapi.com/v1"
client = OpenAI(api_key=api_key, base_url=api_base)
completion = client.chat.completions.create(
model="claude-3-opus-20240229",
stream: False,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Hello!"}
]
)
print(completion.choices[0].message)
Python Whisper 语音转文字
from openai import OpenAI
from pathlib import Path
# 设置你的基础URL和API密钥
base_url = "https://sg.uiuiapi.com/v1"
key = "sk-HTdmSI6B2cNt************************************"
# 初始化OpenAI客户端
client = OpenAI(api_key=key, base_url=base_url)
# 音频文件的路径
audio_file_path = "C:/speech.mp3"
# 打开音频文件
with open(audio_file_path, "rb") as audio_file:
# 创建转录
transcription = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file
)
# 打印转录文本
print(transcription.text)
Python TTS 文字转语音
from openai import OpenAI
from pathlib import Path
def test_text_speech(model="tts-1"):
print(f"Testing {model} - text to speech")
speech_file_path = Path(__file__).parent / "speech1.mp3"
response = client.audio.speech.create(
model=model,
voice="alloy", # 可选 alloy, echo, fable, onyx, nova, shimmer
input="示例文本",
)
response.stream_to_file(speech_file_path)
base_url = "https://sg.uiuiapi.com/v1"
key = "sk-HTdmSI6B2cNt************************************"
client = OpenAI(base_url=base_url, api_key=key)
test_text_speech()
go 实例、java 实例
java 实例
import okhttp3.*;
import java.io.IOException;
public class OpenAIChat {
public static void main(String[] args) {
String url = "https://sg.uiuiapi.com/v1/chat/completions";
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
String json = "{\n" +
" \"max_tokens\": 1200,\n" +
" \"model\": \"gpt-3.5-turbo\",\n" +
" \"temperature\": 0.8,\n" +
" \"top_p\": 1,\n" +
" \"presence_penalty\": 1,\n" +
" \"messages\": [\n" +
" {\n" +
" \"role\": \"system\",\n" +
" \"content\": \"You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.\"\n" +
" },\n" +
" {\n" +
" \"role\": \"user\",\n" +
" \"content\": \"你是chatGPT多少?\"\n" +
" }\n" +
" ]\n" +
"}";
RequestBody body = RequestBody.create(mediaType, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Bearer sk-HTdmSI6B2cNt************************************)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
String result = response.body().string();
System.out.println(result);
} else {
System.err.println("Request failed: " + response);
}
} catch (IOException e) {
System.err.println("Error during API call: " + e.getMessage());
}
}
}
go 实例
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
url := "https://sg.uiuiapi.com/v1/chat/completions"
apiKey := "sk-HTdmSI6B2cNt************************************"
if apiKey == "" {
fmt.Println("API Key is not set")
return
}
payload := map[string]interface{}{
"max_tokens": 1200,
"model": "gpt-3.5-turbo",
"temperature": 0.8,
"top_p": 1,
"presence_penalty": 1,
"messages": []map[string]string{
{
"role": "system",
"content": "You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible.",
},
{
"role": "user",
"content": "你是chatGPT多少?",
},
},
}
jsonPayload, err := json.Marshal(payload)
if err != nil {
fmt.Println("Error encoding JSON payload:", err)
return
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload))
if err != nil {
fmt.Println("Error creating HTTP request:", err)
return
}
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error making API request:", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Printf("Request failed with status: %d\n", resp.StatusCode)
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
fmt.Println("Response:", string(body))
}
1.3 Curl 接入示例
Curl 流式
curl https://sg.uiuiapi.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-HTdmSI6B2cNt************************************" \
-d '{
"model": "claude-3-opus-20240229",
"stream": true,
"messages": [{ "role": "user", "content": "say 1" }]
}'
Curl 非流
curl https://sg.uiuiapi.com/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-HTdmSI6B2cNt************************************" \
-d '{
"model": "claude-3-opus-20240229",
"stream": false,
"messages": [{ "role": "user", "content": "say 1" }]
}'
1.4 Node.js 接入示例
Node.js 流式
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: 'sk-HTdmSI6B2cNt************************************',
baseURL: "https://sg.uiuiapi.com/v1"
});
async function main() {
try {
const completionStream = await openai.chat.completions.create({
stream: true,
messages: [{ role: "system", content: "You are a helpful assistant." }],
model: "claude-3-opus-20240229",
});
completionStream.on('data', (chunk) => {
const data = chunk.toString();
try {
const parsed = JSON.parse(data);
console.log(parsed.choices[0]);
} catch (error) {
console.error("Error parsing JSON:", error);
}
});
completionStream.on('end', () => {
console.log("Stream ended.");
});
completionStream.on('error', (error) => {
console.error("Stream error:", error);
});
} catch (error) {
console.error("Error in API call:", error);
}
}
main();
Node.js 非流
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: 'sk-HTdmSI6B2cNt************************************',
baseURL: "https://sg.uiuiapi.com/v1"
});
async function main() {
try {
const completion = await openai.chat.completions.create({
stream: false,
messages: [{ role: "system", content: "You are a helpful assistant." }],
model: "claude-3-opus-20240229",
});
console.log(completion.choices[0].message.content);
} catch (error) {
console.error("Error in API call:", error);
}
}
main();
1.5 Python使用Claude、gpt-4o识别图片
识别链接格式图片
from openai import OpenAI
client = OpenAI(
base_url="https://sg.uiuiapi.com/v1",
api_key=key
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What’s in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
},
},
],
}
],
max_tokens=300,
)
print(response.choices[0])
识别Base64格式图片
import base64
import time
from openai import OpenAI
import openai
key = 'sk-xxxx'
client = OpenAI(
base_url="https://sg.uiuiapi.com/v1",
api_key=key
)
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
image_path = "图片.jpg"
base64_image = encode_image(image_path)
while True:
response = client.chat.completions.create(
model="claude-3-5-sonnet-20240620",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "这张图片里有什么?请详细描述。"},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
],
temperature=1
)
print(response)
print(response.choices[0].message.content)
time.sleep(1)
dall-e-3、Midjourney接入画图模型示例
dall-e-3 画图模型
其他语言 可通过curl实例 用ChatGPT转下
curl https://sg.uiuiapi.com/v1/images/generations \
-H "Authorization: Bearer sk-xxxx" \
-H "Content-Type: application/json" \
-d '{
"model": "dall-e-3",
"prompt": "a white siamese cat",
"n": 1,
"size": "1024x1024"
}'
Midjourney 画图接入向导 程序实例
本章以提交 Imagine 任务为例子介绍如何使用OpenAI-uiuiapi的api key接入 Midjourney;
点击这里查看更多API接口
模式接入点
- 混合模式(将去除) https://sg.uiuiapi.com
- fast模式 https://sg.uiuiapi.com/fast
- relax模式 https://sg.uiuiapi.com/relax
- 3中模式价格不一致
curl 实例
第一步:提交Imagine任务
接口说明 获取到任何ID result:1320098173412546
curl --request POST \
--url https://sg.uiuiapi.com/fast/mj/submit/imagine \
--header 'Authorization: Bearer sk-xxxxxx替换为你的key' \
-H "Content-Type: application/json" \
--data '{
"base64Array": [],
"instanceId": "",
"modes": [],
"notifyHook": "https://ww.baidu.com/notifyHook/back",
"prompt": "black cat",
"remix": true,
"state": ""
}'
第二步:根据任务ID获取任务结果
由第一步得到任务ID为 :1320098173412546 得到返回结果。
返回结果说明,请参考返回结果说明
curl --request GET \
--url https://sg.uiuiapi.com/fast/mj/task/1320098173412546/fetch \
--header 'Authorization: Bearer sk-xxxxxx替换为你的key' \
-H "Content-Type: application/json"
声明:本文内容及配图来自互利网收集整理撰写或者入驻合作网站授权转载。文章及其配图仅供学习之用,如有内容图片侵权或者其他问题,请联系本站侵删。
-- 展开阅读全文 --
暂无评论,939人围观