SimiRouter

API 脚本接入

通过 API 脚本接入 SimiRouter,按聊天、图像、音频三大类快速完成接口调用配置。

下面按聊天、图像、音频三大类分别给出可直接运行的脚本示例。复制后把 YOUR_API_KEY 替换为你的密钥即可运行。

聊天类

纯文本对话

OpenAI Chat Completions

兼容传统 OpenAI Chat 格式,适合已有客户端平滑迁移。

接口地址:POST /v1/chat/completions

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/chat/completions"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "gpt-5.5",
    "stream": True,
    "messages": [{"role": "user", "content": "用中文简单介绍一下 SimiRouter。"}],
}

def iter_sse(response):
    buffer = ""
    while chunk := response.read(4096):
        buffer += chunk.decode("utf-8", errors="replace")
        frames = buffer.split("\n\n")
        buffer = frames.pop()
        for frame in frames:
            data = "\n".join(line[5:].strip() for line in frame.splitlines() if line.startswith("data:")).strip()
            if data and data != "[DONE]":
                yield data

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json", "Accept": "text/event-stream"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    for data in iter_sse(response):
        chunk = json.loads(data)
        for choice in chunk.get("choices") or []:
            print((choice.get("delta") or {}).get("content", ""), end="", flush=True)
print()

图片识别

OpenAI Chat Completions

接口地址:POST /v1/chat/completions

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/chat/completions"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "gpt-5.5",
    "stream": True,
    "messages": [{
        "role": "user",
        "content": [
            {"type": "text", "text": "这张图片有什么?请用中文简要描述。"},
            {"type": "image_url", "image_url": {"url": "https://api.dwchainless.com/logo.png"}},
        ],
    }],
}

def iter_sse(response):
    buffer = ""
    while chunk := response.read(4096):
        buffer += chunk.decode("utf-8", errors="replace")
        frames = buffer.split("\n\n")
        buffer = frames.pop()
        for frame in frames:
            data = "\n".join(line[5:].strip() for line in frame.splitlines() if line.startswith("data:")).strip()
            if data and data != "[DONE]":
                yield data

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json", "Accept": "text/event-stream"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    for data in iter_sse(response):
        chunk = json.loads(data)
        for choice in chunk.get("choices") or []:
            print((choice.get("delta") or {}).get("content", ""), end="", flush=True)
print()

网络搜索

OpenAI Chat Completions

通过 tools 参数启用网络搜索,模型可自动联网获取实时信息。

接口地址:POST /v1/chat/completions

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/chat/completions"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "mimo-v2.5-chat",
    "messages": [{"role": "user", "content": "搜索:今天北京的天气"}],
    "tools": [{"type": "web_search"}],
    "max_tokens": 1024,
    "stream": False,
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    print(result["choices"][0]["message"]["content"])

工具调用

OpenAI Chat Completions

通过 tools 参数定义自定义函数,让模型在需要时调用你的工具函数(如查询天气、计算、数据库查询等)。

接口地址:POST /v1/chat/completions

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/chat/completions"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "gpt-5.5",
    "messages": [{"role": "user", "content": "北京现在几点?"}],
    "tools": [{
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "获取指定城市的当前时间",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "城市名称"},
                },
                "required": ["city"],
            },
        },
    }],
    "stream": False,
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    message = result["choices"][0]["message"]
    
    # 检查模型是否请求调用工具
    if message.get("tool_calls"):
        for tool_call in message["tool_calls"]:
            print(f"模型请求调用函数:{tool_call['function']['name']}")
            print(f"参数:{tool_call['function']['arguments']}")
    else:
        print(message["content"])

文件识别

OpenAI Chat Completions

通过 content 数组传入文件的 Base64 数据,让模型读取并分析文件内容。支持文本文件(txt、md、json 等)和文档格式(pdf、docx 等)。

接口地址:POST /v1/chat/completions

import base64
import json
import urllib.request
from pathlib import Path

API_URL = "https://api.dwchainless.com/v1/chat/completions"
API_KEY = "YOUR_API_KEY"
FILE_PATH = "/your/file/path/sample.txt"

file_b64 = base64.b64encode(Path(FILE_PATH).read_bytes()).decode()

