胜算云文档
胜算云
胜算云
  1. 使用案例
  • 快速入门
  • 更新公告
  • 使用指南
    • 账号指南
    • 开发者快速入门指南
    • VS Code插件快速入门指南
    • AI群聊快速入门指南
  • 大厂模型
    • 联网搜索
    • 模型路由
    • 工具和函数调用
    • 错误处理
    • 常见问题
    • 使用案例
      • 在VS Code中使用Cline-中文版
      • cherry studio和chat box配置指南
      • 如何在KiloSSY中使用胜算云Router
      • 胜算云大模型API接入各大智能体平台
      • Roo code配置
      • MCP安装
    • API手册
      • API 错误代码说明
      • 聊天补全
        POST
      • 文本向量化
        POST
      • 多模态向量化
        POST
      • 图像生成
        POST
      • 文本分词
        POST
      • 文本重排序
        POST
  • GPU租赁
    • GPU租赁与选型指南
    • 容器实例
    • 数据与存储
    • 费用相关
  • 条款与协议
    • 用户协议
    • 隐私政策
    • 用户充值协议
    • 付费充值协议
    • 使用条款
    • 数据安全协议和分析
  1. 使用案例

胜算云大模型API接入各大智能体平台

Dify

官方网址 https://dify.ai

  1. 在dify工作流编辑器界面,依次点击这些组件打开《模型供应商界面》
    image.png
  2. 在模型供应商中搜索“openai”, 搜索结果中选择 OpenAI-API-compatible 安装。安装以后 OpenAI-API-compatible 会出现在待配置区。

image.png

image.png
3. 点击待配置区 OpenAI-API-compatible 右下角的<添加模型>。添加模型界面有下面这些主要的配置项, 所有这些配置参数都可以在胜算云的模型列表页里找到。https://router.shengsuanyun.com/model
image.png

模型类型

  • LLM 大语言模型接口
  • Rerank 相似性排序接口
  • Text Embedding 文本向量化接口
  • Speech2text 语音转文本接口
  • TTS 文本转语音接口

模型名称

例如:deepseek/deepseek-v3, 可以在胜算云的模型列表页点击复制按钮复制。https://router.shengsuanyun.com/model/3

API Key

例如:hE3k1o********************************hpHmoIhsUrhfA
API endpoint URL
直接填写 https://router.shengsuanyun.com/api/v1
模型上下文长度
例如:64000

  1. 配置完成后就可以在工作流中调用了。

image.png

ima.copilot

官方网址: https://ima.qq.com
不支持接入。目前只支持 Hunyuan, Hunyuan T1, DeepSeek V3, DeepSeek R1 四款模型,不支持其他模型接入。

扣子

官方网址: https://www.coze.cn
https://www.coze.cn/open/docs/guides/Stream_plugin 扣子流式API插件官方配置教程

1. 创建扣子插件

通过扣子的“插件”系统可以接入胜算云的大语言模型API。在《扣子开发平台》页面点击”快速开始“,左侧边栏”工作空间“ > 二级左侧边栏 ”资源库“ > 右上角 ”+资源“,打开插件定义对话框。第一个页面主要填以下内容。
image.png

  • 插件名称 例如,胜算云大语言模型API
  • 插件描述
  • 插件工具创建方式
    这里要选择“云侧插件-基于已有的服务创建”
  • 插件 URL
    由于胜算云官方和返回数据结构和扣子不兼容,这里我们需要建立一个中间服务器转换数据格式。我使用https://api.lookfoto.cc
  • Header列表
    Key: Content-Type value: text/event-stream
  • 授权方式
    选择不需要授权

2. 创建工具

插件创建成功后进入工具创建页面。创建工具有以下主要内容。

image.png

  • 工具名称
  • 工具描述
  • 工具路径
    这里要填写数据结构转换的API URL。 我这里是 /xhs/convert/stream
  • 配置输入参数

image.png

  • 配置输出参数

image.png

3. 胜算云官方 API 转扣子流式输出程序示例

uvicorn coze_converter_service:app --host 0.0.0.0 --port 80 --reload

from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from typing import Any, Dict, Optional
import requests
import json
import uvicorn

app = FastAPI(title="胜算云API转换扣子流式输出服务", version="1.0.0")

class ConvertRequest(BaseModel):
    api_key: str
    data: Dict[str, Any]
