# app.py import gradio as gr import os import gradio as gr import modelscope_studio as mgr from http import HTTPStatus import dashscope from dashscope import Generation from dashscope.api_entities.dashscope_response import Role from typing import List, Optional, Tuple, Dict from urllib.error import HTTPError default_system = 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' YOUR_API_TOKEN = os.getenv('YOUR_API_TOKEN') dashscope.api_key = YOUR_API_TOKEN History = List[Tuple[str, str]] Messages = List[Dict[str, str]] latex_delimiters = [{ "left": "\\(", "right": "\\)", "display": True }, { "left": "\\begin\{equation\}", "right": "\\end\{equation\}", "display": True }, { "left": "\\begin\{align\}", "right": "\\end\{align\}", "display": True }, { "left": "\\begin\{alignat\}", "right": "\\end\{alignat\}", "display": True }, { "left": "\\begin\{gather\}", "right": "\\end\{gather\}", "display": True }, { "left": "\\begin\{CD\}", "right": "\\end\{CD\}", "display": True }, { "left": "\\[", "right": "\\]", "display": True }] def clear_session() -> History: return '', [] def modify_system_session(system: str) -> str: if system is None or len(system) == 0: system = default_system return system, system, [] def history_to_messages(history: History, system: str) -> Messages: messages = [{'role': Role.SYSTEM, 'content': system}] for h in history: messages.append({'role': Role.USER, 'content': h[0].text}) messages.append({'role': Role.ASSISTANT, 'content': h[1].text}) return messages def messages_to_history(messages: Messages) -> Tuple[str, History]: assert messages[0]['role'] == Role.SYSTEM system = messages[0]['content'] history = [] for q, r in zip(messages[1::2], messages[2::2]): history.append([q['content'], r['content']]) return system, history def model_chat(query: Optional[str], history: Optional[History], system: str, radio: str ) -> Tuple[str, str, History, str]: if query is None: query = '' if history is None: history = [] messages = history_to_messages(history, system) messages.append({'role': Role.USER, 'content': query}) label_model = f"qwen2.5-{radio.lower()}-instruct" gen = Generation.call( model=label_model, messages=messages, result_format='message', stream=True ) for response in gen: if response.status_code == HTTPStatus.OK: role = response.output.choices[0].message.role response = response.output.choices[0].message.content system, history = messages_to_history(messages + [{'role': role, 'content': response}]) yield '', history, system else: raise ValueError('Request id: %s, Status code: %s, error code: %s, error message: %s' % ( response.request_id, response.status_code, response.code, response.message )) def chiose_radio(radio, system): mark_ = gr.Markdown(value=f"