body = {
    "model": "mimo-v2.5-chat",
    "messages": [{
        "role": "user",
        "content": [
            {"type": "text", "text": "读取并总结这个文件"},
            {"type": "file", "file": {"file_data": file_b64, "filename": Path(FILE_PATH).name}},
        ],
    }],
    "max_tokens": 1024,
    "stream": False,
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    print(result["choices"][0]["message"]["content"])

纯文本对话

OpenAI Responses

新一代 OpenAI 接口,适合文本对话、图片理解和流式输出。

接口地址:POST /v1/responses

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/responses"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "gpt-5.5",
    "stream": True,
    "input": "用中文简单介绍一下 SimiRouter。",
}

def iter_sse(response):
    buffer = ""
    while chunk := response.read(4096):
        buffer += chunk.decode("utf-8", errors="replace")
        frames = buffer.split("\n\n")
        buffer = frames.pop()
        for frame in frames:
            data = "\n".join(line[5:].strip() for line in frame.splitlines() if line.startswith("data:")).strip()
            if data and data != "[DONE]":
                yield data

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json", "Accept": "text/event-stream"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    for data in iter_sse(response):
        event = json.loads(data)
        if event.get("type") == "response.output_text.delta":
            print(event.get("delta", ""), end="", flush=True)
        if event.get("type") in ("response.completed", "response.done"):
            break
print()

图片识别

OpenAI Responses

接口地址:POST /v1/responses

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/responses"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "gpt-5.5",
    "stream": True,
    "input": [{
        "role": "user",
        "content": [
            {"type": "input_text", "text": "这张图片有什么?请用中文简要描述。"},
            {"type": "input_image", "image_url": "https://api.dwchainless.com/logo.png"},
        ],
    }],
}

def iter_sse(response):
    buffer = ""
    while chunk := response.read(4096):
        buffer += chunk.decode("utf-8", errors="replace")
        frames = buffer.split("\n\n")
        buffer = frames.pop()
        for frame in frames:
            data = "\n".join(line[5:].strip() for line in frame.splitlines() if line.startswith("data:")).strip()
            if data and data != "[DONE]":
                yield data

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json", "Accept": "text/event-stream"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    for data in iter_sse(response):
        event = json.loads(data)
        if event.get("type") == "response.output_text.delta":
            print(event.get("delta", ""), end="", flush=True)
        if event.get("type") in ("response.completed", "response.done"):
            break
print()

纯文本对话

接口地址:POST /v1/messages

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/messages"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "claude-opus-4",
    "max_tokens": 1024,
    "messages": [
        {"role": "user", "content": "用中文简单介绍一下 SimiRouter。"}
    ]
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json"
    },
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    print(result["content"][0]["text"])

图片识别

接口地址:POST /v1/messages

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/messages"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "claude-opus-4",
    "max_tokens": 1024,
    "messages": [{
        "role": "user",
        "content": [
            {"type": "text", "text": "这张图片有什么?请用中文简要描述。"},
            {
                "type": "image",
                "source": {
                    "type": "url",
                    "url": "https://api.dwchainless.com/logo.png"
                }
            }
        ]
    }]
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json"
    },
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    print(result["content"][0]["text"])

网络搜索

接口地址:POST /v1/messages

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/messages"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "claude-opus-4",
    "max_tokens": 1024,
    "stream": False,
    "messages": [
        {"role": "user", "content": "搜索:今天北京的天气"}
    ],
    "tools": [{"type": "web_search"}]
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json"
    },
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    print(result["content"][0]["text"])

工具调用

接口地址:POST /v1/messages

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/messages"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "claude-opus-4",
    "max_tokens": 1024,
    "tools": [{
        "name": "get_current_time",
        "description": "获取指定城市的当前时间",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "城市名称"}
            },
            "required": ["city"]
        }
    }],
    "messages": [
        {"role": "user", "content": "北京现在几点?"}
    ]
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json"
    },
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    for content in result["content"]:
        if content["type"] == "tool_use":
            print(f"模型请求调用工具:{content['name']}")
            print(f"参数:{json.dumps(content['input'], ensure_ascii=False)}")
        elif content["type"] == "text":
            print(content["text"])

纯文本对话

接口地址:POST /v1beta/models/{model}:generateContent

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1beta/models/gemini-2.0-flash-001:generateContent"
API_KEY = "YOUR_API_KEY"

body = {
    "contents": [{
        "role": "user",
        "parts": [{"text": "用中文简单介绍一下 SimiRouter。"}]
    }]
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json"
    },
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    print(result["candidates"][0]["content"]["parts"][0]["text"])

图片识别

接口地址:POST /v1beta/models/{model}:generateContent

