写一个在python中调用openai embedding接口的范例
时间: 2024-04-19 22:28:04 浏览: 14
要在Python中调用OpenAI的Embedding API,你需要使用`requests`库来发送HTTP请求。以下是一个使用OpenAI Embedding API的范例:
```python
import requests
import json
# 设置请求头
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY' # 替换为你的 OpenAI API 密钥
}
# 构建请求数据
data = {
'documents': [
'Hello, world!',
'How are you?'
]
}
# 发送 POST 请求
response = requests.post('https://api.openai.com/v1/engines/davinci-codex/completions', headers=headers, json=data)
# 解析响应结果
if response.status_code == 200:
result = response.json()
embeddings = result['choices'][0]['logprobs']['top_logprobs'][0]['tokens']
print(embeddings)
else:
print('Request failed with status code:', response.status_code)
```
在上面的代码中,你需要将`YOUR_API_KEY`替换为你的OpenAI API密钥。`data`字典中的`documents`键是一个包含文本的列表,你可以将你想要获取嵌入向量的文本放在这个列表中。
然后,我们使用`requests.post()`方法发送POST请求到OpenAI Embedding API的URL,并传递请求头和数据。如果请求成功,我们从响应结果中提取嵌入向量并打印出来。
请注意,这只是一个简单的示例,实际上,你可能需要根据你的具体需求进行更多的参数设置和结果处理。你可以参考OpenAI的文档来了解更多关于Embedding API的用法和参数说明。