中转API 部署ChatGPT应用Python开发调用请求代码示例

号优优网uiuihao
预计阅读时长 30 分钟
位置: 首页 AI工具 正文

API 站点使用教程

1.1 API 接口地址填写

请勿将 API Key 泄露给他人,一旦泄露,请立即删除并创建新的 API Key
修改原则:修改应用 BASE_URL 为其中一个中转接口调用地址接口即可,例如:

修改原则
https://api.openai.com

https://sg.uiuiapi.com

(如果原来接口地址需要加 /v1 的话我们的接口地址也需要在后面加 /v1)

出现回复缓慢的情况,请检查 API 调用日志,若日志正常,则自行调整网络。

Base Url
不同客户端适配的接口地址格式不同,通常为以下三种:

  1. https://sg.uiuiapi.com
  2. https://sg.uiuiapi.com/v1
  3. https://sg.uiuiapi.com/v1/chat/completions

1.2 Python 接入示例

本站所有AI模型均使用 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()

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("https://sg.uiuiapi.com/v1");

async function main() {
  const completion = await openai.chat.completions.create({
    stream: true,
    messages: [{ role: "system", content: "You are a helpful assistant." }],
    model: "claude-3-opus-20240229",
  });

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

main();

Node.js 非流

import OpenAI from "openai";

const openai = new OpenAI("https://sg.uiuiapi.com/v1");

async function main() {
  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]);
}

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)

API快速使用工具推荐 🔥

UIUIAPI在线AI工具

Python调用OpenAI API

设置API基础URL

有两种方法:

  1. 在代码中设置:
import openai
openai.api_base = "https://sg.uiuiapi.com/v1"
  1. 设置环境变量:
OPENAI_API_BASE=https://sg.uiuiapi.com/v1

发送API请求

可以使用curl命令或Python代码发送请求。

curl示例:

bash
curl https://sg.uiuiapi.com/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -d '{
  "model": "gpt-3.5-turbo",
  "messages": [{"role": "user", "content": "Say this is a test!"}],
  "temperature": 0.7
}'

Python示例:

import openai

openai.api_key = "sk-"
openai.api_base = "https://sg.uiuiapi.com/v1"

def gpt_35_api_stream(messages: list):
    try:
        response = openai.ChatCompletion.create(
            model='gpt-3.5-turbo',
            messages=messages,
            stream=True,
        )
        # 处理流式响应
        # ...
    except Exception as err:
        return (False, f'OpenAI API 异常: {err}')

# 使用示例
messages = [{'role': 'user','content': '鲁迅和周树人的关系'},]
print(gpt_35_api_stream(messages))

使用OpenAI官方SDK

import openai

def query_gpt4(question):
    openai.api_key = "sk-xxx"
    openai.base_url = 'https://sg.uiuiapi.com/v1/'

    try:
        response = openai.chat.completions.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": "You are a helpful assistant."},
                {"role": "user", "content": question}
            ]
        )
        return response['choices'][0].message['content']
    except Exception as e:
        return str(e)

# 使用示例
question = "为什么太阳那么红?"
answer = query_gpt4(question)
print(answer)

这个整理后的版本保留了原文的主要内容,并按照不同的调用方法和示例进行了分类,使结构更清晰,便于阅读和理解。

声明:本文内容及配图来自互利网收集整理撰写或者入驻合作网站授权转载。文章及其配图仅供学习之用,如有内容图片侵权或者其他问题,请联系本站侵删。
-- 展开阅读全文 --
头像
MiGPT改造专属语音助手:将小爱音箱接入 ChatGPT 和豆包
« 上一篇 06-05
Anthropic 发布Claude 3.5 Sonnet模型运行速度是Claude 3 Opus的两倍
下一篇 » 06-21

相关文章

取消
微信二维码
微信二维码
支付宝二维码

发表评论

暂无评论,3858人围观

作者信息

似水流年

今日已经过去小时
这周已经过去
本月已经过去
今年已经过去个月

热门文章

系统获取,无需修改

标签列表

目录[+]