OPENAI API 使用学习
OPENAI KEY 使用方法
1. 环境设置
(1) 安装 openai 包
pip install openai
(2) 密钥设置
setx OPENAI_API_KEY "your_api_key_here"
可以不使用这个方法,在函数中设置API key。
2. 使用方法
(1) 生成文本
#Create a human-like response to a prompt
from openai import OpenAI
client = OpenAI()
#client = OpenAI(api_key='key' )
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{
"role": "user",
"content": "Write a haiku about recursion in programming."
}
]
)
print(completion.choices[0].message)
(2) 创造向量嵌入
#Create vector embeddings for a string of text
from openai import OpenAI
client = OpenAI()
response = client.embeddings.create(
model="text-embedding-3-large",
input="The food was delicious and the waiter..."
)
print(response)
(3) 生成图片
链接: link
3.异常处理
httpcore.ConnectError: TLS/SSL connection has been closed (EOF) (_ssl.c:1135)
httpx.ConnectError: TLS/SSL connection has been closed (EOF) (_ssl.c:1135)
openai.APIConnectionError: Connection error.
import os
os.environ["http_proxy"] = "http://localhost:10809"
os.environ["https_proxy"] = "http://localhost:10809" #注意不是https://,https://依然会报错