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://依然会报错
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值