import json
import urllib.request
import base64

API_URL = "https://api.dwchainless.com/v1beta/models/gemini-2.0-flash-001:generateContent"
API_KEY = "YOUR_API_KEY"

# 方式1:使用图片 URL
body = {
    "contents": [{
        "role": "user",
        "parts": [
            {"text": "这张图片有什么?请用中文简要描述。"},
            {
                "inline_data": {
                    "mime_type": "image/png",
                    "data": "图片的base64编码"  # 或使用 fileData 字段传递 URI
                }
            }
        ]
    }]
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json"
    },
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    print(result["candidates"][0]["content"]["parts"][0]["text"])

网络搜索

Gemini 原生支持 Google Search grounding。

接口地址:POST /v1beta/models/{model}:generateContent

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1beta/models/gemini-2.0-flash-001:generateContent"
API_KEY = "YOUR_API_KEY"

body = {
    "contents": [{
        "role": "user",
        "parts": [{"text": "今天北京的天气如何?"}]
    }],
    "tools": [{
        "google_search": {}
    }]
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json"
    },
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    print(result["candidates"][0]["content"]["parts"][0]["text"])

工具调用

接口地址:POST /v1beta/models/{model}:generateContent

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1beta/models/gemini-2.0-flash-001:generateContent"
API_KEY = "YOUR_API_KEY"

body = {
    "contents": [{
        "role": "user",
        "parts": [{"text": "北京现在几点?"}]
    }],
    "tools": [{
        "function_declarations": [{
            "name": "get_current_time",
            "description": "获取指定城市的当前时间",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "城市名称"
                    }
                },
                "required": ["city"]
            }
        }]
    }]
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json"
    },
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    parts = result["candidates"][0]["content"]["parts"]
    for part in parts:
        if "function_call" in part:
            print(f"模型请求调用工具:{part['function_call']['name']}")
            print(f"参数:{json.dumps(part['function_call']['args'], ensure_ascii=False)}")
        elif "text" in part:
            print(part["text"])

MiniMax

对接 MiniMax 系列模型,兼容 OpenAI Chat 格式,支持流式输出。

接口地址:POST /v1/chat/completions

模型名称严格区分大小写:MiniMax-M2.7(日常/代码首选)、MiniMax-M3(高阶推理)、MiniMax-M2.5(轻量快速)

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/chat/completions"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "MiniMax-M2.7",
    "stream": True,
    "messages": [{"role": "user", "content": "用中文简单介绍一下你自己。"}],
}

def iter_sse(response):
    buffer = ""
    while chunk := response.read(4096):
        buffer += chunk.decode("utf-8", errors="replace")
        frames = buffer.split("\n\n")
        buffer = frames.pop()
        for frame in frames:
            data = "\n".join(line[5:].strip() for line in frame.splitlines() if line.startswith("data:")).strip()
            if data and data != "[DONE]":
                yield data

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json", "Accept": "text/event-stream"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    for data in iter_sse(response):
        chunk = json.loads(data)
        for choice in chunk.get("choices") or []:
            print((choice.get("delta") or {}).get("content", ""), end="", flush=True)
print()

图像类

文生图

接口地址:POST /v1/images/generations

import base64
import json
import urllib.request
from pathlib import Path

API_URL = "https://api.dwchainless.com/v1/images/generations"
API_KEY = "YOUR_API_KEY"

def iter_sse(response):
    buffer = ""
    while chunk := response.read(4096):
        buffer += chunk.decode("utf-8", errors="replace")
        frames = buffer.split("\n\n")
        buffer = frames.pop()
        for frame in frames:
            data = "\n".join(line[5:].strip() for line in frame.splitlines() if line.startswith("data:")).strip()
            if data and data != "[DONE]":
                yield data

body = {"model": "gpt-image-2", "prompt": "生成一只太空猫", "n": 1, "size": "1024x1024", "stream": True, "response_format": "b64_json"}
request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json", "Accept": "text/event-stream"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    for data in iter_sse(response):
        event = json.loads(data)
        if event.get("type") == "image_generation.partial_image":
            print(".", end="", flush=True)
        if event.get("type") == "image_generation.completed":
            image = event.get("b64_json") or (event.get("data") or [{}])[0].get("b64_json")
            Path("generated-image.png").write_bytes(base64.b64decode(image))
            print("\n图片已保存:generated-image.png")
            break

图生图(参考图)

接口地址:POST /v1/responses

