OpenAI Client使用
2024-08-20
安装依赖
bash
pip install openai
curl 发出请求
bash
curl ${OPENAI_BASE_URL}/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "填写模型名",
"messages": [{"role": "user", "content": "Say this is a test!"}],
"temperature": 0.7
}'
Python SDK 调用
流式请求
python
from openai import OpenAI
client = OpenAI(base_url="xxx", api_key="sk-xxx")
stream = client.chat.completions.create(
model="替换成具体的模型名",
messages=[{"role": "user", "content": "Say this is a test"}],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
标准请求
python
from openai import OpenAI
client = OpenAI(base_url="xxx", api_key="sk-xxx")
response = client.chat.completions.create(
model="替换成具体的模型名",
messages=[{"role": "user", "content": "Say this is a test"}],
)
print(response.choices[0].message.content)