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

完结!

相关推荐
SQDN5 小时前
OpenAI Python SDK 遇到 502/503 怎么排?先看自动重试、request_id 与 timeout
openai·503·重试·api调试·python sdk
码哥字节11 小时前
为什么你的知识库越用越笨?不是没更新,是你少做了这三件事
openai
小马92612 小时前
GPT-6 Swarm 架构深度解析:从单体模型到 Agent 集群协同的范式跃迁
gpt·架构·大模型·openai·agent·分布式ai·swarm架构
AINative软件工程13 小时前
语义缓存别只看命中率:LLM 应用缓存失效的 5 个生产陷阱
openai
SQDN1 天前
Codex CLI 报 wire_api=“chat“ 不再支持?改为 Responses 并验证 /v1/responses
openai·开发工具·codex·responses api·config.toml
SQDN2 天前
Cline 配置 OpenAI Compatible 前怎么验证?先查 Base URL、/models 与模型 ID
openai·api·baseurl·cline·模型调试
天天摸鱼的java工程师2 天前
公司取消前端岗后,做了 10 年 Java 的我,第一次认真拥抱 AI
前端·后端·openai
西安小哥2 天前
AI与万物融合:从顶层设计到草根落地的全景图景
aigc·openai
gptAI_plus2 天前
TypeScript 7.0 已发布:大型项目迁移别只看提速,这 8 个兼容性问题更关键
chatgpt·openai
Miracleeee3 天前
OpenAI 官方教你怎么用 Codex,其实是在教你怎么写一份「Skill」
aigc·openai