0Pricing
Vector Databases: Pinecone, Weaviate & pgvector · 课时

使用嵌入应用程序接口

学习集成并使用 OpenAI 和 Hugging Face 等提供商提供的嵌入生成服务。

使用嵌入应用程序接口 是 CoddyKit 上的免费 Vector Databases: Pinecone, Weaviate & pgvector 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Vector Databases: Pinecone, Weaviate & pgvector 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Vector Databases: Pinecone, Weaviate & pgvector 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What are Embedding APIs?

Embedding APIs are services that let you easily convert various types of data, like text or images, into vector embeddings.

Think of them as ready-to-use tools. Instead of building and training your own complex models, you send your data to the API, and it returns the numerical vector representation.

Why Use Embedding APIs?

Using an API for embeddings offers significant advantages, especially for beginners or those wanting quick integration:

  • Pre-trained Models: Access to powerful, state-of-the-art models without the need for training.
  • Ease of Use: Simple integration into your applications with just a few lines of code.
  • Scalability: The API provider handles the underlying infrastructure, allowing your application to scale easily.
  • Cost-Effective: Often more economical than maintaining your own models and hardware.

OpenAI: A Leading Provider

OpenAI is a well-known provider of AI models, including powerful embedding services. Their API makes it straightforward to generate high-quality embeddings.

A popular model they offer is text-embedding-ada-002, which is known for its balance of performance, versatility, and cost-effectiveness across many use cases.

OpenAI API: Initial Setup

To get started with OpenAI's embedding API, you'll need an API key from their website. It's crucial to keep this key confidential!

You'll also need to install the official Python client library. Open your terminal and run:

pip install openai

For security, always store your API key in an environment variable rather than directly in your code.

Generate Embeddings with OpenAI

This Python program demonstrates how to generate an embedding for a text using the OpenAI API. Remember to replace "YOUR_OPENAI_API_KEY_HERE" with your actual key.

import os
from openai import OpenAI

# Replace with your actual API key or set as environment variable
# client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
client = OpenAI(api_key="YOUR_OPENAI_API_KEY_HERE") # For demonstration

def get_openai_embedding(text, model="text-embedding-ada-002"):
    # OpenAI recommends replacing newlines with spaces for best results
    text = text.replace("\n", " ") 
    response = client.embeddings.create(input=[text], model=model)
    return response.data[0].embedding

if __name__ == "__main__":
    example_text = "CoddyKit makes learning to code easy and fun."
    embedding = get_openai_embedding(example_text)
    print(f"Text: '{example_text}'")
    print(f"Embedding length: {len(embedding)}")
    print(f"First 5 dimensions: {embedding[:5]}")

Hugging Face: Open-Source Models

Hugging Face is renowned for its vast hub of open-source machine learning models. They also provide an Inference API that allows you to use many of these models without complex local setup.

This is fantastic for experimenting with different models, especially various sentence transformer models that are excellent for text embeddings.

Embeddings with Hugging Face API

You can access the Hugging Face Inference API using standard HTTP requests. You'll need an API token from your Hugging Face account.

Here's a Python example using the requests library to get an embedding from a popular sentence transformer model.

import requests
import json
import os

# Replace with your Hugging Face API token or set as environment variable
# HF_API_TOKEN = os.environ.get("HF_API_TOKEN")
HF_API_TOKEN = "YOUR_HUGGINGFACE_API_TOKEN_HERE" # For demonstration

# Example model for sentence embeddings
API_URL = "https://api-inference.huggingface.co/models/sentence-transformers/all-MiniLM-L6-v2"
HEADERS = {"Authorization": f"Bearer {HF_API_TOKEN}"}

def query_hf_api(payload):
    response = requests.post(API_URL, headers=HEADERS, json=payload)
    return response.json()

if __name__ == "__main__":
    text_to_embed = "Mobile learning platforms are convenient."
    data = query_hf_api({"inputs": text_to_embed})

    if isinstance(data, list) and len(data) > 0 and isinstance(data[0], list):
        embedding = data[0]
        print(f"Text: '{text_to_embed}'")
        print(f"Embedding length: {len(embedding)}")
        print(f"First 5 dimensions: {embedding[:5]}")
    else:
        print(f"Error or unexpected response: {data}")
        print("Please check your API token and ensure the model is available.")

Secure Your API Keys!

API keys are like passwords for your services. Always handle them with extreme care:

  • Environment Variables: The most secure method is to store keys as environment variables, never hardcode them.
  • Version Control: Never commit API keys directly into your code repository (e.g., Git, GitHub).
  • Access Control: Limit who has access to your API keys and rotate them regularly if your provider allows.

Costs & Rate Limits

When using embedding APIs, be aware of:

  • Pricing Models: Most APIs charge per token or per character processed. Costs can vary significantly between models and providers. Always check their pricing pages.
  • Rate Limits: APIs often have limits on the number of requests you can make per minute or second. Exceeding these limits can lead to temporary blocks or errors.
  • Model Choice: Different models offer different performance vs. cost trade-offs. Choose a model that fits your application's requirements and budget.

API Benefits Check

Which of the following are key benefits of using a third-party Embedding API (like OpenAI or Hugging Face) compared to training your own model locally?

Recap: Using Embedding APIs

In this lesson, you learned how to leverage embedding generation services from providers like OpenAI and Hugging Face:

  • We explored the benefits of using pre-trained models via APIs for convenience and scalability.
  • You saw practical Python examples for integrating with both OpenAI and Hugging Face Inference APIs to generate text embeddings.
  • We discussed crucial aspects like API key security, understanding costs, and rate limits.

These APIs are powerful tools for quickly integrating semantic understanding into your applications, enabling features like semantic search, recommendations, and more!

常见问题解答

「使用嵌入应用程序接口」课时是免费的吗?

是的 — 「使用嵌入应用程序接口」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Vector Databases: Pinecone, Weaviate & pgvector 课程的其余内容,请升级到 CoddyKit PRO。 Vector Databases: Pinecone, Weaviate & pgvector 课程共包含 4 节课。

「使用嵌入应用程序接口」这节课中我会学到什么?

学习集成并使用 OpenAI 和 Hugging Face 等提供商提供的嵌入生成服务。 你通过在浏览器中直接运行的动手代码来练习 Vector Databases: Pinecone, Weaviate & pgvector,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Vector Databases: Pinecone, Weaviate & pgvector 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Vector Databases: Pinecone, Weaviate & pgvector 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「使用嵌入应用程序接口」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Vector Databases: Pinecone, Weaviate & pgvector 课中编写并运行代码吗?

能。每节 Vector Databases: Pinecone, Weaviate & pgvector 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 文本嵌入模型
  2. 使用嵌入应用程序接口
  3. 存储与更新嵌入
  4. 为更好的嵌入拆分文本
← 返回 Vector Databases: Pinecone, Weaviate & pgvector