首先安装conda
安装Python 3.12 (低版本的可能缺少openai库)
conda create -n py312 python=3.12
conda activate py312
然后 pip install openai
提示:
Installing collected packages: openai
Successfully installed openai-1.35.8
VScode编写程序
import openai# optional; defaults to `os.environ['OPENAI_API_KEY']`
openai.api_key = "sk-nA7n2IpRLTxDNoIWCd0cF1F165Fc4eDdB4CaBb5b7cB2Cd8a"
openai.base_url = "http://192.168.1.235:3001/v1/"openai.default_headers = {"x-foo": "true"}completion = openai.chat.completions.create(model="qwen2",messages=[{"role": "user","content": "这句话是什么意思:柔情似水,佳期如梦?",},],
)
print(completion.choices[0].message.content)
注意这个代码 采用openai 1.0.0以上的API,使用说明,升级说明参考这里
https://github.com/openai/openai-python/discussions/742
返回结果:
================================
错误处理:
pip install openai报错:
HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.
解决办法:
pip install openai --proxy=http://192.168.1.231:8086
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
或者多执行几次