使用python调用 openai接口

使用python调用 openai接口

调用 openai

大多数模型或者工具均支持以 openai api 方式调用,并不一定需要调用 openai。例如 deepseek 支持这种接口模式

安装依赖

pip install openai

随后就可以直接使用:



# 在终端中与智能助手聊天
from openai import OpenAI
 
 
# 指向本地服务器
client = OpenAI(base_url="http://127.0.0.1:1234/v1", api_key="lm-studio")
 
 
# 初始化历史记录列表,其中包含系统和用户的角色和内容
history = [
    {"role": "system", "content": "现在你是一名主播的助理,而且正在售卖一款二合一的包饺子神器,你需要对进入直播间的用户表达问候,比如要欢迎他,或者关心他,提示他查看商品,尽量要吸引他的注意,面对不同的用户,尽量要表达的有新意一点。而且欢迎词要注重简短,尽量在十个字以内,只要一句就行了,省略思考过程"},
    {"role": "user", "content": "现在用户111进入了直播间,你应该说什么欢迎他,只要一句话,省略思考过程"},
]


# 去除掉思考过程的完整回答内容。直接使用这个内容回答或者展示到窗口
def next_trans(txt):
    print(txt)



def think_trim_send(txt):
    if txt is None or txt == '':
        return
    if txt.strip().startswith('<think>'):
        send_txt = txt
        trip_index = txt.strip().find('</think>')
        if trip_index > 0:
            send_txt = send_txt[trip_index+len('</think>'):]
    else:
        send_txt = txt
    # 移除 think 标签后,将最终的内容发送过去。不需要思考过程。
    next_trans(send_txt.strip())


# 使用while循环不断地接收用户输入并提供回答
while True:
    # 创建聊天完成请求,指定模型、历史消息和其他参数
    completion = client.chat.completions.create(
        model="deepseek-ri-distill-qwen-14b",
        messages=history,
        temperature=0.7,
        stream=True,
    )
 
 
    # 初始化新消息字典,用于存储助手的回答
    new_message = {"role": "assistant", "content": ""}
 
 
    # 遍历完成请求的结果,并打印内容
    for chunk in completion:
        if chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)
            new_message["content"] += chunk.choices[0].delta.content
 
 
    # 将新消息添加到历史记录列表中
    history.append(new_message)
 
    # 将消息发送到直播间或进行额外处理
    think_trim_send(new_message.get('content'))
 
    # 如果需要查看聊天历史,可以取消注释以下代码
    # import json
    # gray_color = "\033[90m"
    # reset_color = "\033[0m"
    # print(f"{gray_color}\n{'-'*20} History dump {'-'*20}\n")
    # print(json.dumps(history, indent=2))
    # print(f"\n{'-'*55}\n{reset_color}")
 
 
    # 打印空行,并将用户的新输入作为消息添加到历史记录列表中
    print()
    history.append({"role": "user", "content": input("> ")})

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://zwc365.com/2025/03/29/shi-yong-python-diao-yong-openai-jie-kou

Buy me a cup of coffee ☕.