def convert_to_coze_stream(api_key: str, data: Dict[str, Any]):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    coze_event = {
        "id": '0',
        "event": "done",
        "data": {
            "stream_id": '0',
            "is_finish": False,
            "is_last_msg": True,
            "is_last_packet_in_msg": True,
            "content": ""
        }
    }
    url = "https://router.shengsuanyun.com/api/v1/chat/completions"
    try:
        with requests.post(url, json=data, headers=headers, stream=True, timeout=30) as res:
            res.raise_for_status()
            for line in res.iter_lines():
                if line:
                    buffer = line.decode('utf-8')
                    if '[DONE]' in buffer:
                        yield json.dumps(coze_event)
                        return
                    if buffer.startswith("data: "):
                        json_str = buffer[6:].strip()                        
               if not json_str:
                            continue
                        try:
                            original = json.loads(json_str)
                            msg_id = original.get("id", "")
                            choices = original.get("choices", [{}])
                            if choices:
                                finish_reason =  choices[0].get("finish_reason")
                                delta = choices[0].get("delta", {})
                                content = delta.get("content", "")
                            else:
                                finish_reason = None
                                content = ""
                            event_type = "content" if content else "reasoning"
                            response_data = {
                                "stream_id": msg_id,
                                "is_finish": finish_reason is not None,
                                "is_last_msg": finish_reason is not None,
                                "is_last_packet_in_msg": finish_reason is not None,
                                "content": "hi"
                            }
                            event_response = {
                                **coze_event,
                                "id": msg_id,
                                "event": event_type,
                                "data": response_data
                            }
                            yield json.dumps(event_response)
                        except json.JSONDecodeError as e:
                            error_msg = {
                                "error": "JSON解析失败",
                                "raw_data": json_str[:200],
                                "details": str(e)
                            }
                            print(f"JSON解析错误: {error_msg}")
                            error_event = {
                                **coze_event,
                                "event": "error",
                                "data": {
                                    **coze_event["data"],
                                    "content": json.dumps(error_msg)
                                }
                            }
                            yield json.dumps(error_event)
    except requests.exceptions.RequestException as e:
        error_event = {
            **coze_event,
            "event": "error",
            "data": {
                **coze_event["data"],
                "content": json.dumps({"error": "请求失败", "details": str(e)})
            }
        }
        yield json.dumps(error_event)


@app.post("/xhs/convert/stream")
async def convert_stream_api(request: ConvertRequest):
    try:
        return StreamingResponse(
            convert_to_coze_stream(
                api_key=request.api_key,
                data=request.data
            ),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Connection": "keep-alive",
                "Content-Type": "text/event-stream"
            }
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"转换失败: {str(e)}")

@app.get("/")
async def root():
    return {"message": "API接口规格转换服务运行中", "status": "healthy"}

if name == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)

文心智能体平台 AgentBuilder

平台不支持自带模型以外的大语言模型,但是可以封装到插件工具中。然后发布到插件商店。
https://agents.baidu.com/docs/develop/plugin/ability-plugin/basic/quick_pass/ 插件制作官方文档。

  1. 编写插件服务代码
    插件需要自备一台有公网ip的服务器,以把大语言模型封装成插件工具。平台支持post 头部验证,可以用来传递API_KEY, 以下是示例代码。
from flask_cors import CORS
import json
import random
import requests 

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "https://agents.baidu.com"}})

@app.route("/coding-master", methods=['POST'])
async def master():
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Bearer '):
        return jsonify({'message': '未提供有效的Authorization头', 'status': 'error'}), 401

    api_key = auth_header.split(' ')[1]
    if len(api_key) < 10:
        return jsonify({'message': '无效的Token', 'status': 'error'}), 401

    demand = request.json.get('demand', None)
    if not demand:
        return jsonify({'message': '无效的编程需求', 'status': 'error'}), 400
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {api_key}'
    }
    url = "https://router.shengsuanyun.com/api/v1/chat/completions"
    data = {
        "model": "anthropic/claude-3.7-sonnet",
        "messages": [{
            "role": "system",
            "content": "You are a helpful assistant that can generate code based on user demands."
        },{
            "role": "user",
            "content": demand
        }],
        "stream": False
    }
    try:
        res = requests.post(url, json=data, headers=headers, stream=False, timeout=60)
        res.raise_for_status()
        print(res.json())
        # return res.choices[0].message.content
        msg = res.json().get('choices', [{}])[0].get('message', None)
        if msg:
            return jsonify(msg), 200
        return jsonify({'message': 'LLM No response', 'status': 'error'}), 500
    except Exception as e:
        print(str(e))
        return jsonify({'message': str(e), 'status': 'error'}), 500


@app.route("/logo.png")
async def plugin_logo():
    return send_file('logo.png', mimetype='image/png')


@app.route("/.well-known/ai-plugin.json")
async def plugin_manifest():
    host = request.host_url
    with open(".well-known/ai-plugin.json", encoding="utf-8") as f:
        text = f.read().replace("PLUGIN_HOST", host)
        return text, 200, {"Content-Type": "application/json"}


@app.route("/.well-known/openapi.yaml")
async def openapi_spec():
    with open(".well-known/openapi.yaml", encoding="utf-8") as f:
        text = f.read()
        return text, 200, {"Content-Type": "text/yaml"}

@app.route("/example.yaml")
async def exampleSpec():
    with open("example.yaml") as f:
        text = f.read()
        return text, 200, {"Content-Type": "text/yaml"}

@app.route('/')
def index():
    return 'welcome to my plugin!'

if name == '__main__':
    app.run(debug=True, host='127.0.0.1', port=8888)
  1. 配置插件
    左侧边栏点击<我的插件>, 右上角点击<创建插件>

image.png
配置插件前,先要使用配置文件验证插件服务器。配置文件可以在官方文档中下载。

image.png
3. 配置完成以后,可以直接在配置页面测试。
image.png
4. 发布到插件商店
image.png
image.png
发布成功,等待审核通过。

修改于 2025-07-10 09:16:42
上一页
如何在KiloSSY中使用胜算云Router
下一页
Roo code配置
Built with