自己实现 OpenAI 的 /v1/embeddings 接口

自己实现 OpenAI 的 /v1/embeddings 接口

  • [0. 背景](#0. 背景)
  • [1. 修改 .env 文件](#1. 修改 .env 文件)
  • [2. 修改 get_embedding 方法](#2. 修改 get_embedding 方法)

0. 背景

使用 OpenAI 的 API Key 是需要付费的,为了节省成本,自己尝试实现 OpenAI 的各种接口。

本文章主要是实现 /v1/embeddings/v1/engines/{model_name}/embeddings 接口的部分代码示例。

1. 修改 .env 文件

添加 COHERE_API_KEY,

复制代码
COHERE_API_KEY='abcdeOuJIC5scu0dB6TJW0CijNMDP5tHfu8u2xyz' # 此 key 无效

2. 修改 get_embedding 方法

复制代码
async def get_embedding(payload: Dict[str, Any]):
    # print(f"payload: {payload}")
    cohere_payload = {"texts": payload["input"], "truncate": "END"}
    # print(f"cohere_payload: {cohere_payload}")
    # print(f"os.environ['COHERE_API_KEY']: {os.environ['COHERE_API_KEY']}")
    cohere_headers = {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + os.environ['COHERE_API_KEY'],
        'Content-Type': 'application/json',
    }
    # print(f"cohere_headers: {cohere_headers}")
    async with httpx.AsyncClient() as client:
        # https://docs.cohere.com/reference/embed
        response = await client.post(
            "https://api.cohere.ai/v1/embed",
            headers=cohere_headers,
            json=cohere_payload,
            timeout=WORKER_API_TIMEOUT,
        )
        # print(f"response: {response}")
        cohere_embeddings = response.json()
        # print(f"cohere_embeddings: {cohere_embeddings}")
        embedding = {"embedding": cohere_embeddings["embeddings"], "token_num": 1}
        return embedding

完结!

相关推荐
全栈弄潮儿6 小时前
AI 编程中的隐私与安全:哪些信息不要提交
安全·openai·ai编程
wangruofeng9 小时前
OpenAI 断供 Cursor:这不是商业决定,是战争行为
openai·ai编程·cursor
VIP_CQCRE12 小时前
在 WorkBuddy 里一键接入 Claude、GPT、Gemini、DeepSeek:Ace Data Cloud 让 AI 模型调用更简单
ai·大模型·openai·workbuddy·ace data cloud
陈大鱼头16 小时前
突发!OpenAI 要封杀 Cursor
openai·cursor·vibecoding
全栈弄潮儿1 天前
用 AI 辅助代码审查:提交前检查什么
aigc·openai·ai编程
Flynt1 天前
Codex回退对话却不回退文件:OpenAI做了两次都没搞定的坑,有人用第三种思路补上了
openai·ai编程
杨杨杨大侠1 天前
MCP、ToolFunction 与 Skill:从模型输入到工具执行
后端·aigc·openai
小四的小六2 天前
AI 生成代码翻车实录:数据库回填脚本上线后数据错乱,我的完整复盘
aigc·openai·ai编程
李剑一3 天前
连名词都不会,你AI个Der!学会AI基础之:到底模型是什么玩意儿?都说大模型,有小模型嘛?训练数据多它就是大模型吗?
aigc·openai·ai编程
GitLqr3 天前
从 TCP 底层看实时通信:为什么 SSE 往往比 WebSocket 更香?
websocket·http·openai