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

完结!

相关推荐
营赢盈英10 小时前
Allow anonymous access to my Azure OpenAI chat bot
ai·openai·azure·webapps
网络研究院2 天前
解码 OpenAI 的 o1 系列大型语言模型
人工智能·语言模型·自然语言处理·openai·技术·推理·能力
营赢盈英2 天前
OpenAI GPT-3 API error: “You must provide a model parameter“
chatgpt·gpt-3·openai·swift
营赢盈英2 天前
OpenAI API key not working in my React App
javascript·ai·openai·reactjs·chatbot
营赢盈英2 天前
Using OpenAI API from Firebase Cloud Functions in flutter app
ai·node.js·openai·googlecloud·firebase
营赢盈英5 天前
404 error when doing workload anlysis using locust on OpenAI API (GPT.35)
人工智能·python·openai·locust
CaiYongji5 天前
深度!程序员生涯的垃圾时间(上)
人工智能·gpt·chatgpt·openai
营赢盈英6 天前
How to see if openAI (node js) createModeration response “flagged“ is true
javascript·ai·node.js·openai·api
营赢盈英7 天前
How to handle the response OpenAI Text-To-Speech API in Node.js?
ai·node.js·openai·openai api·response
营赢盈英9 天前
Azure OpenAI models being unable to correctly identify model
ai·openai·azure·azure ai