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

完结!

相关推荐
梦想的颜色12 小时前
【AI速览】2026年 9月 GPT‑6 Astra 深度解析:Agent 时代的前沿旗舰,能力、成本、落地痛点与选型判断
人工智能·openai·agent·astra·vibecoding·大模型测评·gpt6
向星而行_star12 小时前
# OpenAI 发布 GPT Image 2.5:生成提速 50%,还能“指哪改哪“,AI 生图进入修图时代
人工智能·gpt·openai·gpt6·image2.5·星途ai
ServBay14 小时前
ChatGPT Images 2.5发布,改图终于不换脸了
gpt·openai
Ming_studying18 小时前
近期AI热点010|ChatGPT Images 2.5 加入 Sketch:图像生成从文字提示走向草图交互
人工智能·chatgpt·openai·ai绘图·sketch
全栈弄潮儿18 小时前
我的 AI 编程工作台:工具、模型与基础配置
aigc·openai·ai编程
Kapaseker1 天前
GPT-6 VS GPT-5.6:你该怎么选
openai·ai编程
stormzhangV1 天前
DeepSeek 降价,扩招 150 人
openai·ai编程
VIP_CQCRE2 天前
在 Visual Studio 里接入 Ace Data Cloud:让 IDE 拥有 OpenAI 兼容 AI 能力
openai·ai编程·开发工具·visual studio·ace data cloud
William一直在路上2 天前
GPT-6 Astra 研究报告——模型能力、API 演进与 Agent/MCP 生态影响分析
人工智能·gpt·llm·openai·astra
Code_Artist2 天前
从 Tool Calling 到能力编排:重新理解 Agent Skill 的运行机制——以 tRPC-Agent-Go 为例
人工智能·openai·agent