自己实现 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

完结!

相关推荐
VIP_CQCRE4 小时前
在 Visual Studio 里接入 AI 编程能力:用 Ace Data Cloud + LMLocal 打通 OpenAI 兼容接口
openai·ai编程·visual studio·mcp·ace data cloud
挖掘狂人6 小时前
从 Agent Loop 到沙盒边界:一次讲清楚 Codex 的八大功能
程序员·openai·agent
全栈弄潮儿6 小时前
给中级开发者的 AI 能力升级路线图
aigc·openai·ai编程
全栈弄潮儿18 小时前
哪些任务该交给 AI,哪些必须由开发者负责?
aigc·openai·ai编程
niaonao1 天前
C盘爆红别乱删!我用 Codex 查出 AppData 占了 87.81GB
人工智能·openai
VIP_CQCRE1 天前
在 Visual Studio 里接入 Ace Data Cloud:用 LMLocal 直接调用 OpenAI 兼容模型
openai·ai编程·visual studio·ace data cloud·lmlocal
网络毒刘2 天前
GPT-6.1 Sol 定位速读:成本效率型编码模型与「何时该换本地 Agent」
人工智能·gpt·openai·agent·cursor
VIP_CQCRE2 天前
在 Visual Studio 里接入 Ace Data Cloud:让 LMLocal 调用 OpenAI 兼容模型
openai·ai编程·开发工具·visual studio·ace data cloud
9i编程2 天前
3. 教 AI 上班:带出我的数字同事 —— 文档返工与代码检查——明确指令与丢三落四的拉扯
人工智能·openai·ai编程
AI日报派送佬2 天前
2026年10月5日AI行业日报|中美模型差距缩至3%,物理AI百亿估值爆发,决策模型国产开源竞速
人工智能·openai·ai智能体·ai日报·物理ai·算力基建·ai商业化