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

完结!

相关推荐
怕浪猫3 小时前
第15章 安全、伦理与合规
langchain·openai·agent
悟空码字19 小时前
别再手搓CRUD了,用飞算JavaAI的“工程流水线“,助力高效开发
aigc·openai·ai编程
阿新聊ai1 天前
死磕claude code-Skill 不触发、乱触发、跑挂了:一份评测与调优指南
openai·ai编程
卡卡罗特AI1 天前
ChatGPT取消5小时限额,Codex终于可以疯狂造起来了!Anthropic最严厉的父亲来了!
chatgpt·openai·ai编程
武子康1 天前
OpenAI 把 Codex 接进 Claude Code:Coding Agent 从单兵工具进入协作系统
人工智能·openai·claude
武子康1 天前
GPT-5.6 Sol、Terra、Luna 怎么选?我的素材库项目为什么最终使用 Sol + Medium
人工智能·chatgpt·openai
TrisighT1 天前
Agent 聊了 20 轮 token 翻了 8 倍——三种截断方案实测,最蠢的那种反而最稳
aigc·openai·ai编程
云卷云舒___________1 天前
Grok CLI 泄密用户文件、Codex推理优化、GPT-5.6 Sol 登顶 Arena 前端榜 | 7月13日 AI日报
openai·codex·xai·ai日报·grokcli·gpt56sol·designarena
怕浪猫1 天前
第14章 性能优化与成本控制
openai·agent·ai编程
孟陬2 天前
高质量全方位的 AI 工具 sse-stuntman — Mock SSE 接口
前端·node.js·openai