【OpenAI】Embeddings 接口实例代码

以下是一个PHP代码示例,用于向OpenAI的Embeddings API发送请求。请注意,您需要提供API密钥才能进行身份验证。您还需要在请求正文中包括要嵌入的文本。

OpenAI的Embeddings API是一种自然语言处理工具,可以将文本转换为向量表示形式。 这些向量被认为是“语义空间”中的点,其中包含文本之间的相似性关系。 通过使用Embeddings API,您可以轻松地比较和分析不同的文本,并找到它们之间的共同点和区别。 例如,您可以使用此API来开发文本分类器、语义搜索引擎或词汇扩展工具等。

<?php

// OpenAI Embeddings API endpoint
$api_url = "https://api.openai.com/v1/embeddings";

// Your API key
$api_key = "YOUR_API_KEY_GOES_HERE";

// Text to be embedded
$text = "This is the text that you want to embed.";

// Request body
$request_body = array(
    "model" => "text-embedding",
    "document" => $text
);

// Initialize cURL session
$ch = curl_init($api_url);

// Set request options
curl_setopt_array($ch, array(
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
        "Authorization: Bearer " . $api_key
    ),
    CURLOPT_POSTFIELDS => json_encode($request_body)
));

// Execute the API request
$result = curl_exec($ch);

// Check for errors
if(curl_error($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    // Display the API response
    var_dump(json_decode($result, true));
}

// Close the cURL session
curl_close($ch);

?>

这个示例代码中的每一行都有注释,以便您更好地理解它。请确保将YOUR_API_KEY_GOES_HERE替换为您的实际API密钥。

猜你喜欢

转载自blog.csdn.net/u012240615/article/details/129995717
今日推荐