import base64
import json
import urllib.request
from pathlib import Path

API_URL = "https://api.dwchainless.com/v1/responses"
API_KEY = "YOUR_API_KEY"

def iter_sse(response):
    buffer = ""
    while chunk := response.read(4096):
        buffer += chunk.decode("utf-8", errors="replace")
        frames = buffer.split("\n\n")
        buffer = frames.pop()
        for frame in frames:
            data = "\n".join(line[5:].strip() for line in frame.splitlines() if line.startswith("data:")).strip()
            if data and data != "[DONE]":
                yield data

def image_from_event(event):
    for key in ("b64_json", "base64", "image_base64", "partial_image_b64"):
        if event.get(key):
            return event[key]
    for item in event.get("data") or []:
        image = image_from_event(item)
        if image:
            return image
    for item in (event.get("response") or {}).get("output") or []:
        if item.get("result"):
            return item["result"]
    return (event.get("item") or {}).get("result", "")

body = {
    "model": "gpt-5.5",
    "stream": True,
    "input": [{
        "role": "user",
        "content": [
            {"type": "input_text", "text": "参考这张图,生成一张更精致的科技风品牌图。"},
            {"type": "input_image", "image_url": "https://api.dwchainless.com/logo.png"},
        ],
    }],
    "tools": [{"type": "image_generation", "model": "gpt-image-2", "size": "1024x1024", "output_format": "png"}],
    "tool_choice": {"type": "image_generation"},
}
request = urllib.request.Request(API_URL, data=json.dumps(body).encode("utf-8"), method="POST", headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json", "Accept": "text/event-stream"})

with urllib.request.urlopen(request, timeout=900) as response:
    for data in iter_sse(response):
        event = json.loads(data)
        if event.get("type") in ("image_generation.partial_image", "response.image_generation_call.partial_image"):
            print(".", end="", flush=True)
        image = image_from_event(event)
        if image:
            Path("generated-image.png").write_bytes(base64.b64decode(image))
            print("\n图片已保存:generated-image.png")
            break

接口地址:POST /v1beta/models/{model}:generateContent

通过 responseModalities 指定生成图像,使用 imageConfig 控制尺寸和比例。

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1beta/models/gemini-2.0-flash-001:generateContent"
API_KEY = "YOUR_API_KEY"

body = {
    "contents": [{
        "role": "user",
        "parts": [{"text": "生成一只太空猫"}]
    }],
    "generationConfig": {
        "responseModalities": ["IMAGE"],
        "imageConfig": {
            "aspectRatio": "1:1",
            "imageSize": "1024x1024"
        }
    }
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json"
    },
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    # 处理返回的图像数据
    parts = result["candidates"][0]["content"]["parts"]
    for part in parts:
        if "inline_data" in part:
            image_data = part["inline_data"]["data"]
            print(f"图像已生成,MIME 类型:{part['inline_data']['mime_type']}")
            # 保存图像
            import base64
            with open("generated_image.png", "wb") as f:
                f.write(base64.b64decode(image_data))
            print("图像已保存:generated_image.png")

音频类

文字转语音

项目说明
模型mimo-v2.5-tts
路由POST /v1/audio/speech

voice 参数可选值:

取值音色
alloy冰糖 · 活泼少女
echo茉莉 · 知性女声
novaMia · 活泼英文女声
deanDean · 沉稳温柔
shimmerChloe · 甜美梦幻
onyx苏打 · 阳光少年
fable白桦 · 成熟男声
miloMilo · 阳光英文男声

调用示例:

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/audio/speech"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "mimo-v2.5-tts",
    "input": "你好,这是语音合成可用性测试。",
    "voice": "alloy",
    "speed": 1,
    "response_format": "mp3",
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    with open("speech1.mp3", "wb") as f:
        f.write(response.read())
print("音频已保存:speech1.mp3")

语音转文字

项目说明
模型mimo-v2.5-asr
路由POST /v1/audio/transcriptions

language 参数可选值:

取值说明
zh中文
en英语
auto自动识别

调用示例:

import json
import urllib.request
import uuid
from pathlib import Path

API_URL = "https://api.dwchainless.com/v1/audio/transcriptions"
API_KEY = "YOUR_API_KEY"
FILE_PATH = "/you/file/path/mp3_file_name.mp3"

def multipart(fields, file_data, filename):
    boundary = "----simirouter-" + uuid.uuid4().hex
    body = bytearray()
    for name, value in fields.items():
        body.extend(f"--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n".encode())
    body.extend(f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{filename}\"\r\nContent-Type: application/octet-stream\r\n\r\n".encode())
    body.extend(file_data)
    body.extend(f"\r\n--{boundary}--\r\n".encode())
    return bytes(body), "multipart/form-data; boundary=" + boundary

file_data = Path(FILE_PATH).read_bytes()
body, content_type = multipart(
    {"model": "mimo-v2.5-asr", "language": "auto", "response_format": "json"},
    file_data,
    Path(FILE_PATH).name,
)
request = urllib.request.Request(API_URL, data=body, method="POST", headers={"Authorization": "Bearer " + API_KEY, "Content-Type": content_type})

with urllib.request.urlopen(request, timeout=900) as response:
    print(json.loads(response.read()))

音频设计

使用自然语言提示词,根据提示词生成一段新的音频文件。

项目说明
模型mimo-v2.5-tts-voicedesign
路由POST /v1/audio/speech

调用示例:

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/audio/speech"
API_KEY = "YOUR_API_KEY"

body = {
    "model": "mimo-v2.5-tts-voicedesign",
    "input": "你好,这是声音设计可用性测试。",
    "style": "浑厚男声,普通话标准",
    "speed": 1,
    "response_format": "mp3",
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    with open("speech1.mp3", "wb") as f:
        f.write(response.read())
print("音频已保存:speech1.mp3")

音频克隆

使用已有音频文件的声音,根据提示词生成一段新的音频文件。

项目说明
模型mimo-v2.5-tts-voiceclone
路由POST /v1/audio/speech

voice 参数需传入参考音频的 Base64 数据,格式为 data:audio/wav;base64,$REFERENCE_BASE64。

调用示例:

import base64
import json
import urllib.request
from pathlib import Path

API_URL = "https://api.dwchainless.com/v1/audio/speech"
API_KEY = "YOUR_API_KEY"
REFERENCE_PATH = "/you/file/path/reference.wav"

reference_b64 = base64.b64encode(Path(REFERENCE_PATH).read_bytes()).decode()

body = {
    "model": "mimo-v2.5-tts-voiceclone",
    "input": "你好,这是声音克隆可用性测试。",
    "voice": "data:audio/wav;base64," + reference_b64,
    "speed": 1,
    "response_format": "mp3",
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json"},
)

with urllib.request.urlopen(request, timeout=900) as response:
    with open("speech1.mp3", "wb") as f:
        f.write(response.read())
print("音频已保存:speech1.mp3")

接口地址:POST /v1beta/models/{model}:generateContent

通过 responseModalities 指定生成音频,使用 speechConfig 配置语音参数。

import json
import urllib.request
import base64

API_URL = "https://api.dwchainless.com/v1beta/models/gemini-2.0-flash-001:generateContent"
API_KEY = "YOUR_API_KEY"

body = {
    "contents": [{
        "role": "user",
        "parts": [{"text": "你好,这是语音测试。"}]
    }],
    "generationConfig": {
        "responseModalities": ["AUDIO"],
        "speechConfig": {
            "voiceConfig": {
                "prebuiltVoiceConfig": {
                    "voiceName": "Aoede"
                }
            }
        }
    }
}

request = urllib.request.Request(
    API_URL,
    data=json.dumps(body).encode("utf-8"),
    method="POST",
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json"
    },
)

with urllib.request.urlopen(request, timeout=900) as response:
    result = json.loads(response.read())
    parts = result["candidates"][0]["content"]["parts"]
    for part in parts:
        if "inline_data" in part:
            audio_data = part["inline_data"]["data"]
            print(f"音频已生成,MIME 类型:{part['inline_data']['mime_type']}")
            with open("output_audio.mp3", "wb") as f:
                f.write(base64.b64decode(audio_data))
            print("音频已保存:output_audio.mp3")

获取模型

查询当前可用的模型列表。

接口地址:GET /v1/models

import json
import urllib.request

API_URL = "https://api.dwchainless.com/v1/models"
API_KEY = "YOUR_API_KEY"

request = urllib.request.Request(
    API_URL,
    method="GET",
    headers={"Authorization": "Bearer " + API_KEY},
)

with urllib.request.urlopen(request, timeout=30) as response:
    result = json.loads(response.read())
    print(json.dumps(result, indent=2, ensure_ascii=False))

这篇文档对您有帮助吗?

最后更新于

QQWhatsAppTelegramSimiTalk