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

完结!

相关推荐
全栈弄潮儿16 小时前
先让 AI 出方案,再让它写代码:新手也能使用的设计习惯
aigc·openai·ai编程
全栈弄潮儿1 天前
让 AI 帮你拆分一个功能需求:页面、接口、数据和测试任务怎么分
aigc·openai·ai编程
jeffer_liu1 天前
OpenAI把Codex开源了?
openai·deepseek·harness·openai开源
怕浪猫2 天前
2026年为什么我推荐你学DeepSeek Harness?AI Agent开发入门指南
openai·agent·ai编程
怕浪猫2 天前
从 pre-execute 到 post-execute:AI Agent 调用工具时背后发生了什么
aigc·openai·ai编程
爱吃的小肥羊2 天前
ChatGPT Pro 额度被爆缩水 77%,OpenAI 被喷惨了!
openai
全栈弄潮儿3 天前
一周总结:把 AI 当助手,而不是答案机器
aigc·openai·ai编程
明航咨询_贾老师3 天前
ChatGPT全球宕机12+ API接口异常:事件复盘与AI从业者的架构启示
openai
怕浪猫3 天前
一行行拆解 agent-loop:AI Agent 的"思考循环"到底是怎么转的
aigc·openai·agent
9i编程3 天前
4. AI编写的SKILL,坑我一一试过,这次我自己改写:换个工具,照样不按SKILL写文档
人工智能·openai·ai编程