You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python终端与Oobabooga WebUI交互?求代码示例

用Python终端与Oobabooga WebUI交互的可行方案

前提:开启WebUI的API服务

启动Oobabooga WebUI时必须启用API,否则无法通过Python调用:

  • 终端启动:在启动命令后添加--api参数,比如python server.py --api
  • 启动器启动:在设置界面勾选"Enable API"选项,默认API端口为5000(可在设置中修改)

基础文本生成代码(适配Wizard系列模型)

以下代码通过API调用完成单次文本生成,适合指令类模型:

import requests

# 替换为你的WebUI API地址,默认端口5000
API_URL = "http://localhost:5000/api/v1/generate"

def generate_response(prompt):
    payload = {
        "prompt": prompt,
        "max_new_tokens": 250,
        "temperature": 0.7,
        "top_p": 0.9,
        "stop": ["\nUser:", "\nAssistant:"],  # 匹配模型的对话分隔符
        "mode": "instruct",
        "instruction_template": "WizardLM"  # 对应模型的指令模板
    }

    res = requests.post(API_URL, json=payload)
    if res.status_code == 200:
        return res.json()['results'][0]['text'].strip()
    return f"请求失败,状态码: {res.status_code}"

# 使用示例
prompt = "User: 解释一下量子纠缠的基本原理\nAssistant:"
print(generate_response(prompt))

持续对话交互代码(适配Pygmalion系列模型)

适合角色扮演类模型的多轮对话场景:

import requests

API_URL = "http://localhost:5000/api/v1/chat"

def chat(user_input, history=None):
    if history is None:
        history = []
    
    payload = {
        "user_input": user_input,
        "history": history,
        "mode": "chat",
        "character": "",  # 可替换为WebUI中加载的角色名
        "instruction_template": "Pygmalion",
        "max_new_tokens": 200,
        "temperature": 0.8,
        "top_p": 0.95
    }

    res = requests.post(API_URL, json=payload)
    if res.status_code == 200:
        response = res.json()['response']
        # 更新对话历史
        history.extend([
            {"role": "user", "content": user_input},
            {"role": "assistant", "content": response}
        ])
        return response, history
    return f"请求失败,状态码: {res.status_code}", history

# 启动对话循环
print("输入'退出'结束对话")
chat_history = None
while True:
    msg = input("你: ")
    if msg.lower() == '退出':
        break
    assistant_msg, chat_history = chat(msg, chat_history)
    print(f"助手: {assistant_msg}")

关键注意事项

  • 确保WebUI已成功加载目标模型(Wizard/Pygmalion),且启动过程无报错
  • 停止词(stop参数)需匹配模型的格式规范,可参考模型卡片说明调整
  • 指令模板(instruction_template)要与模型对应,WebUI的"Model"页面可查看可用模板列表
  • 若修改过API端口,需同步更新代码中的API_URL

内容的提问来源于stack exchange,提问作者NzltZ3301

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 22:47:30