import streamlit as st import requests import json import subprocess import os import time # 启动Node.js后端服务 if not st.session_state.get('node_started'): node_process = subprocess.Popen(['npm', 'run', 'start'], cwd=os.getcwd(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) st.session_state.node_started = True time.sleep(2) # 等待服务启动 # Streamlit配置 st.set_page_config(page_title="Dify2OpenAI", layout="wide", page_icon="🚀") # 侧边栏配置 with st.sidebar: st.header("API配置") api_key = st.text_input("API密钥", type="password") dify_url = st.text_input("Dify服务地址", "https://api.dify.ai") bot_type = st.selectbox("机器人类型", ["Chat", "Completion", "Workflow"]) # 主界面 st.title("Dify OpenAI 接口适配器") # 根据机器人类型显示不同输入组件 if bot_type == "Chat": messages = st.text_area("对话历史 (JSON格式)", height=200, value=json.dumps([{"role": "user", "content": "你好"}], ensure_ascii=False)) elif bot_type == "Completion": prompt = st.text_area("输入提示", height=150) elif bot_type == "Workflow": workflow_input = st.text_area("工作流输入参数 (JSON格式)", height=200) # 通用参数配置 with st.expander("高级配置"): temperature = st.slider("温度参数", 0.0, 2.0, 1.0) max_tokens = st.number_input("最大token数", min_value=1, value=2000) if st.button("提交请求"): try: headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } payload = { "model": f"dify|{bot_type}|{dify_url}", "temperature": temperature, "max_tokens": max_tokens } if bot_type == "Chat": payload["messages"] = json.loads(messages) elif bot_type == "Completion": payload["prompt"] = prompt elif bot_type == "Workflow": payload.update(json.loads(workflow_input)) response = requests.post( "http://localhost:3099/v1/chat/completions", headers=headers, json=payload ) if response.status_code == 200: st.success("请求成功") st.json(response.json()) else: st.error(f"请求失败:{response.status_code}") st.text(response.text) except Exception as e: st.error(f"发生错误:{str(e)}")