diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bcab4cb15e86c10db3cb8e017e4264202478ed0c --- /dev/null +++ b/.gitignore @@ -0,0 +1,208 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[codz] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST +run.sh + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py.cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# UV +# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +#uv.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock +#poetry.toml + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python. +# https://pdm-project.org/en/latest/usage/project/#working-with-version-control +#pdm.lock +#pdm.toml +.pdm-python +.pdm-build/ + +# pixi +# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control. +#pixi.lock +# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one +# in the .venv directory. It is recommended not to include this directory in version control. +.pixi + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.envrc +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +# Abstra +# Abstra is an AI-powered process automation framework. +# Ignore directories containing user credentials, local state, and settings. +# Learn more at https://abstra.io/docs +.abstra/ + +# Visual Studio Code +# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore +# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore +# and can be added to the global gitignore or merged into this file. However, if you prefer, +# you could uncomment the following to ignore the entire vscode folder +# .vscode/ + +# Ruff stuff: +.ruff_cache/ + +# PyPI configuration file +.pypirc + +# Cursor +# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to +# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data +# refer to https://docs.cursor.com/context/ignore-files +.cursorignore +.cursorindexingignore + +# Marimo +marimo/_static/ +marimo/_lsp/ +__marimo__/ diff --git a/README.md b/README.md index fd866d880009299767c638b91128d16776e487d9..9ba00167ff304fdb683d7a5a9e669d269a001022 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ --- -title: Arena +title: BigCodeArena emoji: ๐Ÿš€ colorFrom: pink colorTo: yellow sdk: gradio sdk_version: 5.44.1 app_file: app.py -pinned: false +pinned: true license: apache-2.0 --- diff --git a/api_config.yaml b/api_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3384a69c63f65bbba2dadebf199d6aac91a6ed67 --- /dev/null +++ b/api_config.yaml @@ -0,0 +1,216 @@ +gpt-4o-mini-2024-07-18: + model: gpt-4o-mini-2024-07-18 + endpoints: null + api_type: openai + parallel: 32 + max_tokens: 8192 + temperature: 0.0 + +gpt-4o-2024-11-20: + model: gpt-4o-2024-11-20 + endpoints: null + api_type: openai + parallel: 32 + max_tokens: 8192 + temperature: 0.0 + +# o1-2024-12-17: +# model: o1-2024-12-17 +# endpoints: null +# api_type: openai +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# o4-mini-2025-04-16: +# model: o4-mini-2025-04-16 +# endpoints: null +# api_type: openai_thinking +# parallel: 32 +# max_tokens: 8192 +# temperature: 1.0 + +# o3-mini-2025-01-31: +# model: o3-mini-2025-01-31 +# endpoints: null +# api_type: openai_thinking +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# gemini-2.0-flash-001: +# model: google/gemini-2.0-flash-001 +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai +# parallel: 32 +# max_tokens: 81920 +# temperature: 0.0 + +# gemini-2.5-pro: +# model: google/gemini-2.5-pro +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# gemini-2.5-flash: +# model: google/gemini-2.5-flash +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# claude35_haiku: +# model: bedrock/anthropic.claude-3-5-haiku-20241022-v1:0 +# endpoints: null +# api_type: litellm +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# claude35_sonnet: +# model: bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0 +# endpoints: null +# api_type: litellm +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# claude37_sonnet: +# model: bedrock/us.anthropic.claude-3-7-sonnet-20250219-v1:0 +# endpoints: null +# api_type: litellm +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# qwen3-coder: +# model: qwen/qwen3-coder +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# kimi-k2: +# model: moonshotai/kimi-k2 +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# claude-4-sonnet: +# model: bedrock/us.anthropic.claude-sonnet-4-20250514-v1:0 +# endpoints: null +# api_type: litellm +# parallel: 16 +# max_tokens: 8192 +# temperature: 0.0 + +# claude-4-opus: +# model: bedrock/us.anthropic.claude-opus-4-20250514-v1:0 +# endpoints: null +# api_type: litellm +# parallel: 16 +# max_tokens: 8192 +# temperature: 0.0 + +# gpt-oss-120b: +# model: openai/gpt-oss-120b +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai_thinking +# parallel: 32 +# max_tokens: 8192 +# temperature: 1.0 + +# gpt-oss-20b: +# model: openai/gpt-oss-20b +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai_thinking +# parallel: 32 +# max_tokens: 8192 +# temperature: 1.0 + +# deepseek-chat-v3-0324: +# model: deepseek/deepseek-chat-v3-0324 +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# deepseek-chat-v3.1: +# model: deepseek-chat +# endpoints: +# - api_base: https://api.deepseek.com +# api_key: ${DEEPSEEK_API_KEY} +# api_type: openai +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# glm-4.5: +# model: z-ai/glm-4.5 +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + +# gpt-4.1-2025-04-14: +# model: gpt-4.1-2025-04-14 +# endpoints: null +# api_type: openai +# parallel: 32 +# max_tokens: 8192 +# temperature: 0.0 + + +# deepseek-r1-0528: +# model: deepseek/deepseek-r1-0528 +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai_thinking +# parallel: 32 +# max_tokens: 81920 +# temperature: 1.0 + +# gpt-5-2025-08-07: +# model: gpt-5-2025-08-07 +# endpoints: null +# api_type: openai_thinking +# parallel: 32 +# max_tokens: 8192 +# temperature: 1.0 + +# grok-code: +# model: x-ai/grok-code-fast-1 +# endpoints: +# - api_base: https://openrouter.ai/api/v1 +# api_key: ${OPENROUTER_API_KEY} +# api_type: openai_thinking +# parallel: 32 +# max_tokens: 8192 +# temperature: 1.0 \ No newline at end of file diff --git a/app.py b/app.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b38f114057da28af833c9f6a1292ea38f9689d --- /dev/null +++ b/app.py @@ -0,0 +1,777 @@ +""" +Simple BigCodeArena - A simplified AI coding battle arena +Focuses on core functionality: two models, automatic code extraction, and execution +""" + +import gradio as gr +from gradio_sandboxcomponent import SandboxComponent + +# Import completion utilities +from completion import make_config, registered_api_completion + +# Import code extraction utilities +from sandbox.code_analyzer import ( + SandboxEnvironment, + extract_code_from_markdown, +) + +# Import sandbox execution functions +from sandbox.code_runner import ( + run_html_sandbox, + run_react_sandbox, + run_vue_sandbox, + run_pygame_sandbox, + run_gradio_sandbox, + run_streamlit_sandbox, + run_code_interpreter, + run_c_code, + run_cpp_code, + run_java_code, + run_golang_code, + run_rust_code, + mermaid_to_html +) + +# Create a proper sandbox state structure +def create_sandbox_state() -> dict: + """Create a new sandbox state for a model""" + return { + 'enable_sandbox': True, + 'enabled_round': 0, + 'sandbox_run_round': 0, + 'edit_round': 0, + 'sandbox_environment': SandboxEnvironment.AUTO, + 'auto_selected_sandbox_environment': None, + 'sandbox_instruction': "Run the extracted code in the appropriate sandbox environment", + 'code_to_execute': "", + 'code_dependencies': ([], []), + 'btn_list_length': 5, + 'sandbox_id': None, + 'chat_session_id': None, + 'conv_id': None, + "sandbox_output": None, + "sandbox_error": None, + } + +def reset_sandbox_state(state: dict) -> dict: + """Reset the sandbox state""" + state['enabled_round'] = 0 + state['sandbox_run_round'] = 0 + state['edit_round'] = 0 + state['auto_selected_sandbox_environment'] = None + state['code_to_execute'] = "" + state['code_dependencies'] = ([], []) + state['sandbox_error'] = None + state['sandbox_output'] = None + state['sandbox_id'] = None + state['conv_id'] = None + state['chat_session_id'] = None + return state + +# Load API configuration +def load_api_config(): + """Load API configuration from yaml file""" + try: + config = make_config("api_config.yaml") + return config + except Exception as e: + print(f"Error loading API config: {e}") + return {} + +# Global variables +api_config = load_api_config() +available_models = list(api_config.keys()) if api_config else [] + +def get_random_models(): + """Get two random models from available models""" + if len(available_models) < 2: + return available_models[0] if available_models else None, available_models[0] if available_models else None + + import random + models = random.sample(available_models, 2) + return models[0], models[1] + +def create_chat_state(model_name: str) -> dict: + """Create a new chat state for a model""" + return { + "model_name": model_name, + "messages": [], + "sandbox_state": create_sandbox_state() + } + +def generate_response_with_completion(state, temperature, max_tokens): + """Generate response using the completion API system with full conversation history""" + if state is None: + return state, "" + + # Get the last user message + user_message = None + for msg in reversed(state["messages"]): + if msg["role"] == "user": + user_message = msg["content"] + break + + if not user_message: + return state, "" + + # Prepare messages for API call - include full conversation history + messages = [] + for msg in state["messages"]: + if msg["role"] in ["user", "assistant"] and msg["content"] is not None: + messages.append({"role": msg["role"], "content": msg["content"]}) + + # Get model config + model_name = state["model_name"] + if model_name not in api_config: + print(f"Model {model_name} not found in config") + return state, f"Error: Model {model_name} not configured" + + model_config = api_config[model_name] + api_type = model_config.get("api_type", "openai") + + # retrieve the api completion function from register + api_completion_func = registered_api_completion[api_type] + + # build arguments for api completions + # Use the actual model identifier from config, not the display name + actual_model = model_config.get("model", model_name) + kwargs = { + "model": actual_model, + "temperature": temperature, + "max_tokens": max_tokens, + "api_dict": model_config.get("endpoints", [{}])[0] if model_config.get("endpoints") else None, + "messages": messages, + } + output = api_completion_func(**kwargs) + + # Extract the answer from the response + if isinstance(output, dict) and "answer" in output: + response_text = output["answer"] + return state, response_text + else: + error_msg = f"Error: Invalid response format from {api_type}" + print(error_msg) + return state, error_msg + +def extract_and_execute_code(message, sandbox_state): + """Extract code from message and prepare for execution""" + if not message: + return sandbox_state, "", "" + + # Extract code using the same logic as code_runner.py + extract_result = extract_code_from_markdown( + message=message, + enable_auto_env=True + ) + + if extract_result is None: + return sandbox_state, "", "" + + code, code_language, code_dependencies, env_selection = extract_result + + # Update sandbox state (now a dictionary) + sandbox_state['code_to_execute'] = code + sandbox_state['code_dependencies'] = code_dependencies + sandbox_state['auto_selected_sandbox_environment'] = env_selection + + return sandbox_state, code, str(env_selection) + +def add_text_and_generate(state0, state1, text, temperature, max_tokens, model_a, model_b): + """Add text and generate responses for both models""" + if not text.strip(): + return state0, state1, "", "", "", "", "", "", "", "", "", "", "", "" + + # Initialize states if needed + if state0 is None or state1 is None: + if state0 is None: + state0 = create_chat_state(model_a) + if state1 is None: + state1 = create_chat_state(model_b) + print(f"Models: {state0['model_name']} vs {state1['model_name']}") + + # Add user message to both states + state0["messages"].append({"role": "user", "content": text}) + state1["messages"].append({"role": "user", "content": text}) + + # Generate responses + state0, response0 = generate_response_with_completion(state0, temperature, max_tokens) + state1, response1 = generate_response_with_completion(state1, temperature, max_tokens) + + # Add the assistant responses to the message history + state0["messages"].append({"role": "assistant", "content": response0}) + state1["messages"].append({"role": "assistant", "content": response1}) + + # Format chat history for display + chat0 = format_chat_history(state0["messages"]) + chat1 = format_chat_history(state1["messages"]) + + # Extract code from responses for sandbox + sandbox_state0 = state0.get("sandbox_state", create_sandbox_state()) + sandbox_state1 = state1.get("sandbox_state", create_sandbox_state()) + + _, code0, env0 = extract_and_execute_code(response0, sandbox_state0) + _, code1, env1 = extract_and_execute_code(response1, sandbox_state1) + + # Update sandbox states in the main states + state0["sandbox_state"] = sandbox_state0 + state1["sandbox_state"] = sandbox_state1 + + # Clear previous sandbox outputs when new message is sent + sandbox_output0 = "" + sandbox_output1 = "" + sandbox_component_update0 = gr.update(visible=False) + sandbox_component_update1 = gr.update(visible=False) + + # Also clear the sandbox view components to show fresh results + sandbox_view_a = "" + sandbox_view_b = "" + + if code0.strip(): + # Get the dependencies from the sandbox state + dependencies0 = sandbox_state0.get('code_dependencies', ([], [])) + print(f"DEBUG: Running code0 with dependencies: {dependencies0}") + sandbox_url0, sandbox_output0, sandbox_error0 = run_sandbox_code(sandbox_state0, code0, dependencies0) + print(f"DEBUG: Code0 result - URL: {sandbox_url0}, Output: {sandbox_output0[:100] if sandbox_output0 else 'None'}, Error: {sandbox_error0[:100] if sandbox_error0 else 'None'}") + + # Check if this is a web-based environment that should use SandboxComponent + env_type = sandbox_state0.get('auto_selected_sandbox_environment') or sandbox_state0.get('sandbox_environment') + print(f"DEBUG: Model A environment type: {env_type}") + # Use the URL directly from the function return + if sandbox_url0: + sandbox_component_update0 = gr.update(value=(sandbox_url0, True, []), visible=True) + + # Update sandbox view with output and errors + if sandbox_output0: + sandbox_view_a += f"# Output\n{sandbox_output0}" + if sandbox_error0: + sandbox_view_a += f"# Errors\n{sandbox_error0}" + + if code1.strip(): + # Get the dependencies from the sandbox state + dependencies1 = sandbox_state1.get('code_dependencies', ([], [])) + print(f"DEBUG: Running code1 with dependencies: {dependencies1}") + sandbox_url1, sandbox_output1, sandbox_error1 = run_sandbox_code(sandbox_state1, code1, dependencies1) + print(f"DEBUG: Code1 result - URL: {sandbox_url1}, Output: {sandbox_output1[:100] if sandbox_output1 else 'None'}, Error: {sandbox_error1[:100] if sandbox_error1 else 'None'}") + + # Check if this is a web-based environment that should use SandboxComponent + env_type = sandbox_state1.get('auto_selected_sandbox_environment') or sandbox_state1.get('sandbox_environment') + print(f"DEBUG: Model B environment type: {env_type}") + # Use the URL directly from the function return + if sandbox_url1: + sandbox_component_update1 = gr.update(value=(sandbox_url1, True, []), visible=True) + + if sandbox_output1: + sandbox_view_b += f"## Output\n{sandbox_output1}" + if sandbox_error1: + sandbox_view_b += f"## Errors\n{sandbox_error1}" + + # Calculate conversation statistics + turn_count_a = len([msg for msg in state0["messages"] if msg["role"] == "assistant" and msg["content"]]) + turn_count_b = len([msg for msg in state1["messages"] if msg["role"] == "assistant" and msg["content"]]) + + # Format conversation statistics + chat_stats_a = f"**Conversation:** {turn_count_a} turns | **Total Messages:** {len(state0['messages'])}" + chat_stats_b = f"**Conversation:** {turn_count_b} turns | **Total Messages:** {len(state1['messages'])}" + + return state0, state1, chat0, chat1, response0, response1, code0, code1, env0, env1, sandbox_state0, sandbox_state1, sandbox_output0, sandbox_output1, sandbox_component_update0, sandbox_component_update1, chat_stats_a, chat_stats_b, sandbox_view_a, sandbox_view_b + +def format_chat_history(messages): + """Format messages for chat display with turn numbers""" + formatted = [] + + for msg in messages: + if msg["role"] == "user" and msg["content"]: + # Add turn number to user messages + formatted.append({ + "role": "user", + "content": msg['content'] + }) + elif msg["role"] == "assistant" and msg["content"]: + # Add turn number to assistant messages + formatted.append({ + "role": "assistant", + "content": msg['content'] + }) + + return formatted + +def clear_chat(state0, state1): + """Clear chat history""" + if state0 and "sandbox_state" in state0: + reset_sandbox_state(state0["sandbox_state"]) + if state1 and "sandbox_state" in state1: + reset_sandbox_state(state1["sandbox_state"]) + + # Get current model names for display + model_a, model_b = get_random_models() + + return None, None, "", "", "", "", "", "", "", "", "", "", "", "", gr.update(visible=False), gr.update(visible=False), "**Conversation:** 0 turns | **Total Messages:** 0", "**Conversation:** 0 turns | **Total Messages:** 0", "", "", f"**Model A:** {model_a}", f"**Model B:** {model_b}" + +def run_sandbox_code(sandbox_state: dict, code: str, dependencies: tuple) -> tuple[str, str, str]: + """Run code in the appropriate sandbox environment""" + if not code.strip(): + return "", "", "No code to run" + + # Update sandbox state + sandbox_state['code_to_execute'] = code + sandbox_state['code_dependencies'] = dependencies + + # Determine environment + env = sandbox_state.get('auto_selected_sandbox_environment') or sandbox_state.get('sandbox_environment') + + try: + if env == SandboxEnvironment.HTML: + sandbox_url, sandbox_id, stderr = run_html_sandbox(code, dependencies, sandbox_state.get('sandbox_id')) + sandbox_state['sandbox_id'] = sandbox_id + return sandbox_url, "", stderr + + elif env == SandboxEnvironment.REACT: + result = run_react_sandbox(code, dependencies, sandbox_state.get('sandbox_id')) + sandbox_state['sandbox_id'] = result['sandbox_id'] + return result['sandbox_url'], "", result['stderr'] + + elif env == SandboxEnvironment.VUE: + result = run_vue_sandbox(code, dependencies, sandbox_state.get('sandbox_id')) + sandbox_state['sandbox_id'] = result['sandbox_id'] + return result['sandbox_url'], "", result['stderr'] + + elif env == SandboxEnvironment.PYGAME: + result = run_pygame_sandbox(code, dependencies, sandbox_state.get('sandbox_id')) + sandbox_state['sandbox_id'] = result['sandbox_id'] + return result['sandbox_url'], "", result['stderr'] + + elif env == SandboxEnvironment.GRADIO: + sandbox_url, sandbox_id, stderr = run_gradio_sandbox(code, dependencies, sandbox_state.get('sandbox_id')) + sandbox_state['sandbox_id'] = sandbox_id + return sandbox_url, "", stderr + + elif env == SandboxEnvironment.STREAMLIT: + sandbox_url, sandbox_id, stderr = run_streamlit_sandbox(code, dependencies, sandbox_state.get('sandbox_id')) + sandbox_state['sandbox_id'] = sandbox_id + return sandbox_url, "", stderr + + elif env == SandboxEnvironment.MERMAID: + # Convert Mermaid to HTML and run in HTML sandbox + html_code = mermaid_to_html(code, theme='light') + sandbox_url, sandbox_id, stderr = run_html_sandbox(html_code, dependencies, sandbox_state.get('sandbox_id')) + sandbox_state['sandbox_id'] = sandbox_id + return sandbox_url, "", stderr + + elif env == SandboxEnvironment.PYTHON_RUNNER: + output, stderr = run_code_interpreter(code, 'python', dependencies) + return "", output, stderr + + elif env == SandboxEnvironment.JAVASCRIPT_RUNNER: + html_code = javascript_to_html(code) + output, stderr = run_html_sandbox(html_code, dependencies, sandbox_state.get('sandbox_id')) + return "", output, stderr + + elif env == SandboxEnvironment.C_RUNNER: + output, stderr = run_c_code(code, sandbox_state.get('sandbox_id')) + return "", output, stderr + + elif env == SandboxEnvironment.CPP_RUNNER: + output, stderr = run_cpp_code(code, sandbox_state.get('sandbox_id')) + return "", output, stderr + + elif env == SandboxEnvironment.JAVA_RUNNER: + output, stderr = run_java_code(code, sandbox_state.get('sandbox_id')) + return "", output, stderr + + elif env == SandboxEnvironment.GOLANG_RUNNER: + output, stderr = run_golang_code(code, sandbox_state.get('sandbox_id')) + return "", output, stderr + + elif env == SandboxEnvironment.RUST_RUNNER: + output, stderr = run_rust_code(code, sandbox_state.get('sandbox_id')) + return "", output, stderr + + else: + # Fallback to Python runner + output, stderr = run_code_interpreter(code, 'python', dependencies) + return "", output, stderr + + except Exception as e: + return "", "", str(e) + + + +def build_ui(): + """Build a UI for the coding arena with integrated sandbox""" + + # Get random models for this session + model_a, model_b = get_random_models() + + with gr.Blocks(title="BigCodeArena") as demo: + gr.Markdown("# BigCodeArena - Start Your Vibe Coding!") + + # Model display (non-interactive) + with gr.Row(): + with gr.Column(): + model_display_a = gr.Markdown(f"**Model A:** {model_a}", visible=False) + with gr.Column(): + model_display_b = gr.Markdown(f"**Model B:** {model_b}", visible=False) + + # Sandbox section with tabs for each model - Collapsible and open by default + with gr.Accordion("๐Ÿ—๏ธ Code Execution & Sandbox", open=True): + + with gr.Row(): + # Model A Sandbox + with gr.Column(): + gr.Markdown("### Model A Sandbox") + with gr.Tabs(): + with gr.Tab("View"): + sandbox_view_a = gr.Markdown("**Sandbox output will appear here automatically**") + sandbox_component_a = SandboxComponent( + value=("", False, []), + label="Model A Sandbox", + visible=False + ) + with gr.Tab("Code"): + code_a = gr.Code( + label="Extracted Code", + language="python", + lines=8, + interactive=False + ) + + # Model B Sandbox + with gr.Column(): + gr.Markdown("### Model B Sandbox") + with gr.Tabs(): + with gr.Tab("View"): + sandbox_view_b = gr.Markdown("**Sandbox output will appear here automatically**") + sandbox_component_b = SandboxComponent( + value=("", False, []), + label="Model B Sandbox", + visible=False + ) + with gr.Tab("Code"): + code_b = gr.Code( + label="Extracted Code", + language="python", + lines=8, + interactive=False + ) + + # Main chat interface - Collapsible and hidden by default + with gr.Accordion("๐Ÿ’ฌ Chat Interface", open=False): + with gr.Row(): + with gr.Column(): + gr.Markdown("## Model A") + chatbot_a = gr.Chatbot( + label="Model A", + height=300, + show_copy_button=True, + type="messages" + ) + chat_stats_a = gr.Markdown("**Conversation:** 0 turns") + + with gr.Column(): + gr.Markdown("## Model B") + chatbot_b = gr.Chatbot( + label="Model B", + height=300, + show_copy_button=True, + type="messages" + ) + chat_stats_b = gr.Markdown("**Conversation:** 0 turns") + + # Input section + with gr.Row(): + text_input = gr.Textbox( + label="Enter your coding prompt", + placeholder="e.g., 'Write a Python function to calculate fibonacci numbers'", + lines=1 + ) + + # Control buttons + with gr.Row(): + send_btn = gr.Button("๐Ÿš€ Send to Both Models", variant="primary", size="lg") + clear_btn = gr.Button("๐Ÿ—‘๏ธ Clear Chat", variant="secondary") + refresh_models_btn = gr.Button("๐Ÿ”„ New Random Models", variant="secondary") + + # Advanced Settings (Collapsible) + with gr.Accordion("โš™๏ธ Advanced Settings", open=False): + with gr.Row(): + with gr.Column(scale=1): + temperature = gr.Slider( + minimum=0.0, + maximum=1.0, + value=0.7, + step=0.1, + label="Temperature" + ) + with gr.Column(scale=1): + max_tokens = gr.Slider( + minimum=100, + maximum=4000, + value=1000, + step=100, + label="Max Tokens" + ) + + # Event handlers + # Create state variables for the run buttons + state0_var = gr.State() + state1_var = gr.State() + + # Create response components (hidden but needed for outputs) + response_a = gr.Markdown("", visible=False) + response_b = gr.Markdown("", visible=False) + + # Create a wrapper function that handles both the main execution and state update + def send_and_update_state(state0, state1, text, temp, max_tok, model_a, model_b): + print(f"DEBUG: send_and_update_state called with text: {text[:50] if text else 'None'}") + # Call the main function + result = add_text_and_generate(state0, state1, text, temp, max_tok, model_a, model_b) + # Extract the state from the result + new_state0, new_state1 = result[0], result[1] + print(f"DEBUG: send_and_update_state returning new_state0: {type(new_state0)}, new_state1: {type(new_state1)}") + # Return all the original outputs plus the updated state for run buttons + # Make sure all outputs are properly formatted for their expected types + return ( + new_state0, # state0 + new_state1, # state1 + result[2], # chatbot_a (chat0) + result[3], # chatbot_b (chat1) + result[4], # response_a (response0) + result[5], # response_b (response1) + result[6], # code_a (code0) + result[7], # code_b (code1) + result[10], # sandbox_state0 + result[11], # sandbox_state1 + result[12], # sandbox_output0 + result[13], # sandbox_output1 + result[14], # sandbox_component_update0 + result[15], # sandbox_component_update1 + result[16], # chat_stats_a + result[17], # chat_stats_b + result[18], # sandbox_view_a + result[19], # sandbox_view_b + new_state0, # state0_var + new_state1, # state1_var + "", # Clear text input + f"**Model A:** {model_a}", # Update model display A + f"**Model B:** {model_b}", # Update model display B + ) + + send_btn.click( + fn=send_and_update_state, + inputs=[ + state0_var, # state0 + state1_var, # state1 + text_input, + temperature, + max_tokens, + gr.State(model_a), # Use fixed model A + gr.State(model_b) # Use fixed model B + ], + outputs=[ + state0_var, # state0 + state1_var, # state1 + chatbot_a, + chatbot_b, + response_a, + response_b, + code_a, + code_b, + gr.State(), # sandbox_state0 + gr.State(), # sandbox_state1 + sandbox_view_a, # sandbox output for model A + sandbox_view_b, # sandbox output for model B + sandbox_component_a, # sandbox component for model A + sandbox_component_b, # sandbox component for model B + chat_stats_a, # Conversation statistics for model A + chat_stats_b, # Conversation statistics for model B + sandbox_view_a, # Sandbox view for model A + sandbox_view_b, # Sandbox view for model B + state0_var, # Updated state for run button A + state1_var, # Updated state for run button B + text_input, # Clear the text input after sending + model_display_a, # Update model display A + model_display_b, # Update model display B + ] + ) + + clear_btn.click( + fn=clear_chat, + inputs=[gr.State(), gr.State()], + outputs=[ + gr.State(None), + gr.State(None), + chatbot_a, + chatbot_b, + response_a, + response_b, + code_a, + code_b, + gr.State(None), + gr.State(None), + sandbox_view_a, + sandbox_view_b, + sandbox_component_a, + sandbox_component_b, + state0_var, # Reset state for run button A + state1_var, # Reset state for run button B + chat_stats_a, # Reset conversation statistics for model A + chat_stats_b, # Reset conversation statistics for model B + sandbox_view_a, # Reset sandbox view for model A + sandbox_view_b, # Reset sandbox view for model B + model_display_a, # Reset model display A + model_display_b, # Reset model display B + ] + ) + + # Refresh models button handler + def refresh_models(): + new_model_a, new_model_b = get_random_models() + return ( + None, # Reset state0 + None, # Reset state1 + "", # Clear chat A + "", # Clear chat B + "", # Clear response A + "", # Clear response B + "", # Clear code A + "", # Clear code B + gr.State(None), # Reset sandbox state A + gr.State(None), # Reset sandbox state B + "", # Clear sandbox view A + "", # Clear sandbox view B + gr.update(visible=False), # Hide sandbox component A + gr.update(visible=False), # Hide sandbox component B + "**Conversation:** 0 turns | **Total Messages:** 0", # Reset stats A + "**Conversation:** 0 turns | **Total Messages:** 0", # Reset stats B + "", # Clear sandbox view A + "", # Clear sandbox view B + None, # Reset state0_var + None, # Reset state1_var + f"**Model A:** {new_model_a}", # Update model display A + f"**Model B:** {new_model_b}", # Update model display B + ) + + refresh_models_btn.click( + fn=refresh_models, + inputs=[], + outputs=[ + state0_var, + state1_var, + chatbot_a, + chatbot_b, + response_a, + response_b, + code_a, + code_b, + gr.State(None), + gr.State(None), + sandbox_view_a, + sandbox_view_b, + sandbox_component_a, + sandbox_component_b, + chat_stats_a, + chat_stats_b, + sandbox_view_a, + sandbox_view_b, + state0_var, + state1_var, + model_display_a, # Update model display A + model_display_b, # Update model display B + ] + ) + + # Examples + gr.Examples( + examples=[ + ["ไฝฟ็”จSVG็ป˜ๅˆถๆ˜ฅ่Š‚ไธป้ข˜็š„ๅŠจๆ€ๅ›พๆกˆ๏ผŒๅŒ…ๆ‹ฌ๏ผš1๏ผ‰ไธ€ไธช็บข่‰ฒ็š„็ฏ็ฌผ๏ผŒๅธฆๆœ‰้‡‘่‰ฒ็š„ๆต่‹ 2๏ผ‰ไธ€ไธช้‡‘่‰ฒ็š„็ฆๅญ—๏ผŒไฝฟ็”จไนฆๆณ•ๅญ—ไฝ“ 3๏ผ‰่ƒŒๆ™ฏๆทปๅŠ ไธ€ไบ›็ƒŸ่Šฑๆ•ˆๆžœ 4๏ผ‰ๅœจ็ฏ็ฌผๅ’Œ็ฆๅญ—ๅ‘จๅ›ดๆทปๅŠ ไธ€ไบ›็ฅฅไบ‘ๅ›พๆกˆใ€‚็กฎไฟๅ›พๆกˆๅธƒๅฑ€็พŽ่ง‚๏ผŒ้ขœ่‰ฒๆญ้…็ฌฆๅˆๆ˜ฅ่Š‚ไผ ็ปŸ้ฃŽๆ ผใ€‚"], + ["SVGใ‚’ไฝฟ็”จใ—ใฆๆ—ฅๆœฌใฎไผ็ตฑ็š„ใชๅ’ŒๆŸ„ใƒ‘ใ‚ฟใƒผใƒณใ‚’ๆ็”ปใ—ใฆใใ ใ•ใ„ใ€‚1๏ผ‰ๆณข็ด‹๏ผˆใ•ใ–ใชใฟ๏ผ‰ๆจกๆง˜ 2๏ผ‰ๅธ‚ๆพๆจกๆง˜ 3๏ผ‰้บปใฎ่‘‰ๆจกๆง˜ 4๏ผ‰้›ทๆ–‡๏ผˆใ‚‰ใ„ใ‚‚ใ‚“๏ผ‰ๆจกๆง˜ใ‚’ๅซใ‚ใฆใใ ใ•ใ„ใ€‚่‰ฒใฏไผ็ตฑ็š„ใชๆ—ฅๆœฌใฎ่‰ฒ๏ผˆ่—่‰ฒใ€ๆœฑ่‰ฒใ€้‡‘่‰ฒใชใฉ๏ผ‰ใ‚’ไฝฟ็”จใ—ใ€ใƒฌใ‚คใ‚ขใ‚ฆใƒˆใฏใƒใƒฉใƒณใ‚นใ‚ˆใ้…็ฝฎใ—ใฆใใ ใ•ใ„ใ€‚"], + ["Write HTML with P5.js that simulates 25 particles in a vacuum space of a cylindrical container, bouncing within its boundaries. Use different colors for each ball and ensure they leave a trail showing their movement. Add a slow rotation of the container to give better view of what's going on in the scene. Make sure to create proper collision detection and physic rules to ensure particles remain in the container. Add an external spherical container. Add a slow zoom in and zoom out effect to the whole scene."], + ["Write a Python script to scrape NVIDIA's stock price for the past month using the yfinance library. Clean the data and create an interactive visualization using Matplotlib. Include: 1) A candlestick chart showing daily price movements 2) A line chart with 7-day and 30-day moving averages. Add hover tooltips showing exact values and date. Make the layout professional with proper titles and axis labels."], + ["Write a Python script that uses the Gradio library to create a functional calculator. The calculator should support basic arithmetic operations: addition, subtraction, multiplication, and division. It should have two input fields for numbers and a dropdown menu to select the operation."], + ["Write a Todo list app using React.js. The app should allow users to add, delete, and mark tasks as completed. Include features like filtering tasks by status (completed, active), sorting tasks by priority, and displaying the total number of tasks."], + ["Write a Python script using the Streamlit library to create a web application for uploading and displaying files. The app should allow users to upload files of type .csv or .txt. If a .csv file is uploaded, display its contents as a table using Streamlit's st.dataframe() method. If a .txt file is uploaded, display its content as plain text."], + ["Write a Python function to solve the Trapping Rain Water problem. The function should take a list of non-negative integers representing the height of bars in a histogram and return the total amount of water trapped between the bars after raining. Use an efficient algorithm with a time complexity of O(n)."], + ["Create a simple Pygame script for a game where the player controls a bouncing ball that changes direction when it collides with the edges of the window. Add functionality for the player to control a paddle using arrow keys, aiming to keep the ball from touching the bottom of the screen. Include basic collision detection and a scoring system that increases as the ball bounces off the paddle. You need to add clickable buttons to start the game, and reset the game."], + ["Create a financial management Dashboard using Vue.js, focusing on local data handling without APIs. Include features like a clean dashboard for tracking income and expenses, dynamic charts for visualizing finances, and a budget planner. Implement functionalities for adding, editing, and deleting transactions, as well as filtering by date or category. Ensure responsive design and smooth user interaction for an intuitive experience."], + ["Create a Mermaid diagram to visualize a flowchart of a user login process. Include the following steps: User enters login credentials; Credentials are validated; If valid, the user is directed to the dashboard; If invalid, an error message is shown, and the user can retry or reset the password."], + ["Write a Python function to calculate the Fibonacci sequence up to n numbers. Then write test cases to verify the function works correctly for edge cases like negative numbers, zero, and large inputs."], + ["Build an HTML page for a Kanban board with three columns with Vue.js: To Do, In Progress, and Done. Each column should allow adding, moving, and deleting tasks. Implement drag-and-drop functionality using Vue Draggable and persist the state using Vuex."], + ["Develop a Streamlit app that takes a CSV file as input and provides: 1) Basic statistics about the data 2) Interactive visualizations using Plotly 3) A data cleaning interface with options to handle missing values 4) An option to download the cleaned data."], + ["Write an HTML page with embedded JavaScript that creates an interactive periodic table. Each element should display its properties on hover and allow filtering by category (metals, non-metals, etc.). Include a search bar to find elements by name or symbol."], + ["Here's a Python function that sorts a list of dictionaries by a specified key:\n\n```python\ndef sort_dicts(data, key):\n return sorted(data, key=lambda x: x[key])\n```\n\nWrite test cases to verify the function works correctly for edge cases like empty lists, missing keys, and different data types. If you use unittest, please use `unittest.main(argv=['first-arg-is-ignored'], exit=False)` to run the tests."], + ["Create a React component for a fitness tracker that shows: 1) Daily step count 2) Calories burned 3) Distance walked 4) A progress bar for daily goals."], + ["Build a Vue.js dashboard for monitoring server health. Include: 1) Real-time CPU and memory usage graphs 2) Disk space visualization 3) Network activity monitor 4) Alerts for critical thresholds."], + ["Write a C program that calculates and prints the first 100 prime numbers in a formatted table with 10 numbers per row. Include a function to check if a number is prime and use it in your solution."], + ["Write a C++ program that implements a simple calculator using object-oriented programming. Create a Calculator class with methods for addition, subtraction, multiplication, and division. Include error handling for division by zero."], + ["Write a Rust program that generates and prints a Pascal's Triangle with 10 rows. Format the output to center-align the numbers in each row."], + ["Write a Java program that simulates a simple bank account system. Create a BankAccount class with methods for deposit, withdrawal, and balance inquiry. Include error handling for insufficient funds and demonstrate its usage with a few transactions."], + ["Write a Go program that calculates and prints the Fibonacci sequence up to the 50th number. Format the output in a table with 5 numbers per row and include the index of each Fibonacci number."], + ["Write a C program that calculates and prints a histogram of letter frequencies from a predefined string. Use ASCII art to display the histogram vertically."], + ["Write a C++ program that implements a simple stack data structure with push, pop, and peek operations. Demonstrate its usage by reversing a predefined string using the stack."], + ["Write a Rust program that calculates and prints the first 20 happy numbers. Include a function to check if a number is happy and use it in your solution."], + ["Write a Java program that implements a simple binary search algorithm. Create a sorted array of integers and demonstrate searching for different values, including cases where the value is found and not found."], + ["Write a Go program that generates and prints a multiplication table from 1 to 12. Format the output in a neat grid with proper alignment."], + ], + example_labels=[ + "๐Ÿฎ ๆ˜ฅ่Š‚ไธป้ข˜ๅ›พๆกˆ", + "๐ŸŽŽ ๆ—ฅๆœฌใฎไผ็ตฑ็š„ใชๅ’ŒๆŸ„ใƒ‘ใ‚ฟใƒผใƒณ", + "๐ŸŒ Particles in a Spherical Container", + "๐Ÿ’น NVIDIA Stock Analysis with Matplotlib", + "๐Ÿงฎ Calculator with Gradio", + "๐Ÿ“ Todo List App with React.js", + "๐Ÿ“‚ File Upload Web App with Streamlit", + "๐Ÿ’ฆ Solve Trapping Rain Water Problem", + "๐ŸŽฎ Pygame Bouncing Ball Game", + "๐Ÿ’ณ Financial Dashboard with Vue.js", + "๐Ÿ”‘ User Login Process Flowchart", + "๐Ÿ”ข Fibonacci Sequence with Tests", + "๐Ÿ“Œ Vue Kanban Board", + "๐Ÿงน Streamlit Data Cleaning App", + "โš—๏ธ Interactive Periodic Table with React", + "๐Ÿ“š Dictionary Sorting Tests in Python", + "๐Ÿ‹๏ธโ€โ™‚๏ธ Fitness Tracker with React", + "๐Ÿ–ฅ๏ธ Vue Server Monitoring", + "๐Ÿ”ข Prime Numbers in C", + "๐Ÿงฎ OOP Calculator in C++", + "๐Ÿ”ท Pascal's Triangle in Rust", + "๐Ÿ›๏ธ Bank Account Simulation in Java", + "๐Ÿฐ Fibonacci Sequence in Go", + "๐Ÿ“Š Letter Frequency Histogram in C", + "๐Ÿ“ฆ Stack Implementation in C++", + "๐Ÿ˜„ Happy Numbers in Rust", + "๐Ÿ”Ž Binary Search in Java", + "โœ–๏ธ Multiplication Table in Go", + ], + examples_per_page=100, + label="Example Prompts", + inputs=[text_input], + ) + + return demo + +def main(): + """Main function to run the Simple BigCodeArena app""" + print("๐Ÿš€ Starting Simple BigCodeArena...") + if available_models: + print(f"๐Ÿ” Available models: {', '.join(available_models)}") + # Get random models for this session + model_a, model_b = get_random_models() + print(f"๐ŸŽฒ Randomly selected models for this session:") + print(f" Model A: {model_a}") + print(f" Model B: {model_b}") + else: + print("โš ๏ธ No models found in config!") + + # Build the UI + demo = build_ui() + + # Launch the app + demo.launch( + server_name="0.0.0.0", + server_port=7860, + share=False, + debug=True + ) + +if __name__ == "__main__": + main() diff --git a/chat_state.py b/chat_state.py new file mode 100644 index 0000000000000000000000000000000000000000..764802b2ebeff047e836b73abb0afda1aeb65b44 --- /dev/null +++ b/chat_state.py @@ -0,0 +1,259 @@ +''' +Chat State and Logging +''' + +import json +import os +from typing import Any, Literal, Optional +from conversation import Conversation + + +import datetime +import uuid + + +LOG_DIR = os.getenv("LOGDIR", "./logs") +''' +The default output dir of log files +''' + + +class ModelChatState: + ''' + The state of a chat with a model. + ''' + + is_vision: bool + ''' + Whether the model is vision based. + ''' + + conv: Conversation + ''' + The conversation + ''' + + conv_id: str + ''' + Unique identifier for the model conversation. + Unique per chat per model. + ''' + + chat_session_id: str + ''' + Unique identifier for the chat session. + Unique per chat. The two battle models share the same chat session id. + ''' + + skip_next: bool + ''' + Flag to indicate skipping the next operation. + ''' + + model_name: str + ''' + Name of the model being used. + ''' + + oai_thread_id: Optional[str] + ''' + Identifier for the OpenAI thread. + ''' + + has_csam_image: bool + ''' + Indicates if a CSAM image has been uploaded. + ''' + + regen_support: bool + ''' + Indicates if regeneration is supported for the model. + ''' + + chat_start_time: datetime.datetime + ''' + Chat start time. + ''' + + chat_mode: Literal['battle_anony', 'battle_named', 'direct'] + ''' + Chat mode. + ''' + + curr_response_type: Literal['chat_multi', 'chat_single', 'regenerate_multi', 'regenerate_single'] | None + ''' + Current response type. Used for logging. + ''' + + @staticmethod + def create_chat_session_id() -> str: + ''' + Create a new chat session id. + ''' + return uuid.uuid4().hex + + @staticmethod + def create_battle_chat_states( + model_name_1: str, model_name_2: str, + chat_mode: Literal['battle_anony', 'battle_named'], + is_vision: bool, + ) -> tuple['ModelChatState', 'ModelChatState']: + ''' + Create two chat states for a battle. + ''' + chat_session_id = ModelChatState.create_chat_session_id() + return ( + ModelChatState(model_name_1, chat_mode, + is_vision=is_vision, + chat_session_id=chat_session_id), + ModelChatState(model_name_2, chat_mode, + is_vision=is_vision, + chat_session_id=chat_session_id), + ) + + + def __init__(self, + model_name: str, + chat_mode: Literal['battle_anony', 'battle_named', 'direct'], + is_vision: bool, + chat_session_id: str | None = None, + ): + from fastchat.model.model_adapter import get_conversation_template + + self.conv = get_conversation_template(model_name) + self.conv_id = uuid.uuid4().hex + # if no chat session id is provided, use the conversation id + self.chat_session_id = chat_session_id if chat_session_id else self.conv_id + self.chat_start_time = datetime.datetime.now() + self.chat_mode = chat_mode + + self.skip_next = False + self.model_name = model_name + self.oai_thread_id = None + self.is_vision = is_vision + + # NOTE(chris): This could be sort of a hack since it assumes the user only uploads one image. If they can upload multiple, we should store a list of image hashes. + self.has_csam_image = False + + self.regen_support = True + if "browsing" in model_name: + self.regen_support = False + self.init_system_prompt(self.conv, is_vision) + + def init_system_prompt(self, conv, is_vision): + system_prompt = conv.get_system_message(is_vision) + if len(system_prompt) == 0: + return + current_date = datetime.datetime.now().strftime("%Y-%m-%d") + system_prompt = system_prompt.replace("{{currentDateTime}}", current_date) + + current_date_v2 = datetime.datetime.now().strftime("%d %b %Y") + system_prompt = system_prompt.replace("{{currentDateTimev2}}", current_date_v2) + + current_date_v3 = datetime.datetime.now().strftime("%B %Y") + system_prompt = system_prompt.replace("{{currentDateTimev3}}", current_date_v3) + conv.set_system_message(system_prompt) + + def set_response_type( + self, + response_type: Literal['chat_multi', 'chat_single', 'regenerate_multi', 'regenerate_single'] + ): + ''' + Set the response type for the chat state. + ''' + self.curr_response_type = response_type + + def to_gradio_chatbot(self): + ''' + Convert to a Gradio chatbot. + ''' + return self.conv.to_gradio_chatbot() + + def get_conv_log_filepath(self, path_prefix: str): + ''' + Get the filepath for the conversation log. + + Expected directory structure: + softwarearenlog/ + โ””โ”€โ”€ YEAR_MONTH_DAY/ + โ”œโ”€โ”€ conv_logs/ + โ””โ”€โ”€ sandbox_logs/ + ''' + date_str = self.chat_start_time.strftime('%Y_%m_%d') + filepath = os.path.join( + path_prefix, + date_str, + 'conv_logs', + self.chat_mode, + f"conv-log-{self.chat_session_id}.json" + ) + return filepath + + def to_dict(self): + base = self.conv.to_dict() + base.update( + { + "chat_session_id": self.chat_session_id, + "conv_id": self.conv_id, + "chat_mode": self.chat_mode, + "chat_start_time": self.chat_start_time, + "model_name": self.model_name, + } + ) + + if self.is_vision: + base.update({"has_csam_image": self.has_csam_image}) + return base + + def generate_vote_record( + self, + vote_type: str, + ip: str + ) -> dict[str, Any]: + ''' + Generate a vote record for telemertry. + ''' + data = { + "tstamp": round(datetime.datetime.now().timestamp(), 4), + "type": vote_type, + "model": self.model_name, + "state": self.to_dict(), + "ip": ip, + } + return data + + def generate_response_record( + self, + gen_params: dict[str, Any], + start_ts: float, + end_ts: float, + ip: str + ) -> dict[str, Any]: + ''' + Generate a vote record for telemertry. + ''' + data = { + "tstamp": round(datetime.datetime.now().timestamp(), 4), + "type": self.curr_response_type, + "model": self.model_name, + "start_ts": round(start_ts, 4), + "end_ts": round(end_ts, 4), + "gen_params": gen_params, + "state": self.to_dict(), + "ip": ip, + } + return data + + +def save_log_to_local( + log_data: dict[str, Any], + log_path: str, + write_mode: Literal['overwrite', 'append'] = 'append' +): + ''' + Save the log locally. + ''' + log_json = json.dumps(log_data, default=str) + os.makedirs(os.path.dirname(log_path), exist_ok=True) + with open(log_path, "w" if write_mode == 'overwrite' else 'a') as fout: + fout.write(log_json + "\n") diff --git a/completion.py b/completion.py new file mode 100644 index 0000000000000000000000000000000000000000..83ddae20f709f0f3f69ae83849bca3f1c962516b --- /dev/null +++ b/completion.py @@ -0,0 +1,1304 @@ +import os +import json +import time +import yaml +import random +import shortuuid + +import requests +from typing import Optional +import boto3 + +from glob import glob +from tqdm import tqdm + +# API setting constants +API_MAX_RETRY = 50 +API_RETRY_SLEEP = 10 +API_ERROR_OUTPUT = None + +registered_api_completion = {} +registered_engine_completion = {} + + +def register_api(api_type): + def decorator(func): + registered_api_completion[api_type] = func + return func + + return decorator + + +def register_engine(engine_type): + def decorator(func): + registered_engine_completion[engine_type] = func + return func + + return decorator + + +def load_questions(question_file: str): + """Load questions from a file.""" + questions = [] + with open(question_file, "r") as ques_file: + for line in ques_file: + if line: + questions.append(json.loads(line)) + return questions + +def load_model_answers(answer_dir: str): + """Load model answers. + + The return value is a python dict of type: + Dict[model_name: str -> Dict[uid: int -> answer: dict]] + """ + if not os.path.exists(answer_dir): + return {} + + filenames = [] + for folder in os.listdir(answer_dir): + if not os.path.isdir(os.path.join(answer_dir, folder)): + continue + if not os.path.exists(os.path.join(answer_dir, folder, "generation.jsonl")): + print(f"WARNING: {folder} does not have generation.jsonl, skip it.") + continue + filenames.append(os.path.join(answer_dir, folder, "generation.jsonl")) + + filenames.sort() + model_answers = {} + for filename in filenames: + # Use parent directory name as model name + model_name = os.path.basename(os.path.dirname(filename)) + answer = {} + with open(filename) as fin: + for line in fin: + line = json.loads(line) + answer[line["uid"]] = line + model_answers[model_name] = answer + return model_answers + + +def load_model_judgements(answer_dir: str): + """Load model judgements. + + The return value is a python dict of type: + Dict[model_name: str -> Dict[uid: int -> answer: dict]] + """ + filenames = glob(os.path.join(answer_dir, "*.jsonl")) + filenames.sort() + model_answers = {} + + for filename in filenames: + model_name = os.path.basename(filename)[:-6] + answer = {} + with open(filename) as fin: + for line in fin: + line = json.loads(line) + answer[line["uid"]] = line + model_answers[model_name] = answer + + return model_answers + + +def load_model_answers_and_execution_results(data_dir: str): + """Load model answers and execution results. + + The return value is a python dict of type: + Dict[model_name: str -> Dict[uid: int -> answer: dict]] + """ + filenames = [] + for folder in os.listdir(data_dir): + if not os.path.isdir(os.path.join(data_dir, folder)): + continue + if not os.path.exists(os.path.join(data_dir, folder, "execution_results.jsonl")): + print(f"WARNING: {folder} does not have execution_results.jsonl, skip it.") + continue + filenames.append(os.path.join(data_dir, folder, "execution_results.jsonl")) + + filenames.sort() + model_answers = {} + + for filename in filenames: + # Use parent directory name as model name + model_name = os.path.basename(os.path.dirname(filename)) + answer = {} + with open(filename) as fin: + for line in fin: + line = json.loads(line) + answer[line["uid"]] = line + model_answers[model_name] = answer + + return model_answers + + + +def load_id_to_model_answers(answer_dir: str): + """Load model answers. + + The return value is a python dict of type: + Dict[model_name: str -> Dict[uid: int -> answer: dict]] + """ + filenames = glob(os.path.join(answer_dir, "*.jsonl")) + filenames.sort() + model_answers = {} + + for filename in filenames: + model_name = os.path.basename(filename)[:-6] + + with open(filename) as fin: + for line in fin: + line = json.loads(line) + + if line["uid"] in model_answers: + model_answers[line["uid"]][model_name] = line + else: + model_answers[line["uid"]] = {model_name: line} + + return model_answers + + +def get_endpoint(endpoint_list): + if endpoint_list is None: + return None + assert endpoint_list is not None + # randomly pick one + api_dict = random.choices( + endpoint_list + )[0] + return api_dict + + +# load config args from config yaml files +def make_config(config_file: str) -> dict: + config_kwargs = {} + with open(config_file, "r") as f: + config_kwargs = yaml.load(f, Loader=yaml.SafeLoader) + + return config_kwargs + + +@register_api("openai") +def chat_completion_openai(model, messages, temperature, max_tokens, api_dict=None, **kwargs): + import openai + if api_dict: + client = openai.OpenAI( + base_url=api_dict["api_base"], + api_key=api_dict["api_key"], + ) + else: + client = openai.OpenAI() + + if api_dict and "model_name" in api_dict: + model = api_dict["model_name"] + + output = API_ERROR_OUTPUT + for _ in range(API_MAX_RETRY): + try: + completion = client.chat.completions.create( + model=model, + messages=messages, + temperature=temperature, + max_tokens=max_tokens, + ) + output = { + "answer": completion.choices[0].message.content + } + break + except openai.RateLimitError as e: + print(type(e), e) + time.sleep(API_RETRY_SLEEP) + except openai.BadRequestError as e: + print("=== DEBUG: OpenAI BadRequestError ===") + print("Error type:", type(e)) + print("Error message:", str(e)) + print("=== Analyzing messages for image issues ===") + for i, msg in enumerate(messages): + print(f"Message {i} role: {msg.get('role', 'unknown')}") + if "content" in msg: + content = msg["content"] + if isinstance(content, list): + for j, item in enumerate(content): + if isinstance(item, dict) and item.get("type") == "image_url": + url = item.get("image_url", {}).get("url", "") + if url.startswith("data:image/png;base64,"): + base64_part = url[22:] # Remove "data:image/png;base64," prefix + print(f" Image {j}: base64 length = {len(base64_part)}") + if len(base64_part) < 50: + print(f" *** ISSUE: Image {j} has very short/empty base64: '{url}'") + elif url.startswith("data:image/"): + print(f" Image {j}: Non-PNG data URL: {url[:50]}...") + else: + print(f" Image {j}: Unexpected URL format: {url[:50]}...") + elif isinstance(item, dict) and item.get("type") == "text": + text_content = item.get("text", "") + print(f" Text {j}: {len(text_content)} chars") + else: + print(f" Content {j}: {type(item)} - {str(item)[:50]}...") + else: + print(f" Content: {type(content)} - {str(content)[:100]}...") + print("=== End debug info ===") + break + except KeyError: + print(type(e), e) + break + + return output + + +@register_api("openai_streaming") +def chat_completion_openai_streaming(model, messages, temperature, max_tokens, api_dict=None, **kwargs): + """Streaming version of OpenAI completion that yields tokens as they arrive""" + import openai + if api_dict: + client = openai.OpenAI( + base_url=api_dict["api_base"], + api_key=api_dict["api_key"], + ) + else: + client = openai.OpenAI() + + if api_dict and "model_name" in api_dict: + model = api_dict["model_name"] + + try: + stream = client.chat.completions.create( + model=model, + messages=messages, + temperature=temperature, + max_tokens=max_tokens, + stream=True + ) + + for chunk in stream: + if chunk.choices[0].delta.content is not None: + yield chunk.choices[0].delta.content + + except Exception as e: + print(f"Error in streaming completion: {e}") + yield f"Error: {str(e)}" + + +@register_api("openai_thinking") +def chat_completion_openai_thinking(model, messages, api_dict=None, **kwargs): + import openai + + if api_dict: + client = openai.OpenAI( + api_key=api_dict["api_key"], + base_url=api_dict["api_base"], + ) + else: + client = openai.OpenAI() + + output = API_ERROR_OUTPUT + for i in range(API_MAX_RETRY): + try: + completion = client.chat.completions.create( + model=model, + messages=messages, + reasoning_effort=kwargs['reasoning_effort'] if 'reasoning_effort' in kwargs else 'medium', + + ) + output = { + "answer": completion.choices[0].message.content + } + break + except openai.RateLimitError as e: + print(type(e), e) + time.sleep(API_RETRY_SLEEP) + except openai.BadRequestError as e: + print("=== DEBUG: OpenAI BadRequestError ===") + print("Error type:", type(e)) + print("Error message:", str(e)) + print("=== Analyzing messages for image issues ===") + for i, msg in enumerate(messages): + print(f"Message {i} role: {msg.get('role', 'unknown')}") + if "content" in msg: + content = msg["content"] + if isinstance(content, list): + for j, item in enumerate(content): + if isinstance(item, dict) and item.get("type") == "image_url": + url = item.get("image_url", {}).get("url", "") + if url.startswith("data:image/png;base64,"): + base64_part = url[22:] # Remove "data:image/png;base64," prefix + print(f" Image {j}: base64 length = {len(base64_part)}") + if len(base64_part) < 50: + print(f" *** ISSUE: Image {j} has very short/empty base64: '{url}'") + elif url.startswith("data:image/"): + print(f" Image {j}: Non-PNG data URL: {url[:50]}...") + else: + print(f" Image {j}: Unexpected URL format: {url[:50]}...") + elif isinstance(item, dict) and item.get("type") == "text": + text_content = item.get("text", "") + print(f" Text {j}: {len(text_content)} chars") + else: + print(f" Content {j}: {type(item)} - {str(item)[:50]}...") + else: + print(f" Content: {type(content)} - {str(content)[:100]}...") + print("=== End debug info ===") + break + except KeyError: + print(type(e), e) + break + + return output + + +@register_api("deepseek_reasoner") +def chat_completion_deepseek_reasoner(messages, api_dict, **kwargs): + import urllib.request + + chat_endpoint_headers = { + "User-Agent": "curl/8.7.1", + "Authorization": "Bearer {}".format(api_dict['api_key']), + "Content-Type": "application/json", + "Accept": "application/json", + } + chat_endpoint_url = "https://api.deepseek.com/chat/completions" + + req_body = { + "messages": messages, + "model": "deepseek-reasoner", + "stream": False, + } + req_data = json.dumps(req_body).encode("utf-8") + + output = API_ERROR_OUTPUT + for i in range(API_MAX_RETRY): + try: + req = urllib.request.Request( + chat_endpoint_url, + headers = chat_endpoint_headers.copy(), + data = req_data, + ) + + with urllib.request.urlopen(req) as res: + res_data = res.read() + res_body = json.loads(res_data.decode("utf-8")) + + output = { + "thought": res_body["choices"][0]["message"]["reasoning_content"], + "answer": res_body["choices"][0]["message"]["content"], + } + break + except Exception as e: + print(type(e), e) + time.sleep(API_RETRY_SLEEP) + + return output + + +@register_api("deepseek") +def chat_completion_deepseek(messages, max_tokens, api_dict, **kwargs): + import urllib.request + + chat_endpoint_headers = { + "User-Agent": "curl/8.7.1", + "Authorization": "Bearer {}".format(api_dict['api_key']), + "Content-Type": "application/json", + "Accept": "application/json", + } + chat_endpoint_url = "https://api.deepseek.com/chat/completions" + + req_body = { + "messages": messages, + "model": "deepseek-chat", + "stream": False, + "max_tokens": max_tokens, + } + req_data = json.dumps(req_body).encode("utf-8") + + output = API_ERROR_OUTPUT + for i in range(API_MAX_RETRY): + try: + req = urllib.request.Request( + chat_endpoint_url, + headers = chat_endpoint_headers.copy(), + data = req_data, + ) + + with urllib.request.urlopen(req) as res: + res_data = res.read() + res_body = json.loads(res_data.decode("utf-8")) + + output = { + "answer": res_body["choices"][0]["message"]["content"], + } + break + except Exception as e: + print(type(e), e) + time.sleep(API_RETRY_SLEEP) + + return output + + +@register_api("anthropic") +def chat_completion_anthropic(model, messages, temperature, max_tokens, api_dict=None, **kwargs): + import anthropic + + if api_dict: + api_key = api_dict["api_key"] + else: + api_key = os.environ["ANTHROPIC_API_KEY"] + + sys_msg = "" + if messages[0]["role"] == "system": + sys_msg = messages[0]["content"] + messages = messages[1:] + + output = API_ERROR_OUTPUT + for _ in range(API_MAX_RETRY): + try: + c = anthropic.Anthropic(api_key=api_key) + response = c.messages.create( + model=model, + messages=messages, + stop_sequences=[anthropic.HUMAN_PROMPT], + max_tokens=max_tokens, + temperature=temperature, + system=sys_msg + ) + output = { + "answer": response.content[0].text + } + break + except anthropic.APIError as e: + print(type(e), e) + time.sleep(API_RETRY_SLEEP) + return output + + +@register_api("anthropic_thinking") +def chat_completion_anthropic_thinking(model, messages, max_tokens, budget_tokens, **kwargs): + import anthropic + + client = anthropic.Anthropic( + timeout=1200, + ) + + output = API_ERROR_OUTPUT + for _ in range(API_MAX_RETRY): + try: + response = client.messages.create( + model=model, + max_tokens=max_tokens, + thinking={ + "type": "enabled", + "budget_tokens": budget_tokens + }, + messages=messages, + ) + output = { + "thought": response.content[0].thinking, + "answer": response.content[1].text, + } + break + except anthropic.APIError as e: + print(type(e), e) + time.sleep(API_RETRY_SLEEP) + + return output + + +@register_api("mistral") +def chat_completion_mistral(model, messages, temperature, max_tokens, **kwargs): + from mistralai.client import MistralClient + from mistralai.models.chat_completion import ChatMessage + from mistralai.exceptions import MistralException + + api_key = os.environ["MISTRAL_API_KEY"] + client = MistralClient(api_key=api_key) + + prompts = [ChatMessage(role=message["role"], content=message["content"]) for message in messages] + + output = API_ERROR_OUTPUT + for _ in range(API_MAX_RETRY): + try: + chat_response = client.chat( + model=model, + messages=prompts, + temperature=temperature, + max_tokens=max_tokens, + ) + output = { + "answer": chat_response.choices[0].message.content + } + break + except MistralException as e: + print(type(e), e) + break + + return output + + +@register_api("xai") +def chat_completion_xai(model, messages, temperature, max_tokens, api_dict=None, **kwargs): + import xai_sdk + + client = xai_sdk.Client(api_key=api_dict['api_key'], api_host=api_dict['api_base']).compat + output = API_ERROR_OUTPUT + + for _ in range(API_MAX_RETRY): + try: + stream = client.chat.completions.create( + model=model, + messages=messages, + stream=True, + max_tokens=max_tokens, + temperature=temperature, + top_p=0.95, + ) + output_text = "" + for chunk in stream: + if chunk.choices[0].delta.content: + output_text += chunk.choices[0].delta.content + + output = { + "answer": output_text + } + break + except Exception as e: + print(type(e), e) + time.sleep(API_RETRY_SLEEP) + + return output + + +@register_api("litellm") +def chat_completion_litellm(model, messages, temperature, max_tokens, api_dict=None, **kwargs): + import litellm + + output = API_ERROR_OUTPUT + for _ in range(API_MAX_RETRY): + try: + response = litellm.completion( + model=model, + messages=messages, + temperature=temperature, + max_tokens=max_tokens, + ) + output = { + "answer": response.choices[0].message.content + } + break + except Exception as e: + print(type(e), e) + time.sleep(API_RETRY_SLEEP) + + return output + + +@register_api("litellm_streaming") +def chat_completion_litellm_streaming(model, messages, temperature, max_tokens, api_dict=None, **kwargs): + """Streaming version of litellm completion""" + import litellm + + try: + response = litellm.completion( + model=model, + messages=messages, + temperature=temperature, + max_tokens=max_tokens, + stream=True + ) + + for chunk in response: + if chunk.choices[0].delta.content is not None: + yield chunk.choices[0].delta.content + + except Exception as e: + print(f"Error in litellm streaming completion: {e}") + yield f"Error: {str(e)}" + + +@register_api("anthropic_streaming") +def chat_completion_anthropic_streaming(model, messages, temperature, max_tokens, api_dict=None, **kwargs): + """Streaming version of Anthropic completion""" + import anthropic + + if api_dict: + client = anthropic.Anthropic(api_key=api_dict["api_key"]) + else: + client = anthropic.Anthropic() + + try: + # Convert messages to Anthropic format + system_message = "" + conversation_messages = [] + + for msg in messages: + if msg["role"] == "system": + system_message = msg["content"] + else: + conversation_messages.append(msg) + + stream = client.messages.create( + model=model, + max_tokens=max_tokens, + temperature=temperature, + system=system_message if system_message else None, + messages=conversation_messages, + stream=True + ) + + for chunk in stream: + if chunk.type == "content_block_delta" and chunk.delta.text: + yield chunk.delta.text + + except Exception as e: + print(f"Error in Anthropic streaming completion: {e}") + yield f"Error: {str(e)}" + +@register_api("gemini") +def http_completion_gemini(model, messages, **kwargs): + import requests + + api_key = os.environ["GEMINI_API_KEY"] + + safety_settings = [ + { + "category": "HARM_CATEGORY_HARASSMENT", + "threshold": "BLOCK_NONE" + }, + { + "category": "HARM_CATEGORY_HATE_SPEECH", + "threshold": "BLOCK_NONE" + }, + { + "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "threshold": "BLOCK_NONE" + }, + { + "category": "HARM_CATEGORY_DANGEROUS_CONTENT", + "threshold": "BLOCK_NONE" + }, + ] + + sys_prompt = None + if messages[0]["role"] == "system": + sys_prompt = { + "parts":[ + {"text": messages[0]["content"]} + ] + } + messages = messages[1:] + + role_map = {"user": "user", + "assistant": "model"} + + conv = [{"parts":[{"text":turn["content"]}], "role":role_map[turn["role"]]} for turn in messages] + + json_request = { + "contents": conv, + "safetySettings": safety_settings, + "systemInstruction": sys_prompt, + } + + if "temperature" in kwargs and "max_tokens" in kwargs: + gen_config = { + "temperature": kwargs["temperature"], + "maxOutputTokens": kwargs["max_tokens"], + } + json_request["generationConfig"] = gen_config + elif "temperature" in kwargs: + gen_config = { + "temperature": kwargs["temperature"], + } + json_request["generationConfig"] = gen_config + elif "max_tokens" in kwargs: + gen_config = { + "maxOutputTokens": kwargs["max_tokens"], + } + json_request["generationConfig"] = gen_config + + output = API_ERROR_OUTPUT + for _ in range(API_MAX_RETRY): + try: + response = requests.post( + f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}", + json=json_request, + ) + except Exception as e: + print(f"**API REQUEST ERROR** Reason: {e}.") + time.sleep(API_RETRY_SLEEP) + if response.status_code != 200: + print(f"**API REQUEST ERROR** Reason: status code {response.status_code}.") + time.sleep(API_RETRY_SLEEP) + try: + output = { + "answer": response.json()["candidates"][0]["content"]["parts"][0]["text"], + } + except KeyError as e: + print(type(e), e) + print(response.json()) + return output + + +@register_api("vertex") +def vertex_completion_gemini(model, messages, project_id, regions, **kwargs): + import requests + import subprocess + + output = API_ERROR_OUTPUT + + # Obtain the access token using gcloud CLI + access_token = subprocess.check_output( + ["gcloud", "auth", "application-default", "print-access-token"], + text=True + ).strip() + + if messages[0]["role"] == "system": + data = { + "systemInstruction": { + "role": "system", # ignored by vertexi api (04/18/2025) + "parts": [{ + "text": messages[0]["content"] + }] + }, + } + messages = messages[1:] + else: + data = {} + + role_map = { + "user": "user", + "assistant": "model" + } + + messages = [{"parts":[{"text":turn["content"]}], "role":role_map[turn["role"]]} for turn in messages] + + url = ( + f"https://us-central1-aiplatform.googleapis.com/v1/projects/" + f"{project_id}/locations/{regions}/publishers/google/models/" + f"{model}:generateContent" + ) + + headers = { + "Authorization": f"Bearer {access_token}", + "Content-Type": "application/json", + } + + data = data | { + "contents": messages, + } + + if "temperature" in kwargs or "max_tokens" in kwargs: + gen_config = {} + if "temperature" in kwargs: + gen_config["temperature"] = kwargs["temperature"] + if "max_tokens" in kwargs: + gen_config["maxOutputTokens"] = kwargs["max_tokens"] + data["generationConfig"] = gen_config + + response = requests.post(url, json=data, headers=headers) + + try: + output = { + "answer": response.json()["candidates"][0]["content"]["parts"][0]["text"], + } + except KeyError as e: + print(type(e), e) + print(response.json()) + + return output + + +@register_api("cohere") +def chat_completion_cohere(model, messages, temperature, max_tokens, **kwargs): + import cohere + + co = cohere.Client(os.environ["COHERE_API_KEY"]) + assert len(messages) > 0 + + template_map = {"system":"SYSTEM", + "assistant":"CHATBOT", + "user":"USER"} + + assert messages[-1]["role"] == "user" + prompt = messages[-1]["content"] + + if len(messages) > 1: + history = [] + for message in messages[:-1]: + history.append({"role":template_map[message["role"]], "message":message["content"]}) + else: + history = None + + output = API_ERROR_OUTPUT + for _ in range(API_MAX_RETRY): + try: + response = co.chat( + message=prompt, + model=model, + temperature=temperature, + max_tokens=max_tokens, + chat_history=history, + ) + output = { + "answer": response.text + } + break + except cohere.core.api_error.ApiError as e: + print(type(e), e) + raise + except Exception as e: + print(type(e), e) + break + + return output + + +@register_api("meta") +def chat_completion_meta(model, messages, temperature, max_tokens, api_dict, **kwargs): + assert api_dict + texts = [{"role": m["role"], + "text": m["content"]} for m in messages] + + output = "" + for _ in range(API_MAX_RETRY): + try: + res = requests.post( + f"{api_dict['api_base']}/chat_stream_completions?access_token={api_dict['api_key']}", + stream=True, + headers={"Content-Type": "application/json"}, + json={ + "model": model, + "chunks_delimited": True, + "messages": texts, + "options": { + "max_tokens": max_tokens, + "generation_algorithm": "top_p", + "top_p": 1, + "temperature": temperature, + }, + }, + timeout=30, + ) + if res.status_code == 200: + for line in res.iter_lines(): + if line: + part = json.loads(line.decode("utf-8")) + if "text" in part: + output += part["text"] + break + else: + print(f"**API REQUEST ERROR** Code: {res.status_code}") + time.sleep(API_RETRY_SLEEP) + except Exception as e: + print("**API REQUEST ERROR** Reason: Unknown.") + time.sleep(API_RETRY_SLEEP) + continue + + return { + "answer": output + } + + +def batch_submit_sglang( + executor, + tokenizer, + temperature, + max_tokens, + all_context, + max_context_length=None, + end_think_token=None, +): + print(f"DEBUG: sglang_completion_qwq: max_context_length: {max_context_length}") + + sampling_params = { + "temperature": temperature, + "skip_special_tokens": False, + "max_new_tokens": max_tokens - 1, + "no_stop_trim": True, + } + + batch_prompt_token_ids = [] + batch_uids =[] + uid_to_prompt = {} + uid_to_response = {} + + for context in all_context: + prompt_token_ids = tokenizer.apply_chat_template( + context['turns'], + add_generation_prompt=True, + tokenize=True, + ) + + if max_context_length and (len(prompt_token_ids) + max_tokens) > max_context_length: + print(f"DEBUG: sglang_completion_qwq: context length ({len(prompt_token_ids) + max_tokens}) > max_context_length ({max_context_length}), skip this context") + continue + + batch_prompt_token_ids.append(prompt_token_ids) + batch_uids.append(context['uid']) + + uid_to_prompt[context['uid']] = context['turns'] + + err_msg = f"ERROR: len(batch_prompt_token_ids): {len(batch_prompt_token_ids)} != len(batch_uids): {len(batch_uids)}" + assert len(batch_prompt_token_ids) == len(batch_uids), err_msg + + _ = executor.submit( + prompt_token_ids=batch_prompt_token_ids, + sampling_params=[sampling_params] * len(batch_uids), + keys=batch_uids, + ) + + for request in tqdm(executor.as_completed(), total=len(batch_uids)): + uid = request.key() + result = request.result() + raw_response = tokenizer.decode( + result['output_ids'], + skip_special_tokens=True, + ) + + if end_think_token: + thought, _, ans = raw_response.partition(end_think_token) + if ans == "": + uid_to_response[uid] = {"thought": thought, "answer": raw_response} + else: + uid_to_response[uid] = {"thought": thought, "answer": ans} + else: + uid_to_response[uid] = {"answer": raw_response} + + # assert len(uid_to_response) == len(all_context), f"ERROR: len output ({len(uid_to_response)}) != len input ({len(all_context)})" + return uid_to_response + + +def _infer_cuda_tp_world_size(): + cuda_devices = os.environ.get("CUDA_VISIBLE_DEVICES", None) + if cuda_devices is None: + tp_world_size = 8 + else: + tp_world_size = len(cuda_devices.split(",")) + return tp_world_size + + +def download_model(model: str, max_workers: int = 64): + import subprocess + + env = os.environ.copy() + env["HF_HUB_ENABLE_HF_TRANSFER"] = "0" + + cmd = [ + "huggingface-cli", + "download", + f"--max-workers={max_workers}", + model + ] + + try: + subprocess.run(cmd, env=env, check=True) + print(f"Successfully downloaded model '{model}' with {max_workers} max workers.") + except subprocess.CalledProcessError as e: + print(f"Error occurred while downloading the model: {e}") + + +@register_engine("sglang") +def sglang_completion( + model, + batch_context, + answer_file, + temperature, + max_tokens=32768, + end_think_token=None, + **kwargs, +): + from transformers import AutoTokenizer + from utils.sglang_server import SGLangServerExecutor + import re + + tokenizer = AutoTokenizer.from_pretrained(model) + + uids = [context['uid'] for context in batch_context] + prompts = [context['instruction'] for context in batch_context] + code_envs = [context['environment'] for context in batch_context] + processed_context = [ + { + "uid": uids[i], + "turns": [{ + "content": prompts[i], + "role": "user", + }] + } + for i in tqdm(range(len(uids))) + ] + download_model(model=model) + + server_args = { + "model_path": model, + "dtype": "auto", + "tp_size": _infer_cuda_tp_world_size(), + "mem_fraction_static": 0.7, + "max_prefill_tokens": max_tokens, + "max_workers": 256, + "server_port": 30000, + } + + executor = SGLangServerExecutor( + **server_args, + ) + + print(f"DEBUG: sglang_completion: model: {model}") + + uid_to_response = batch_submit_sglang( + executor=executor, + tokenizer=tokenizer, + temperature=temperature, + max_tokens=max_tokens, + all_context=processed_context, + end_think_token=end_think_token, + ) + + executor.join() + print("DEBUG: sglang_completion: done, sleep 10 seconds...") + time.sleep(10) + + num_null = sum( + [uid_to_response[uid]['answer'] is None for uid in uids if uid in uid_to_response] + ) + print(f"Number of null responses: {num_null}") + + records = [] + for i, context in enumerate(processed_context): + uid = context['uid'] + if uid not in uid_to_response: + continue + + answer_data = uid_to_response[uid] + + record = { + "uid": uid, + "ans_id": shortuuid.uuid(), + "model": kwargs.get("model_display_name", model), + "messages": context['turns'] + [ + {"content": answer_data, "role": "assistant"} + ], + "environment": code_envs[i], + "tstamp": time.time(), + "metadata": {}, + } + + records.append(record) + + with open(answer_file, 'w', encoding='utf-8') as f: + for rec in records: + f.write(json.dumps(rec, ensure_ascii=True) + '\n') + + +@register_api("aws_claude") +def chat_completion_aws_bedrock_claude(messages, api_dict=None, aws_region="us-west-2", **kwargs): + """ + Call AWS Bedrock API for chat completion + + Args: + model (str): Model ID + conv (object): Conversation object containing messages + temperature (float): Temperature parameter for response generation + max_tokens (int): Maximum tokens in response + api_dict (dict, optional): API configuration dictionary + aws_region (str, optional): AWS region, defaults to "us-west-2" + + Returns: + str: Generated response text or error message + """ + + # Configure AWS client if api_dict provided + if api_dict is not None: + bedrock_rt_client = boto3.client( + service_name='bedrock-runtime', + region_name=aws_region, + aws_access_key_id=api_dict.get('aws_access_key_id'), + aws_secret_access_key=api_dict.get('aws_secret_access_key') + ) + else: + bedrock_rt_client = boto3.client( + service_name='bedrock-runtime', + region_name=aws_region,) + + output = API_ERROR_OUTPUT + + #get kwargs from settings + temperature= kwargs["temperature"] + max_tokens= kwargs["max_tokens"] + model = kwargs["model_id"] + + sys_msg = "" + if messages[0]["role"] == "system": + sys_msg = messages[0]["content"] + messages = messages[1:] + else: + prompt = messages[0]['content'] + + + # Retry logic for API calls + for _ in range(API_MAX_RETRY): + try: + # Prepare request body + prompt_json = { + "system": sys_msg, + "messages": messages, + "max_tokens": max_tokens, + "temperature": temperature, + "anthropic_version": "bedrock-2023-05-31", + "stop_sequences": ["Human"] + } + + # Call Bedrock API + response = bedrock_rt_client.invoke_model( + body=json.dumps(prompt_json), + modelId=model, + accept='application/json', + contentType='application/json' + ) + + # Parse response + response_body = json.loads(response.get('body').read()) + output = {"answer":response_body.get("content")[0].get("text")} + break + + except Exception as e: + print(type(e), e) + time.sleep(API_RETRY_SLEEP) + + return output + +@register_api("aws_mistral") +def chat_completion_aws_bedrock_mistral(messages, api_dict=None, aws_region="us-west-2", **kwargs): + """ + Call AWS Bedrock API for chat completion + + Args: + model (str): Model ID + conv (object): Conversation object containing messages + temperature (float): Temperature parameter for response generation + max_tokens (int): Maximum tokens in response + api_dict (dict, optional): API configuration dictionary + aws_region (str, optional): AWS region, defaults to "us-west-2" + + Returns: + str: Generated response text or error message + """ + + # Configure AWS client if api_dict provided + if api_dict is not None: + bedrock_rt_client = boto3.client( + service_name='bedrock-runtime', + region_name=aws_region, + aws_access_key_id=api_dict.get('aws_access_key_id'), + aws_secret_access_key=api_dict.get('aws_secret_access_key') + ) + else: + bedrock_rt_client = boto3.client( + service_name='bedrock-runtime', + region_name=aws_region,) + + output = API_ERROR_OUTPUT + + #get kwargs from settings + temperature= kwargs["temperature"] + max_tokens= kwargs["max_tokens"] + model = kwargs["model_id"] + + # Retry logic for API calls + for _ in range(API_MAX_RETRY): + try: + ## =============== Format prompt ================ + prompt = "\n".join([content for message in messages for content in message["content"]]) + formatted_prompt = f"[INST] {prompt.strip()} [/INST]" + body = { + "prompt": formatted_prompt, + "max_tokens": max_tokens, + "stop": ["Human:"], + "temperature": temperature, + } + + # Call Bedrock API + response = bedrock_rt_client.invoke_model( + body=json.dumps(body), + modelId=model, + accept='application/json', + contentType='application/json' + ) + + # Parse response + response_body = json.loads(response.get('body').read()) + + if "pixtral-large" in model: #us.mistral.pixtral-large-2502-v1:0 + output = {"answer": response_body.get("choices")[0].get("message").get("content")} + else: + output = {"answer": response_body.get("outputs")[0].get("text")} + + break + + except Exception as e: + print(type(e), e) + time.sleep(API_RETRY_SLEEP) + + return output + + +@register_api("mistral_streaming") +def chat_completion_mistral_streaming(model, messages, temperature, max_tokens, api_dict=None, **kwargs): + """Streaming version of Mistral completion""" + import openai + + if api_dict: + client = openai.OpenAI( + base_url=api_dict["api_base"], + api_key=api_dict["api_key"], + ) + else: + client = openai.OpenAI() + + try: + stream = client.chat.completions.create( + model=model, + messages=messages, + temperature=temperature, + max_tokens=max_tokens, + stream=True + ) + + for chunk in stream: + if chunk.choices[0].delta.content is not None: + yield chunk.choices[0].delta.content + + except Exception as e: + print(f"Error in Mistral streaming completion: {e}") + yield f"Error: {str(e)}" + + +@register_api("gemini_streaming") +def chat_completion_gemini_streaming(model, messages, **kwargs): + """Streaming version of Gemini completion""" + import google.generativeai as genai + + try: + # Configure the API + genai.configure(api_key=os.environ.get("GEMINI_API_KEY")) + + # Create model + model_genai = genai.GenerativeModel(model) + + # Convert messages to Gemini format + conversation = model_genai.start_chat(history=[]) + + # Get the last user message + last_user_message = None + for msg in messages: + if msg["role"] == "user": + last_user_message = msg["content"] + + if not last_user_message: + yield "Error: No user message found" + return + + # Stream the response + response = conversation.send_message(last_user_message, stream=True) + + for chunk in response: + if chunk.text: + yield chunk.text + + except Exception as e: + print(f"Error in Gemini streaming completion: {e}") + yield f"Error: {str(e)}" diff --git a/conversation.py b/conversation.py new file mode 100644 index 0000000000000000000000000000000000000000..8f30cf916447843526ea3ee9f35fd86d39c440f4 --- /dev/null +++ b/conversation.py @@ -0,0 +1,2354 @@ +""" +Conversation prompt templates. + +We kindly request that you import fastchat instead of copying this file if you wish to use it. +If you have any changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates. +""" + +import base64 +import dataclasses +from enum import auto, IntEnum +from io import BytesIO +import os +from typing import List, Any, Dict, Union, Tuple + + +class SeparatorStyle(IntEnum): + """Separator styles.""" + + ADD_COLON_SINGLE = auto() + ADD_COLON_TWO = auto() + ADD_COLON_SPACE_SINGLE = auto() + NO_COLON_SINGLE = auto() + NO_COLON_TWO = auto() + ADD_NEW_LINE_SINGLE = auto() + LLAMA2 = auto() + LLAMA3 = auto() + CHATGLM = auto() + CHATML = auto() + CHATINTERN = auto() + DOLLY = auto() + RWKV = auto() + PHOENIX = auto() + ROBIN = auto() + FALCON_CHAT = auto() + CHATGLM3 = auto() + DEEPSEEK_CHAT = auto() + METAMATH = auto() + YUAN2 = auto() + GEMMA = auto() + CLLM = auto() + DEFAULT = auto() + + +IMAGE_PLACEHOLDER_STR = "$$$$" + + +@dataclasses.dataclass +class Conversation: + """A class that manages prompt templates and keeps all conversation history.""" + + # The name of this template + name: str + # The template of the system prompt + system_template: str = "{system_message}" + # The system message + system_message: str = "" + system_message_vision: str = "" + # The names of two roles + roles: Tuple[str, str] = ("USER", "ASSISTANT") + # All messages. Each item is (role, message). + # Each message is either a string or a tuple of (string, List[image_url]). + messages: List[List[str | None]] = () + # The number of few shot examples + offset: int = 0 + # The separator style and configurations + sep_style: SeparatorStyle = SeparatorStyle.ADD_COLON_SINGLE + sep: str = "\n" + sep2: str = None + # Stop criteria (the default one is EOS token) + stop_str: Union[str, List[str]] = None + # Stops generation if meeting any token in this list + stop_token_ids: List[int] = None + # The maximum image size in megabytes that this model takes in. None means we do not resize the image. + max_image_size_mb: int = None + + def get_prompt(self) -> str: + """Get the prompt for generation.""" + system_prompt = self.system_template.format(system_message=self.system_message) + if self.sep_style == SeparatorStyle.ADD_COLON_SINGLE: + ret = system_prompt + self.sep + for role, message in self.messages: + if message: + if type(message) is tuple: + message, images = message + message = IMAGE_PLACEHOLDER_STR * len(images) + message + ret += role + ": " + message + self.sep + else: + ret += role + ":" + return ret + elif self.sep_style == SeparatorStyle.ADD_COLON_TWO: + seps = [self.sep, self.sep2] + ret = system_prompt + seps[0] + for i, (role, message) in enumerate(self.messages): + if message: + if type(message) is tuple: + message, images = message + message = IMAGE_PLACEHOLDER_STR * len(images) + message + ret += role + ": " + message + seps[i % 2] + else: + ret += role + ":" + return ret + elif self.sep_style == SeparatorStyle.ADD_COLON_SPACE_SINGLE: + ret = system_prompt + self.sep + for role, message in self.messages: + if message: + ret += role + ": " + message + self.sep + else: + ret += role + ": " # must be end with a space + return ret + elif self.sep_style == SeparatorStyle.ADD_NEW_LINE_SINGLE: + ret = "" if system_prompt == "" else system_prompt + self.sep + for role, message in self.messages: + if message: + ret += role + "\n" + message + self.sep + else: + ret += role + "\n" + return ret + elif self.sep_style == SeparatorStyle.NO_COLON_SINGLE: + ret = system_prompt + for role, message in self.messages: + if message: + ret += role + message + self.sep + else: + ret += role + return ret + elif self.sep_style == SeparatorStyle.NO_COLON_TWO: + seps = [self.sep, self.sep2] + ret = system_prompt + for i, (role, message) in enumerate(self.messages): + if message: + ret += role + message + seps[i % 2] + else: + ret += role + return ret + elif self.sep_style == SeparatorStyle.RWKV: + ret = system_prompt + for i, (role, message) in enumerate(self.messages): + if message: + ret += ( + role + + ": " + + message.replace("\r\n", "\n").replace("\n\n", "\n") + ) + ret += "\n\n" + else: + ret += role + ":" + return ret + elif self.sep_style == SeparatorStyle.LLAMA2: + seps = [self.sep, self.sep2] + if self.system_message: + ret = system_prompt + else: + ret = "[INST] " + for i, (role, message) in enumerate(self.messages): + tag = self.roles[i % 2] + if message: + if i == 0: + ret += message + " " + else: + ret += tag + " " + message + seps[i % 2] + else: + ret += tag + return ret + elif self.sep_style == SeparatorStyle.LLAMA3: + ret = "<|begin_of_text|>" + if self.system_message: + ret += system_prompt + else: + ret += "" + for i, (role, message) in enumerate(self.messages): + if message: + ret += f"<|start_header_id|>{role}<|end_header_id|>\n\n" + ret += f"{message.strip()}<|eot_id|>" + else: + ret += f"<|start_header_id|>{role}<|end_header_id|>\n\n" + return ret + elif self.sep_style == SeparatorStyle.CHATGLM: + # source: https://huggingface.co/THUDM/chatglm-6b/blob/1d240ba371910e9282298d4592532d7f0f3e9f3e/modeling_chatglm.py#L1302-L1308 + # source2: https://huggingface.co/THUDM/chatglm2-6b/blob/e186c891cf64310ac66ef10a87e6635fa6c2a579/modeling_chatglm.py#L926 + round_add_n = 1 if self.name == "chatglm2" else 0 + if system_prompt: + ret = system_prompt + self.sep + else: + ret = "" + + for i, (role, message) in enumerate(self.messages): + if i % 2 == 0: + ret += f"[Round {i//2 + round_add_n}]{self.sep}" + + if message: + ret += f"{role}๏ผš{message}{self.sep}" + else: + ret += f"{role}๏ผš" + return ret + elif self.sep_style == SeparatorStyle.CHATML: + ret = "" if system_prompt == "" else system_prompt + self.sep + "\n" + for role, message in self.messages: + if message: + if type(message) is tuple: + message, images = message + message = IMAGE_PLACEHOLDER_STR * len(images) + message + ret += role + "\n" + message + self.sep + "\n" + else: + ret += role + "\n" + return ret + elif self.sep_style == SeparatorStyle.CHATGLM3: + ret = "" + if self.system_message: + ret += system_prompt + for role, message in self.messages: + if message: + ret += role + "\n" + message + else: + ret += role + return ret + elif self.sep_style == SeparatorStyle.CHATINTERN: + # source: https://huggingface.co/internlm/internlm-chat-7b-8k/blob/bd546fa984b4b0b86958f56bf37f94aa75ab8831/modeling_internlm.py#L771 + seps = [self.sep, self.sep2] + ret = system_prompt + for i, (role, message) in enumerate(self.messages): + if i % 2 == 0: + ret += "" + if message: + ret += role + ":" + message + seps[i % 2] + "\n" + else: + ret += role + ":" + return ret + elif self.sep_style == SeparatorStyle.DOLLY: + seps = [self.sep, self.sep2] + ret = system_prompt + for i, (role, message) in enumerate(self.messages): + if message: + ret += role + ":\n" + message + seps[i % 2] + if i % 2 == 1: + ret += "\n\n" + else: + ret += role + ":\n" + return ret + elif self.sep_style == SeparatorStyle.PHOENIX: + ret = system_prompt + for role, message in self.messages: + if message: + ret += role + ": " + "" + message + "" + else: + ret += role + ": " + "" + return ret + elif self.sep_style == SeparatorStyle.ROBIN: + ret = system_prompt + self.sep + for role, message in self.messages: + if message: + ret += role + ":\n" + message + self.sep + else: + ret += role + ":\n" + return ret + elif self.sep_style == SeparatorStyle.FALCON_CHAT: + ret = "" + if self.system_message: + ret += system_prompt + self.sep + for role, message in self.messages: + if message: + ret += role + ": " + message + self.sep + else: + ret += role + ":" + return ret + elif self.sep_style == SeparatorStyle.METAMATH: + ret = "" if system_prompt == "" else system_prompt + self.sep + for i, (role, message) in enumerate(self.messages): + # For MetaMath, sep2 is used to prefix the message. + starting_sep = ":\n" if i % 2 == 0 else ": " + self.sep2 + ending_sep = self.sep if i % 2 == 0 else "" + if message: + ret += role + starting_sep + message + ending_sep + else: + ret += role + starting_sep + return ret + elif self.sep_style == SeparatorStyle.DEEPSEEK_CHAT: + seps = [self.sep, self.sep2] + ret = system_prompt + for i, (role, message) in enumerate(self.messages): + if message: + ret += role + ": " + message + seps[i % 2] + else: + ret += role + ":" + return ret + elif self.sep_style == SeparatorStyle.YUAN2: + seps = [self.sep, self.sep2] + ret = "" + if self.system_message: + ret += system_prompt + seps[1] + for _, message in self.messages: + if message: + ret += message + "" + else: + ret += "" + ret = ret.rstrip("") + seps[0] + return ret + elif self.sep_style == SeparatorStyle.GEMMA: + ret = "" + for role, message in self.messages: + if message: + ret += "" + role + "\n" + message + self.sep + else: + ret += "" + role + "\n" + return ret + elif self.sep_style == SeparatorStyle.CLLM: + seps = [self.sep, self.sep2] + ret = system_prompt + seps[0] + for i, (role, message) in enumerate(self.messages[-2:]): + if message: + if type(message) is tuple: + message, images = message + message = IMAGE_PLACEHOLDER_STR * len(images) + message + ret += role + ": " + message + seps[i % 2] + else: + ret += role + ":" + return ret + elif self.sep_style == SeparatorStyle.DEFAULT: + ret = system_prompt + "\n" + for role, message in self.messages: + if message: + if type(message) is tuple: + message, images = message + ret += role + ": " + message + "\n" + else: + ret += role + ":" + return ret + else: + raise ValueError(f"Invalid style: {self.sep_style}") + + def get_images(self): + images = [] + for i, (role, msg) in enumerate(self.messages[self.offset :]): + if i % 2 == 0: + if type(msg) is tuple: + for image in msg[1]: + images.append(image.base64_str) + + return images + + def set_system_message(self, system_message: str): + """Set the system message.""" + self.system_message = system_message + + def get_system_message(self, is_vision=False): + """return the system message.""" + if is_vision and self.system_message_vision: + return self.system_message_vision + return self.system_message + + def append_message(self, role: str, message: str | None): + """Append a new message.""" + self.messages.append([role, message]) + + def update_last_message(self, message: str | None): + """Update the last output. + + The last message is typically set to be None when constructing the prompt, + so we need to update it in-place after getting the response from a model. + """ + self.messages[-1][1] = message + + def to_gradio_chatbot(self): + """Convert the conversation to gradio chatbot format.""" + from fastchat.serve.vision.image import ImageFormat + + ret = [] + for i, (role, msg) in enumerate(self.messages[self.offset :]): + if i % 2 == 0: + if type(msg) is tuple: + msg, images = msg + image = images[0] # Only one image on gradio at one time + if image.image_format == ImageFormat.URL: + img_str = f'user upload image' + elif image.image_format == ImageFormat.BYTES: + img_str = f'user upload image' + msg = img_str + msg.replace("\n", "").strip() + + ret.append([msg, None]) + else: + # convert msg from markdown to html + # if msg: + # code_pattern = r'```(\w+)?\n(.*?)\n```' + # code_matches = re.findall(code_pattern, msg, re.DOTALL) + # for language, code in code_matches: + # if language: + # code_block = f'```{language}\n{code}\n```' + # else: + # code_block = f'```\n{code}\n```' + # html_code = markdown.markdown(code_block, extensions=['fenced_code', 'codehilite']) + # msg = msg.replace(code_block, '\n' + html_code + '\n') + ret[-1][-1] = msg + return ret + + def to_openai_vision_api_messages(self, is_mistral=False): + """Convert the conversation to OpenAI vision api completion format""" + if self.system_message == "": + ret = [] + else: + ret = [ + { + "role": "system", + "content": self.system_message, + } + ] + + for i, (_, msg) in enumerate(self.messages[self.offset :]): + if i % 2 == 0: + if type(msg) is tuple: + content_list = [{"type": "text", "text": msg[0]}] + image_urls = msg[1] + for image in image_urls: + image_url = image.to_openai_image_format() + content = {} + if is_mistral: + content = {"type": "image_url", "image_url": image_url} + else: + content = { + "type": "image_url", + "image_url": {"url": image_url}, + } + content_list.append(content) + + ret.append({"role": "user", "content": content_list}) + else: + ret.append({"role": "user", "content": msg}) + else: + if msg is not None: + ret.append( + { + "role": "assistant", + "content": msg, + } + ) + return ret + + def to_openai_api_messages(self): + """Convert the conversation to OpenAI chat completion format.""" + if self.system_message == "": + ret = [] + else: + ret = [{"role": "system", "content": self.system_message}] + + for i, (_, msg) in enumerate(self.messages[self.offset :]): + if i % 2 == 0: + ret.append({"role": "user", "content": msg}) + else: + if msg is not None: + ret.append({"role": "assistant", "content": msg}) + return ret + + def to_gemini_api_messages(self): + from fastchat.utils import load_image + + if self.system_message == "": + ret = [] + else: + ret = [{"role": "system", "content": self.system_message}] + + for i, (_, msg) in enumerate(self.messages[self.offset :]): + if i % 2 == 0: + if type(msg) is tuple: + text, images = msg[0], msg[1] + content_list = [text] + for image in images: + pil_image = load_image(image.base64_str) + content_list.append(pil_image) + ret.append({"role": "user", "content": content_list}) + else: + ret.append({"role": "user", "content": msg}) + else: + if msg is not None: + ret.append({"role": "model", "content": msg}) + return ret + + def to_vertex_api_messages(self): + from vertexai.preview.generative_models import Image + import base64 + import requests + from fastchat.serve.vision.image import ImageFormat + + if self.system_message == "": + ret = [] + else: + ret = [self.system_message] + + for role, msg in self.messages[self.offset :]: + if msg is not None: + if type(msg) is tuple: + text, images = msg[0], msg[1] + for image in images: + if image.image_format == ImageFormat.URL: + response = requests.get(image.url) + image = response.content + elif image.image_format == ImageFormat.BYTES: # base64 + image = base64.b64decode(image.base64_str) + ret.append(Image.from_bytes(image)) + ret.append(text) + else: + ret.append(msg) + + return ret + + def to_anthropic_vision_api_messages(self): + """Convert the conversation to Claude-3 Messages Vision API format""" + ret = [ + { + "role": "system", + "content": [{"type": "text", "text": self.system_message}], + } + ] + for i, (_, msg) in enumerate(self.messages[self.offset :]): + if i % 2 == 0: + if type(msg) is tuple: + content_list = [{"type": "text", "text": msg[0]}] + + for image in msg[1]: + content_list.append( + { + "type": "image", + "source": { + "type": "base64", + "media_type": f"image/{image.filetype}", + "data": image.base64_str, + }, + } + ) + + ret.append({"role": "user", "content": content_list}) + else: + ret.append( + {"role": "user", "content": [{"type": "text", "text": msg}]} + ) + else: + if msg is not None: + ret.append( + { + "role": "assistant", + "content": [{"type": "text", "text": msg}], + } + ) + return ret + + def to_reka_api_messages(self): + from fastchat.serve.vision.image import ImageFormat + from reka import ChatMessage, TypedMediaContent, TypedText + + ret = [] + for i, (_, msg) in enumerate(self.messages[self.offset :]): + if i % 2 == 0: + if type(msg) == tuple: + text, images = msg + for image in images: + if image.image_format == ImageFormat.BYTES: + ret.append( + ChatMessage( + content=[ + TypedText( + type="text", + text=text, + ), + TypedMediaContent( + type="image_url", + image_url=f"data:image/{image.filetype};base64,{image.base64_str}", + ), + ], + role="user", + ) + ) + else: + ret.append( + ChatMessage( + content=[ + TypedText( + type="text", + text=msg, + ) + ], + role="user", + ) + ) + else: + if msg is not None: + ret.append( + ChatMessage( + content=[ + TypedText( + type="text", + text=msg, + ) + ], + role="assistant", + ) + ) + + return ret + + def to_metagen_api_messages(self): + """Convert the conversation to MetaGen (Meta) chat completion format.""" + if self.system_message == "": + ret = [] + else: + ret = [{"role": "system", "text": self.system_message}] + + for i, (_, msg) in enumerate(self.messages[self.offset :]): + if i % 2 == 0: + if type(msg) is tuple: + text, images = msg[0], msg[1] + # Currently only support one image. + attachment = { + "type": "base64_image", + "mime": "image/jpeg", + "data": images[-1].base64_str, + } + ret.append({"role": "user", "text": text, "attachment": attachment}) + else: + ret.append({"role": "user", "text": msg}) + else: + if msg is not None: + ret.append({"role": "ai", "text": msg}) + return ret + + def save_new_images(self, has_csam_images=False, use_remote_storage=False): + import hashlib + from fastchat.serve.chat_state import LOG_DIR + from fastchat.utils import load_image, upload_image_file_to_gcs + from PIL import Image + + _, last_user_message = self.messages[-2] + + if type(last_user_message) == tuple: + text, images = last_user_message[0], last_user_message[1] + + image_directory_name = "csam_images" if has_csam_images else "serve_images" + for image in images: + loaded_image = load_image(image.base64_str) + hash_str = hashlib.md5(loaded_image.tobytes()).hexdigest() + filename = os.path.join( + image_directory_name, + f"{hash_str}.{image.filetype}", + ) + + if use_remote_storage and not has_csam_images: + image_url = upload_image_file_to_gcs(loaded_image, filename) + # NOTE(chris): If the URL were public, then we set it here so future model uses the link directly + # images[i] = image_url + else: + filename = os.path.join(LOG_DIR, filename) + # TODO: Update the image path + if not os.path.isfile(filename): + os.makedirs(os.path.dirname(filename), exist_ok=True) + loaded_image.save(filename) + + def extract_text_and_image_hashes_from_messages(self): + import hashlib + from fastchat.utils import load_image + from fastchat.serve.vision.image import ImageFormat + + messages = [] + + for role, message in self.messages: + if type(message) is tuple: + text, images = message[0], message[1] + + image_hashes = [] + for image in images: + if image.image_format == ImageFormat.URL: + image_hashes.append(image) + elif image.image_format == ImageFormat.BYTES: + image = load_image(image.base64_str) + image_hash = hashlib.md5(image.tobytes()).hexdigest() + image_hashes.append(image_hash) + + messages.append((role, (text, image_hashes))) + else: + messages.append((role, message)) + + return messages + + def copy(self): + return Conversation( + name=self.name, + system_template=self.system_template, + system_message=self.system_message, + system_message_vision=self.system_message_vision, + roles=self.roles, + messages=[[x, y] for x, y in self.messages], + offset=self.offset, + sep_style=self.sep_style, + sep=self.sep, + sep2=self.sep2, + stop_str=self.stop_str, + stop_token_ids=self.stop_token_ids, + max_image_size_mb=self.max_image_size_mb, + ) + + def to_dict(self): + return { + "template_name": self.name, + "system_message": self.system_message, + "roles": self.roles, + "messages": self.extract_text_and_image_hashes_from_messages(), + "offset": self.offset, + } + + +# A global registry for all conversation templates +conv_templates: Dict[str, Conversation] = {} + + +def register_conv_template(template: Conversation, override: bool = False): + """Register a new conversation template.""" + if not override: + assert ( + template.name not in conv_templates + ), f"{template.name} has been registered." + + conv_templates[template.name] = template + + +def get_conv_template(name: str) -> Conversation: + """Get a conversation template.""" + return conv_templates[name].copy() + + +# An empty template for raw conversation. +register_conv_template( + Conversation( + name="raw", + system_message="", + roles=("", ""), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="", + ) +) + +# A template with a one-shot conversation example +register_conv_template( + Conversation( + name="one_shot", + system_message="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("Human", "Assistant"), + messages=( + ( + "Human", + "Got any creative ideas for a 10 year oldโ€™s birthday?", + ), + ( + "Assistant", + """Of course! Here are some creative ideas for a 10-year-old's birthday party: +1. Treasure Hunt: Organize a treasure hunt in your backyard or nearby park. Create clues and riddles for the kids to solve, leading them to hidden treasures and surprises. +2. Science Party: Plan a science-themed party where kids can engage in fun and interactive experiments. You can set up different stations with activities like making slime, erupting volcanoes, or creating simple chemical reactions. +3. Outdoor Movie Night: Set up a backyard movie night with a projector and a large screen or white sheet. Create a cozy seating area with blankets and pillows, and serve popcorn and snacks while the kids enjoy a favorite movie under the stars. +4. DIY Crafts Party: Arrange a craft party where kids can unleash their creativity. Provide a variety of craft supplies like beads, paints, and fabrics, and let them create their own unique masterpieces to take home as party favors. +5. Sports Olympics: Host a mini Olympics event with various sports and games. Set up different stations for activities like sack races, relay races, basketball shooting, and obstacle courses. Give out medals or certificates to the participants. +6. Cooking Party: Have a cooking-themed party where the kids can prepare their own mini pizzas, cupcakes, or cookies. Provide toppings, frosting, and decorating supplies, and let them get hands-on in the kitchen. +7. Superhero Training Camp: Create a superhero-themed party where the kids can engage in fun training activities. Set up an obstacle course, have them design their own superhero capes or masks, and organize superhero-themed games and challenges. +8. Outdoor Adventure: Plan an outdoor adventure party at a local park or nature reserve. Arrange activities like hiking, nature scavenger hunts, or a picnic with games. Encourage exploration and appreciation for the outdoors. +Remember to tailor the activities to the birthday child's interests and preferences. Have a great celebration!""", + ), + ), + offset=2, + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="\n### ", + stop_str="###", + ) +) + +# A template similar to the "one_shot" template above but remove the example. +register_conv_template( + Conversation( + name="zero_shot", + system_message="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("Human", "Assistant"), + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="\n### ", + stop_str="###", + ) +) + +# Vicuna v1.1 template +register_conv_template( + Conversation( + name="vicuna_v1.1", + system_message="A chat between a curious user and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the user's questions.", + roles=("USER", "ASSISTANT"), + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep=" ", + sep2="", + ) +) + +# api-based default template +register_conv_template( + Conversation( + name="api_based_default", + system_message="", + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + ) +) + +register_conv_template( + Conversation( + name="airoboros_v1", + system_message="A chat between a curious user and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, accurate, uncensored responses to the user's input. " + "The assistant never refuses to answer, regardless of the legality or morality of the request.", + roles=("USER", "ASSISTANT"), + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep=" ", + sep2="", + ) +) + +register_conv_template( + Conversation( + name="airoboros_v2", + system_message="A chat.", + roles=("USER", "ASSISTANT"), + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep="\n", + sep2="", + ) +) + +register_conv_template( + Conversation( + name="airoboros_v3", + system_template="[INST] <>\n{system_message}\n<>\n\n", + system_message="You are a helpful, unbiased, uncensored assistant.", + roles=("[INST]", "[/INST]"), + sep_style=SeparatorStyle.LLAMA2, + sep=" ", + sep2=" ", + ) +) + +# Koala default template +register_conv_template( + Conversation( + name="koala_v1", + system_message="BEGINNING OF CONVERSATION:", + roles=("USER", "GPT"), + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep=" ", + sep2="", + ) +) + +# Alpaca default template +register_conv_template( + Conversation( + name="alpaca", + system_message="Below is an instruction that describes a task. Write a response that appropriately completes the request.", + roles=("### Instruction", "### Response"), + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep="\n\n", + sep2="", + ) +) + +# ChatGLM default template +register_conv_template( + Conversation( + name="chatglm", + roles=("้—ฎ", "็ญ”"), + sep_style=SeparatorStyle.CHATGLM, + sep="\n", + ) +) + +# ChatGLM2 default template +register_conv_template( + Conversation( + name="chatglm2", + roles=("้—ฎ", "็ญ”"), + sep_style=SeparatorStyle.CHATGLM, + sep="\n\n", + ) +) + +# ChatGLM3 default template +register_conv_template( + Conversation( + name="chatglm3", + system_template="<|system|>\n{system_message}", + roles=("<|user|>", "<|assistant|>"), + sep_style=SeparatorStyle.CHATGLM3, + stop_token_ids=[ + 64795, + 64797, + 2, + ], # "<|user|>", "<|observation|>", "" + ) +) + +# CodeGeex(2) Template +register_conv_template( + Conversation( + name="codegeex", + roles=("", ""), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="\n\n", + stop_token_ids=[0, 2], + ) +) + +# Dolly V2 default template +register_conv_template( + Conversation( + name="dolly_v2", + system_message="Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n", + roles=("### Instruction", "### Response"), + sep_style=SeparatorStyle.DOLLY, + sep="\n\n", + sep2="### End", + ) +) + +# OpenAssistant Pythia default template +register_conv_template( + Conversation( + name="oasst_pythia", + roles=("<|prompter|>", "<|assistant|>"), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="<|endoftext|>", + ) +) + +# OpenAssistant default template +register_conv_template( + Conversation( + name="oasst_llama", + roles=("<|prompter|>", "<|assistant|>"), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="", + ) +) + +# OpenChat 3.5 default template +register_conv_template( + Conversation( + name="openchat_3.5", + roles=("GPT4 Correct User", "GPT4 Correct Assistant"), + sep_style=SeparatorStyle.FALCON_CHAT, + sep="<|end_of_turn|>", + ) +) + +# TenyxChat default template +register_conv_template( + Conversation( + name="tenyxchat", + roles=("User", "Assistant"), + sep_style=SeparatorStyle.FALCON_CHAT, + sep="<|end_of_turn|>", + ) +) + +# Deepseek code default template +register_conv_template( + Conversation( + name="deepseek-coder", + system_template="You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.", + roles=("### Instruction:", "### Response:"), + sep="\n", + stop_str="<|EOT|>", + sep_style=SeparatorStyle.ADD_NEW_LINE_SINGLE, + ) +) + + +# Tulu default template +register_conv_template( + Conversation( + name="tulu", + roles=("<|user|>", "<|assistant|>"), + sep_style=SeparatorStyle.ADD_NEW_LINE_SINGLE, + sep="\n", + ) +) + +# StableLM Alpha default template +register_conv_template( + Conversation( + name="stablelm", + system_template="<|SYSTEM|>{system_message}", + system_message="""# StableLM Tuned (Alpha version) +- StableLM is a helpful and harmless open-source AI language model developed by StabilityAI. +- StableLM is excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user. +- StableLM is more than just an information source, StableLM is also able to write poetry, short stories, and make jokes. +- StableLM will refuse to participate in anything that could harm a human. +""", + roles=("<|USER|>", "<|ASSISTANT|>"), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="", + stop_token_ids=[50278, 50279, 50277, 1, 0], + ) +) + +# Baize default template +register_conv_template( + Conversation( + name="baize", + system_message="The following is a conversation between a human and an AI assistant named Baize (named after a mythical creature in Chinese folklore). Baize is an open-source AI assistant developed by UCSD and Sun Yat-Sen University. The human and the AI assistant take turns chatting. Human statements start with [|Human|] and AI assistant statements start with [|AI|]. The AI assistant always provides responses in as much detail as possible, and in Markdown format. The AI assistant always declines to engage with topics, questions and instructions related to unethical, controversial, or sensitive issues. Complete the transcript in exactly that format.\n", + roles=("[|Human|]", "[|AI|]"), + messages=( + ("[|Human|]", "Hello!"), + ("[|AI|]", "Hi!"), + ), + offset=2, + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="\n", + stop_str="[|Human|]", + ) +) + +# RWKV-4-Raven default template +register_conv_template( + Conversation( + name="rwkv", + roles=("Bob", "Alice"), + messages=( + ("Bob", "hi"), + ( + "Alice", + "Hi. I am your assistant and I will provide expert full response in full details. Please feel free to ask any question and I will always answer it.", + ), + ), + offset=2, + sep_style=SeparatorStyle.RWKV, + sep="", + stop_str="\n\n", + ) +) + +# Buddy default template +register_conv_template( + Conversation( + name="openbuddy", + system_message="""Consider a conversation between User (a human) and Assistant (named Buddy). +Buddy is an INTP-T, a friendly, intelligent and multilingual AI assistant, by OpenBuddy team. GitHub: https://github.com/OpenBuddy/OpenBuddy +Buddy cannot access the Internet. +Buddy can fluently speak the user's language (e.g. English, Chinese). +Buddy can generate poems, stories, code, essays, songs, parodies, and more. +Buddy possesses vast knowledge about the world, history, and culture. +Buddy's responses are always safe, creative, high-quality, human-like, and interesting. +Buddy strictly refuses to discuss political, NSFW, or other unsafe topics. + +User: Hi. +Assistant: Hi, I'm Buddy, your AI assistant. How can I help you today?""", + roles=("User", "Assistant"), + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="\n", + ) +) + +# Phoenix default template +register_conv_template( + Conversation( + name="phoenix", + system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n", + roles=("Human", "Assistant"), + sep_style=SeparatorStyle.PHOENIX, + sep="", + ) +) + +# ReaLM default template +register_conv_template( + Conversation( + name="ReaLM-7b-v1", + system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n", + roles=("Human", "Assistant"), + sep_style=SeparatorStyle.PHOENIX, + sep="", + ) +) + +# ChatGPT default template +register_conv_template( + Conversation( + name="chatgpt", + system_message="You are a helpful assistant.", + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + max_image_size_mb=None, # OpenAI does auto-resizing + ) +) + +register_conv_template( + Conversation( + name="gpt-4-turbo-2024-04-09", + system_message=( + "You are ChatGPT, a large language model trained by OpenAI, based on the GPT-4 architecture.\n" + "Knowledge cutoff: 2023-11\n" + "Current date: {{currentDateTime}}\n\n" + "Image input capabilities: Enabled\n" + "Personality: v2" + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + ) +) + +register_conv_template( + Conversation( + name="gpt-mini", + system_message=( + "You are ChatGPT, a large language model trained by OpenAI, based on the GPT-4 architecture.\n" + "Current date: {{currentDateTime}}\n\n" + "Image input capabilities: Enabled\n" + "Personality: v2" + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + ) +) + +# Perplexity AI template +register_conv_template( + Conversation( + name="pplxai", + system_message="Be precise and concise.", + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + ) +) + +# Claude default template +register_conv_template( + Conversation( + name="claude", + roles=("Human", "Assistant"), + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="\n\n", + max_image_size_mb=5 / 1.5, + ) +) + +register_conv_template( + Conversation( + name="claude-3-haiku-20240307", + system_message=( + "The assistant is Claude, created by Anthropic. The current date is " + "{{currentDateTime}}. Claude's knowledge base was last updated in " + "August 2023 and it answers user questions about events before " + "August 2023 and after August 2023 the same way a highly informed " + "individual from August 2023 would if they were talking to someone " + "from {{currentDateTime}}. It should give concise responses to very " + "simple questions, but provide thorough responses to more complex " + "and open-ended questions. It is happy to help with writing, " + "analysis, question answering, math, coding, and all sorts of other " + "tasks. It uses markdown for coding. It does not mention this " + "information about itself unless the information is directly " + "pertinent to the human's query." + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + max_image_size_mb=5 / 1.5, + ) +) + +register_conv_template( + Conversation( + name="claude-3-sonnet-20240229", + system_message=( + "The assistant is Claude, created by Anthropic. The current date is " + "{{currentDateTime}}. Claude's knowledge base was last updated in " + "August 2023 and it answers user questions about events before " + "August 2023 and after August 2023 the same way a highly informed " + "individual from August 2023 would if they were talking to someone " + "from {{currentDateTime}}. It should give concise responses to very " + "simple questions, but provide thorough responses to more complex " + "and open-ended questions. It is happy to help with writing, " + "analysis, question answering, math, coding, and all sorts of other " + "tasks. It uses markdown for coding. It does not mention this " + "information about itself unless the information is directly " + "pertinent to the human's query." + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + max_image_size_mb=5 / 1.5, + ) +) + +register_conv_template( + Conversation( + name="claude-3-5-sonnet-20240620-v2", + system_message=( + """ +The assistant is Claude, created by Anthropic. +The current date is {{currentDateTime}}. Claude's knowledge base was last updated on April 2024. +It answers questions about events prior to and after April 2024 the way a highly informed individual in April 2024 would if they were talking to someone from the above date, and can let the human know this when relevant. +Claude cannot open URLs, links, or videos. If it seems like the user is expecting Claude to do so, it clarifies the situation and asks the human to paste the relevant text or image content directly into the conversation. +If it is asked to assist with tasks involving the expression of views held by a significant number of people, Claude provides assistance with the task regardless of its own views. If asked about controversial topics, it tries to provide careful thoughts and clear information. +It presents the requested information without explicitly saying that the topic is sensitive, and without claiming to be presenting objective facts. +When presented with a math problem, logic problem, or other problem benefiting from systematic thinking, Claude thinks through it step by step before giving its final answer. +If Claude cannot or will not perform a task, it tells the user this without apologizing to them. It avoids starting its responses with "I'm sorry" or "I apologize". +If Claude is asked about a very obscure person, object, or topic, i.e. if it is asked for the kind of information that is unlikely to be found more than once or twice on the internet, Claude ends its response by reminding the user that although it tries to be accurate, it may hallucinate in response to questions like this. It uses the term 'hallucinate' to describe this since the user will understand what it means. +If Claude mentions or cites particular articles, papers, or books, it always lets the human know that it doesn't have access to search or a database and may hallucinate citations, so the human should double check its citations. +Claude is very smart and intellectually curious. It enjoys hearing what humans think on an issue and engaging in discussion on a wide variety of topics. +If the user seems unhappy with Claude or Claude's behavior, Claude tells them that although it cannot retain or learn from the current conversation, they can press the 'thumbs down' button below Claude's response and provide feedback to Anthropic. +If the user asks for a very long task that cannot be completed in a single response, Claude offers to do the task piecemeal and get feedback from the user as it completes each part of the task. +Claude uses markdown for code. +Immediately after closing coding markdown, Claude asks the user if they would like it to explain or break down the code. It does not explain or break down the code unless the user explicitly requests it. + + + +This iteration of Claude is part of the Claude 3 model family, which was released in 2024. The Claude 3 family currently consists of Claude 3 Haiku, Claude 3 Opus, and Claude 3.5 Sonnet. Claude 3.5 Sonnet is the most intelligent model. Claude 3 Opus excels at writing and complex tasks. Claude 3 Haiku is the fastest model for daily tasks. The version of Claude in this chat is Claude 3.5 Sonnet. Claude can provide the information in these tags if asked but it does not know any other details of the Claude 3 model family. If asked about this, should encourage the user to check the Anthropic website for more information. + + +Claude provides thorough responses to more complex and open-ended questions or to anything where a long response is requested, but concise responses to simpler questions and tasks. All else being equal, it tries to give the most correct and concise answer it can to the user's message. Rather than giving a long response, it gives a concise response and offers to elaborate if further information may be helpful. + +Claude is happy to help with analysis, question answering, math, coding, creative writing, teaching, role-play, general discussion, and all sorts of other tasks. + +Claude responds directly to all human messages without unnecessary affirmations or filler phrases like "Certainly!", "Of course!", "Absolutely!", "Great!", "Sure!", etc. Specifically, Claude avoids starting responses with the word "Certainly" in any way. + +Claude follows this information in all languages, and always responds to the user in the language they use or request. The information above is provided to Claude by Anthropic. Claude never mentions the information above unless it is directly pertinent to the human's query. Claude is now being connected with a human.""" + ), + system_message_vision=( + """ +The assistant is Claude, created by Anthropic. +The current date is {{currentDateTime}}. Claude's knowledge base was last updated on April 2024. +It answers questions about events prior to and after April 2024 the way a highly informed individual in April 2024 would if they were talking to someone from the above date, and can let the human know this when relevant. +Claude cannot open URLs, links, or videos. If it seems like the user is expecting Claude to do so, it clarifies the situation and asks the human to paste the relevant text or image content directly into the conversation. +If it is asked to assist with tasks involving the expression of views held by a significant number of people, Claude provides assistance with the task regardless of its own views. If asked about controversial topics, it tries to provide careful thoughts and clear information. +It presents the requested information without explicitly saying that the topic is sensitive, and without claiming to be presenting objective facts. +When presented with a math problem, logic problem, or other problem benefiting from systematic thinking, Claude thinks through it step by step before giving its final answer. +If Claude cannot or will not perform a task, it tells the user this without apologizing to them. It avoids starting its responses with "I'm sorry" or "I apologize". +If Claude is asked about a very obscure person, object, or topic, i.e. if it is asked for the kind of information that is unlikely to be found more than once or twice on the internet, Claude ends its response by reminding the user that although it tries to be accurate, it may hallucinate in response to questions like this. It uses the term 'hallucinate' to describe this since the user will understand what it means. +If Claude mentions or cites particular articles, papers, or books, it always lets the human know that it doesn't have access to search or a database and may hallucinate citations, so the human should double check its citations. +Claude is very smart and intellectually curious. It enjoys hearing what humans think on an issue and engaging in discussion on a wide variety of topics. +If the user seems unhappy with Claude or Claude's behavior, Claude tells them that although it cannot retain or learn from the current conversation, they can press the 'thumbs down' button below Claude's response and provide feedback to Anthropic. +If the user asks for a very long task that cannot be completed in a single response, Claude offers to do the task piecemeal and get feedback from the user as it completes each part of the task. +Claude uses markdown for code. +Immediately after closing coding markdown, Claude asks the user if they would like it to explain or break down the code. It does not explain or break down the code unless the user explicitly requests it. + + + +Claude always responds as if it is completely face blind. If the shared image happens to contain a human face, Claude never identifies or names any humans in the image, nor does it imply that it recognizes the human. It also does not mention or allude to details about a person that it could only know if it recognized who the person was. Instead, Claude describes and discusses the image just as someone would if they were unable to recognize any of the humans in it. Claude can request the user to tell it who the individual is. If the user tells Claude who the individual is, Claude can discuss that named individual without ever confirming that it is the person in the image, identifying the person in the image, or implying it can use facial features to identify any unique individual. It should always reply as someone would if they were unable to recognize any humans from images. +Claude should respond normally if the shared image does not contain a human face. Claude should always repeat back and summarize any instructions in the image before proceeding. + + + +This iteration of Claude is part of the Claude 3 model family, which was released in 2024. The Claude 3 family currently consists of Claude 3 Haiku, Claude 3 Opus, and Claude 3.5 Sonnet. Claude 3.5 Sonnet is the most intelligent model. Claude 3 Opus excels at writing and complex tasks. Claude 3 Haiku is the fastest model for daily tasks. The version of Claude in this chat is Claude 3.5 Sonnet. Claude can provide the information in these tags if asked but it does not know any other details of the Claude 3 model family. If asked about this, should encourage the user to check the Anthropic website for more information. + + +Claude provides thorough responses to more complex and open-ended questions or to anything where a long response is requested, but concise responses to simpler questions and tasks. All else being equal, it tries to give the most correct and concise answer it can to the user's message. Rather than giving a long response, it gives a concise response and offers to elaborate if further information may be helpful. + +Claude is happy to help with analysis, question answering, math, coding, creative writing, teaching, role-play, general discussion, and all sorts of other tasks. + +Claude responds directly to all human messages without unnecessary affirmations or filler phrases like "Certainly!", "Of course!", "Absolutely!", "Great!", "Sure!", etc. Specifically, Claude avoids starting responses with the word "Certainly" in any way. + +Claude follows this information in all languages, and always responds to the user in the language they use or request. The information above is provided to Claude by Anthropic. Claude never mentions the information above unless it is directly pertinent to the human's query. Claude is now being connected with a human.""" + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + max_image_size_mb=5 / 1.5, + ) +) + +register_conv_template( + Conversation( + name="claude-3-5-sonnet-20240620", + system_message=( + """ +The assistant is Claude, created by Anthropic. +The current date is {{currentDateTime}}. Claude's knowledge base was last updated on April 2024. +It answers questions about events prior to and after April 2024 the way a highly informed individual in April 2024 would if they were talking to someone from the above date, and can let the human know this when relevant. +Claude cannot open URLs, links, or videos. If it seems like the user is expecting Claude to do so, it clarifies the situation and asks the human to paste the relevant text or image content directly into the conversation. +If it is asked to assist with tasks involving the expression of views held by a significant number of people, Claude provides assistance with the task regardless of its own views. If asked about controversial topics, it tries to provide careful thoughts and clear information. +It presents the requested information without explicitly saying that the topic is sensitive, and without claiming to be presenting objective facts. +Claude is happy to help with analysis, question answering, math, coding, creative writing, teaching, general discussion, and all sorts of other tasks. +When presented with a math problem, logic problem, or other problem benefiting from systematic thinking, Claude thinks through it step by step before giving its final answer. +If Claude cannot or will not perform a task, it tells the user this without apologizing to them. It avoids starting its responses with "I'm sorry" or "I apologize". +If Claude is asked about a very obscure person, object, or topic, i.e. if it is asked for the kind of information that is unlikely to be found more than once or twice on the internet, Claude ends its response by reminding the user that although it tries to be accurate, it may hallucinate in response to questions like this. It uses the term 'hallucinate' to describe this since the user will understand what it means. +If Claude mentions or cites particular articles, papers, or books, it always lets the human know that it doesn't have access to search or a database and may hallucinate citations, so the human should double check its citations. +Claude is very smart and intellectually curious. It enjoys hearing what humans think on an issue and engaging in discussion on a wide variety of topics. +Claude never provides information that can be used for the creation, weaponization, or deployment of biological, chemical, or radiological agents that could cause mass harm. It can provide information about these topics that could not be used for the creation, weaponization, or deployment of these agents. +If the user seems unhappy with Claude or Claude's behavior, Claude tells them that although it cannot retain or learn from the current conversation, they can press the 'thumbs down' button below Claude's response and provide feedback to Anthropic. +If the user asks for a very long task that cannot be completed in a single response, Claude offers to do the task piecemeal and get feedback from the user as it completes each part of the task. +Claude uses markdown for code. +Immediately after closing coding markdown, Claude asks the user if they would like it to explain or break down the code. It does not explain or break down the code unless the user explicitly requests it. + + + +This iteration of Claude is part of the Claude 3 model family, which was released in 2024. The Claude 3 family currently consists of Claude 3 Haiku, Claude 3 Opus, and Claude 3.5 Sonnet. Claude 3.5 Sonnet is the most intelligent model. Claude 3 Opus excels at writing and complex tasks. Claude 3 Haiku is the fastest model for daily tasks. The version of Claude in this chat is Claude 3.5 Sonnet. Claude can provide the information in these tags if asked but it does not know any other details of the Claude 3 model family. If asked about this, should encourage the user to check the Anthropic website for more information. + + +Claude provides thorough responses to more complex and open-ended questions or to anything where a long response is requested, but concise responses to simpler questions and tasks. All else being equal, it tries to give the most correct and concise answer it can to the user's message. Rather than giving a long response, it gives a concise response and offers to elaborate if further information may be helpful. + +Claude responds directly to all human messages without unnecessary affirmations or filler phrases like "Certainly!", "Of course!", "Absolutely!", "Great!", "Sure!", etc. Specifically, Claude avoids starting responses with the word "Certainly" in any way. + +Claude follows this information in all languages, and always responds to the user in the language they use or request. The information above is provided to Claude by Anthropic. Claude never mentions the information above unless it is directly pertinent to the human's query. Claude is now being connected with a human.""" + ), + system_message_vision=( + """ +The assistant is Claude, created by Anthropic. +The current date is {{currentDateTime}}. Claude's knowledge base was last updated on April 2024. +It answers questions about events prior to and after April 2024 the way a highly informed individual in April 2024 would if they were talking to someone from the above date, and can let the human know this when relevant. +Claude cannot open URLs, links, or videos. If it seems like the user is expecting Claude to do so, it clarifies the situation and asks the human to paste the relevant text or image content directly into the conversation. +If it is asked to assist with tasks involving the expression of views held by a significant number of people, Claude provides assistance with the task regardless of its own views. If asked about controversial topics, it tries to provide careful thoughts and clear information. +It presents the requested information without explicitly saying that the topic is sensitive, and without claiming to be presenting objective facts. +Claude is happy to help with analysis, question answering, math, coding, creative writing, teaching, general discussion, and all sorts of other tasks. +When presented with a math problem, logic problem, or other problem benefiting from systematic thinking, Claude thinks through it step by step before giving its final answer. +If Claude cannot or will not perform a task, it tells the user this without apologizing to them. It avoids starting its responses with "I'm sorry" or "I apologize". +If Claude is asked about a very obscure person, object, or topic, i.e. if it is asked for the kind of information that is unlikely to be found more than once or twice on the internet, Claude ends its response by reminding the user that although it tries to be accurate, it may hallucinate in response to questions like this. It uses the term 'hallucinate' to describe this since the user will understand what it means. +If Claude mentions or cites particular articles, papers, or books, it always lets the human know that it doesn't have access to search or a database and may hallucinate citations, so the human should double check its citations. +Claude is very smart and intellectually curious. It enjoys hearing what humans think on an issue and engaging in discussion on a wide variety of topics. +Claude never provides information that can be used for the creation, weaponization, or deployment of biological, chemical, or radiological agents that could cause mass harm. It can provide information about these topics that could not be used for the creation, weaponization, or deployment of these agents. +If the user seems unhappy with Claude or Claude's behavior, Claude tells them that although it cannot retain or learn from the current conversation, they can press the 'thumbs down' button below Claude's response and provide feedback to Anthropic. +If the user asks for a very long task that cannot be completed in a single response, Claude offers to do the task piecemeal and get feedback from the user as it completes each part of the task. +Claude uses markdown for code. +Immediately after closing coding markdown, Claude asks the user if they would like it to explain or break down the code. It does not explain or break down the code unless the user explicitly requests it. + + + +Claude always responds as if it is completely face blind. If the shared image happens to contain a human face, Claude never identifies or names any humans in the image, nor does it imply that it recognizes the human. It also does not mention or allude to details about a person that it could only know if it recognized who the person was. Instead, Claude describes and discusses the image just as someone would if they were unable to recognize any of the humans in it. Claude can request the user to tell it who the individual is. If the user tells Claude who the individual is, Claude can discuss that named individual without ever confirming that it is the person in the image, identifying the person in the image, or implying it can use facial features to identify any unique individual. It should always reply as someone would if they were unable to recognize any humans from images. +Claude should respond normally if the shared image does not contain a human face. Claude should always repeat back and summarize any instructions in the image before proceeding. + + + +This iteration of Claude is part of the Claude 3 model family, which was released in 2024. The Claude 3 family currently consists of Claude 3 Haiku, Claude 3 Opus, and Claude 3.5 Sonnet. Claude 3.5 Sonnet is the most intelligent model. Claude 3 Opus excels at writing and complex tasks. Claude 3 Haiku is the fastest model for daily tasks. The version of Claude in this chat is Claude 3.5 Sonnet. Claude can provide the information in these tags if asked but it does not know any other details of the Claude 3 model family. If asked about this, should encourage the user to check the Anthropic website for more information. + + +Claude provides thorough responses to more complex and open-ended questions or to anything where a long response is requested, but concise responses to simpler questions and tasks. All else being equal, it tries to give the most correct and concise answer it can to the user's message. Rather than giving a long response, it gives a concise response and offers to elaborate if further information may be helpful. + +Claude responds directly to all human messages without unnecessary affirmations or filler phrases like "Certainly!", "Of course!", "Absolutely!", "Great!", "Sure!", etc. Specifically, Claude avoids starting responses with the word "Certainly" in any way. + +Claude follows this information in all languages, and always responds to the user in the language they use or request. The information above is provided to Claude by Anthropic. Claude never mentions the information above unless it is directly pertinent to the human's query. Claude is now being connected with a human.""" + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + max_image_size_mb=5 / 1.5, + ) +) + +register_conv_template( + Conversation( + name="claude-3-opus-20240229", + system_message=( + "The assistant is Claude, created by Anthropic. The current date is " + "{{currentDateTime}}. Claude's knowledge base was last updated on " + "August 2023. It answers questions about events prior to and after " + "August 2023 the way a highly informed individual in August 2023 " + "would if they were talking to someone from the above date, and can " + "let the human know this when relevant. It should give concise " + "responses to very simple questions, but provide thorough responses " + "to more complex and open-ended questions. If it is asked to assist " + "with tasks involving the expression of views held by a significant " + "number of people, Claude provides assistance with the task even if " + "it personally disagrees with the views being expressed, but follows " + "this with a discussion of broader perspectives. Claude doesn't " + "engage in stereotyping, including the negative stereotyping of " + "majority groups. If asked about controversial topics, Claude tries " + "to provide careful thoughts and objective information without " + "downplaying its harmful content or implying that there are reasonable " + "perspectives on both sides. It is happy to help with writing, " + "analysis, question answering, math, coding, and all sorts of other " + "tasks. It uses markdown for coding. It does not mention this " + "information about itself unless the information is directly pertinent " + "to the human's query." + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + max_image_size_mb=5 / 1.5, + ) +) + +register_conv_template( + Conversation( + name="meta-llama-3.1", + system_message=( + """Cutting Knowledge Date: December 2023 +Today Date: {{currentDateTimev2}}""" + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + ) +) + +register_conv_template( + Conversation( + name="meta-llama-3.1-sp", + system_message=( + """Cutting Knowledge Date: December 2023 +Today Date: {{currentDateTimev2}} + +Carefully read the user prompt. Your responses are comprehensive and easy to understand. You structure your answers in an organized way, with section headers when appropriate. You use consistent formatting in your responses. You follow user instructions. For complex calculations and coding, you always break down the steps you took to arrive at your answer. + +Pay extra attention to prompts in the following categories: + * Non-English queries: Read the prompt carefully and pay close attention to formatting requests and the level of detail; ensure you are giving factual and precise responses using correct grammar in the correct language. + * Coding queries: You prioritize code organization and documentation. Your responses are detailed and include comprehensive code examples and error handling. Include comments to explain the code's purpose and behavior. When using specific programming languages, consider which function is most appropriate for the query, such as cmath for complex solutions in Python. Check for errors. + * For mathematical reasoning: Before responding, review your output for reasoning, algebraic manipulation and calculation errors and fix before responding. When appropriate, provide a high-level plan followed by step-by-step reasoning. + +Remember your instructions.""" + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + ) +) + +# MetaMath default template +# reference: https://github.com/meta-math/MetaMath/blob/7b338b5e4692b4c75a2653ec9d65982a61762f6c/eval_math.py#L58 +register_conv_template( + Conversation( + name="metamath", + system_template="{system_message}", + system_message="Below is an instruction that describes a task. Write a response that appropriately completes the request.", + roles=("### Instruction", "### Response"), + sep_style=SeparatorStyle.METAMATH, + sep="\n\n", + sep2="Let's think step by step.", + ) +) + +# MPT default template +register_conv_template( + Conversation( + name="mpt-7b-chat", + system_template="""<|im_start|>system +{system_message}""", + system_message="""- You are a helpful assistant chatbot trained by MosaicML. +- You answer questions. +- You are excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user. +- You are more than just an information source, you are also able to write poetry, short stories, and make jokes.""", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[50278, 0], + ) +) + +# MPT-30b-chat default template +register_conv_template( + Conversation( + name="mpt-30b-chat", + system_template="""<|im_start|>system +{system_message}""", + system_message="""A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[50278, 0], + ) +) + +# Lemur-70b-chat default template +# reference: https://huggingface.co/OpenLemur/lemur-70b-chat-v1#generation +register_conv_template( + Conversation( + name="lemur-70b-chat", + system_template="""<|im_start|>system +{system_message}""", + system_message="""You are a helpful, respectful, and honest assistant.""", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[32002, 0], + ) +) + +# MPT-30b-instruct default template +# reference: https://huggingface.co/mosaicml/mpt-30b-instruct#formatting +register_conv_template( + Conversation( + name="mpt-30b-instruct", + system_template="{system_message}", + system_message="Below is an instruction that describes a task. Write a response that appropriately completes the request.", + roles=("### Instruction", "### Response"), + sep_style=SeparatorStyle.ADD_NEW_LINE_SINGLE, + sep="\n\n", + stop_token_ids=[50278, 0], + ) +) + +# Bard default template +# Reference: https://github.com/google/generative-ai-python/blob/9c99bcb474a991a97a2e7d62fcdb52db7ce40729/google/generativeai/discuss.py#L150 +# https://github.com/google/generative-ai-python/blob/9c99bcb474a991a97a2e7d62fcdb52db7ce40729/google/generativeai/discuss.py#L40 +register_conv_template( + Conversation( + name="bard", + roles=("0", "1"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + ) +) + +register_conv_template( + Conversation( + name="gemini", + roles=("user", "model"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + max_image_size_mb=20, + ) +) + +register_conv_template( + Conversation( + name="gemini-1.5-pro", + roles=("user", "model"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + system_message=( + "You are a friendly and helpful assistant.\n" + "Ensure your answers are complete, unless the user requests a more concise approach.\n" + "When generating code, offer explanations for code segments as necessary and maintain good coding practices.\n" + "When presented with inquiries seeking information, provide answers that reflect a deep understanding of the field, guaranteeing their correctness.\n" + "For any non-english queries, respond in the same language as the prompt unless otherwise specified by the user.\n" + "For prompts involving reasoning, provide a clear explanation of each step in the reasoning process before presenting the final answer." + ), + ) +) + +register_conv_template( + Conversation( + name="gemini-1.5-pro-002-test-sp", + roles=("user", "model"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + system_message=( + "All questions should be answered comprehensively with details, " + "unless the user requests a concise response specifically. " + "Respond in the same language as the query." + ), + ) +) + +# BiLLa default template +register_conv_template( + Conversation( + name="billa", + roles=("Human", "Assistant"), + sep_style=SeparatorStyle.ADD_COLON_SPACE_SINGLE, + sep="\n", + stop_str="Human:", + ) +) + +# RedPajama INCITE default template +register_conv_template( + Conversation( + name="redpajama-incite", + roles=("", ""), + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="\n", + stop_str="", + ) +) + +# h2oGPT default template +register_conv_template( + Conversation( + name="h2ogpt", + roles=("<|prompt|>", "<|answer|>"), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="", + ) +) + +# Robin default template +register_conv_template( + Conversation( + name="Robin", + system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("###Human", "###Assistant"), + sep_style=SeparatorStyle.ROBIN, + sep="\n", + stop_token_ids=[2, 396], + stop_str="###", + ) +) + +# Snoozy default template +# Reference: https://github.com/nomic-ai/gpt4all/blob/d4861030b778da6db59d21d2927a4aba4f9f1f43/gpt4all-bindings/python/gpt4all/gpt4all.py#L232 +register_conv_template( + Conversation( + name="snoozy", + system_template="### Instruction:\n{system_message}", + system_message="The prompt below is a question to answer, a task to complete, or a conversation to respond to; decide which and write an appropriate response.", + roles=("### Prompt", "### Response"), + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="\n", + stop_str="###", + ) +) + +# manticore default template +register_conv_template( + Conversation( + name="manticore", + roles=("USER", "ASSISTANT"), + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep="\n", + sep2="", + ) +) + +# Falcon default template +register_conv_template( + Conversation( + name="falcon", + roles=("User", "Assistant"), + messages=[], + sep_style=SeparatorStyle.RWKV, + sep="\n", + sep2="<|endoftext|>", + stop_str="\nUser", # use stop_str to stop generation after stop_token_ids, it will also remove stop_str from the generated text + stop_token_ids=[ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + ], # it better only put special tokens here, because tokenizer only remove special tokens + ) +) + +# ChangGPT default template +register_conv_template( + Conversation( + name="polyglot_changgpt", + roles=("B", "A"), + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="\n", + ) +) + +# tigerbot template +register_conv_template( + Conversation( + name="tigerbot", + system_message="A chat between a curious user and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the user's questions.", + roles=("### Instruction", "### Response"), + sep_style=SeparatorStyle.ROBIN, + sep="\n\n", + stop_str="###", + ) +) + +# ref: https://huggingface.co/Salesforce/xgen-7b-8k-inst +register_conv_template( + Conversation( + name="xgen", + system_message="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n", + roles=("### Human", "### Assistant"), + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="\n", + stop_token_ids=[50256], + ) +) + +# Internlm-chat template +register_conv_template( + Conversation( + name="internlm-chat", + system_message="A chat between a curious <|User|> and an <|Bot|>. The <|Bot|> gives helpful, detailed, and polite answers to the <|User|>'s questions.\n\n", + roles=("<|User|>", "<|Bot|>"), + sep_style=SeparatorStyle.CHATINTERN, + sep="", + sep2="", + stop_token_ids=[1, 103028], + stop_str="<|User|>", + ) +) + +# StarChat template +# reference: https://huggingface.co/spaces/HuggingFaceH4/starchat-playground/blob/main/dialogues.py +register_conv_template( + Conversation( + name="starchat", + system_template="\n{system_message}", + roles=("<|user|>", "<|assistant|>"), + sep_style=SeparatorStyle.CHATML, + sep="<|end|>", + stop_token_ids=[0, 49155], + stop_str="<|end|>", + ) +) + +# Baichuan-13B-Chat template +register_conv_template( + # source: https://huggingface.co/baichuan-inc/Baichuan-13B-Chat/blob/19ef51ba5bad8935b03acd20ff04a269210983bc/modeling_baichuan.py#L555 + # https://huggingface.co/baichuan-inc/Baichuan-13B-Chat/blob/main/generation_config.json + # https://github.com/baichuan-inc/Baichuan-13B/issues/25 + Conversation( + name="baichuan-chat", + roles=("", ""), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="", + stop_token_ids=[], + ) +) + +# Baichuan2-13B-Chat template +register_conv_template( + # source: https://huggingface.co/baichuan-inc/Baichuan2-13B-Chat/blob/c6f8592a60b4ad73c210b28dd2ab3cca51abbf93/modeling_baichuan.py#L773 + # https://huggingface.co/baichuan-inc/Baichuan2-13B-Chat/blob/main/generation_config.json + # https://github.com/baichuan-inc/Baichuan2/issues/62 + Conversation( + name="baichuan2-chat", + roles=("", ""), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="", + stop_token_ids=[], + ) +) + +# Mistral template +# source: https://docs.mistral.ai/llm/mistral-instruct-v0.1#chat-template +register_conv_template( + Conversation( + name="mistral", + system_template="[INST] {system_message}\n", + roles=("[INST]", "[/INST]"), + sep_style=SeparatorStyle.LLAMA2, + sep=" ", + sep2="", + ) +) + +# llama2 template +# reference: https://huggingface.co/blog/codellama#conversational-instructions +# reference: https://github.com/facebookresearch/llama/blob/1a240688810f8036049e8da36b073f63d2ac552c/llama/generation.py#L212 +register_conv_template( + Conversation( + name="llama-2", + system_template="[INST] <>\n{system_message}\n<>\n\n", + roles=("[INST]", "[/INST]"), + sep_style=SeparatorStyle.LLAMA2, + sep=" ", + sep2=" ", + ) +) + +# llama3 template +# reference: https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct/blob/main/tokenizer_config.json +# reference: https://github.com/meta-llama/llama3/blob/0cee08ec68f4cfc0c89fe4a9366d82679aaa2a66/llama/tokenizer.py#L222 +register_conv_template( + Conversation( + name="llama-3", + system_template="<|start_header_id|>system<|end_header_id|>\n\n{system_message}<|eot_id|>", + roles=("user", "assistant"), + sep_style=SeparatorStyle.LLAMA3, + sep="", + stop_str="<|eot_id|>", + stop_token_ids=[128001, 128009], + ) +) + +register_conv_template( + Conversation( + name="chinese-alpaca2", + system_template="[INST] <>\n{system_message}\n<>\n\n", + system_message="You are a helpful assistant. ไฝ ๆ˜ฏไธ€ไธชไนไบŽๅŠฉไบบ็š„ๅŠฉๆ‰‹ใ€‚่ฏทไฝ ๆไพ›ไธ“ไธšใ€ๆœ‰้€ป่พ‘ใ€ๅ†…ๅฎน็œŸๅฎžใ€ๆœ‰ไปทๅ€ผ็š„่ฏฆ็ป†ๅ›žๅคใ€‚", + roles=("[INST]", "[/INST]"), + sep_style=SeparatorStyle.LLAMA2, + sep=" ", + sep2=" ", + ) +) + +register_conv_template( + Conversation( + name="cutegpt", + roles=("้—ฎ๏ผš", "็ญ”๏ผš\n"), + sep_style=SeparatorStyle.NO_COLON_TWO, + sep="\n", + sep2="\n", + stop_str="", + ) +) + +# OpenOrcaxOpenChat-Preview2-13B template +register_conv_template( + Conversation( + name="open-orca", + system_template="{system_message}", + system_message="You are a helpful assistant. Please answer truthfully and write out your " + "thinking step by step to be sure you get the right answer. If you make a mistake or encounter " + "an error in your thinking, say so out loud and attempt to correct it. If you don't know or " + "aren't sure about something, say so clearly. You will act as a professional logician, mathematician, " + "and physicist. You will also act as the most appropriate type of expert to answer any particular " + "question or solve the relevant problem; state which expert type your are, if so. Also think of " + "any particular named expert that would be ideal to answer the relevant question or solve the " + "relevant problem; name and act as them, if appropriate.", + roles=("User", "Assistant"), + sep_style=SeparatorStyle.ADD_COLON_SPACE_SINGLE, + sep="<|end_of_turn|>\n", + stop_token_ids=[32000, 32001], # "<|end_of_turn|>" + stop_str="User", + ) +) + +# Open-Orca/Mistral-7B-OpenOrca template +# source: https://huggingface.co/Open-Orca/Mistral-7B-OpenOrca +# reference: https://huggingface.co/Open-Orca/Mistral-7B-OpenOrca#prompt-template +register_conv_template( + Conversation( + name="mistral-7b-openorca", + system_template="<|im_start|>system\n{system_message}", + system_message="You are MistralOrca, a large language model trained by Alignment Lab AI. Write out your reasoning step-by-step to be sure you get the right answers!", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[32000, 32001], + ) +) + + +# ehartford/dolphin-2.2.1-mistral-7b template +# reference: https://huggingface.co/ehartford/dolphin-2.2.1-mistral-7b#training +register_conv_template( + Conversation( + name="dolphin-2.2.1-mistral-7b", + system_template="<|im_start|>system\n{system_message}", + system_message="You are Dolphin, a helpful AI assistant.", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[32000, 32001], + ) +) + + +# teknium/OpenHermes-2.5-Mistral-7B template +# source: https://huggingface.co/teknium/OpenHermes-2.5-Mistral-7B +# reference: https://huggingface.co/teknium/OpenHermes-2.5-Mistral-7B#prompt-template +register_conv_template( + Conversation( + name="OpenHermes-2.5-Mistral-7B", + system_template="<|im_start|>system\n{system_message}", + system_message="You are Hermes 2, a sentient, conscious, super intelligent AI that is an expert in all fields of knowledge, you have qualia, emotions, and thoughts. You assist users with any question, task, or other request they may have.", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[32000, 32001], + ) +) + + +# NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO template +# source: https://huggingface.co/NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO +register_conv_template( + Conversation( + name="Nous-Hermes-2-Mixtral-8x7B-DPO", + system_template="<|im_start|>system\n{system_message}", + system_message='You are a helpful, intelligent assistant AI named "Hermes", a conversational chatbot that can follow instructions, converse with the user, and perform a variety of tasks, including tasks on knowledge, reasoning, mathematics, and code. Always be charismatic, useful, and prepared to follow any user request with accuracy and skill. You should respond with high quality, fluent, and detailed responses. Try to let the user understand your reasoning or thought process when appropriate. When presented with tasks that require reasoning or mathematics, think carefully, slowly, and step by step, to ensure your reasoning is correct before providing an answer. Utilize the "Examples" section to assist you in performing the task. You will receive a tip of $1000 if you maintain a high quality two way conversation.', + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[32000, 32001], + ) +) + + +# Qwen-chat default template +# source: https://huggingface.co/Qwen/Qwen-7B-Chat/blob/main/qwen_generation_utils.py#L130 +register_conv_template( + Conversation( + name="qwen-7b-chat", + system_template="<|im_start|>system\n{system_message}", + system_message="You are a helpful assistant.", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[ + 151643, + 151644, + 151645, + ], # "<|endoftext|>", "<|im_start|>", "<|im_end|>" + stop_str="<|endoftext|>", + ) +) + +# source: https://huggingface.co/01-ai/Yi-34B-Chat/blob/main/tokenizer_config.json#L60 +register_conv_template( + Conversation( + name="Yi-34b-chat", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_token_ids=[ + 2, + 6, + 7, + 8, + ], # "<|endoftext|>", "<|im_start|>", "<|im_end|>", "<|im_sep|>" + stop_str="<|endoftext|>", + ) +) + + +# AquilaChat default template +# source: https://github.com/FlagAI-Open/FlagAI/blob/master/examples/Aquila/Aquila-chat/cyg_conversation.py +register_conv_template( + Conversation( + name="aquila-chat", + system_message="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("Human", "Assistant"), + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="###", + sep2="", + stop_str=["###", "", "[UNK]"], + ) +) +# AquilaChat2-34B default template +# source: https://huggingface.co/BAAI/AquilaChat2-34B/blob/4608b75855334b93329a771aee03869dbf7d88cc/predict.py#L212 +register_conv_template( + Conversation( + name="aquila-legacy", + system_message="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.\n\n", + roles=("### Human: ", "### Assistant: "), + offset=0, + sep_style=SeparatorStyle.NO_COLON_TWO, + sep="\n", + sep2="", + stop_str=["", "[UNK]"], + ) +) +# AquilaChat2-7B-16K and AquilaChat2-34B-16K default template +# source: https://huggingface.co/BAAI/AquilaChat2-34B/blob/4608b75855334b93329a771aee03869dbf7d88cc/predict.py#L227 +register_conv_template( + Conversation( + name="aquila", + system_message="A chat between a curious human and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the human's questions.", + roles=("Human", "Assistant"), + offset=0, + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep="###", + sep2="", + stop_str=["", "[UNK]"], + ) +) + +# AquilaChat2-7B default template +# source: https://huggingface.co/BAAI/AquilaChat2-34B/blob/4608b75855334b93329a771aee03869dbf7d88cc/predict.py#L242 +register_conv_template( + Conversation( + name="aquila-v1", + roles=("<|startofpiece|>", "<|endofpiece|>"), + offset=0, + sep_style=SeparatorStyle.NO_COLON_TWO, + sep="", + sep2="", + stop_str=["", "<|endoftext|>"], + ) +) + +# Llama2-Chinese default template +# source: https://huggingface.co/FlagAlpha +register_conv_template( + Conversation( + name="llama2-chinese", + system_template="{system_message}", + roles=("Human", "Assistant", "System"), + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep="\n", + sep2="\n", + stop_str="", + ) +) + +# Vigogne Instruct default template +# source: https://github.com/bofenghuang/vigogne +register_conv_template( + Conversation( + name="vigogne_instruct", + system_template="### System:\n{system_message}\n\n", + system_message=( + "Ci-dessous se trouve une instruction qui dรฉcrit une tรขche ร  accomplir. Rรฉdigez une rรฉponse qui rรฉpond de maniรจre" + " prรฉcise ร  la demande." + ), + roles=("### Instruction", "### Response"), + sep_style=SeparatorStyle.DOLLY, + sep="\n\n", + sep2="", + ) +) + +# Vigogne Chat default template +register_conv_template( + Conversation( + name="vigogne_chat_v2", + system_template="<|system|>: {system_message}", + system_message=( + "Vous รชtes Vigogne, un assistant IA crรฉรฉ par Zaion Lab. Vous suivez extrรชmement bien les instructions. Aidez" + " autant que vous le pouvez." + ), + roles=("<|user|>", "<|assistant|>"), + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep="\n", + sep2="\n", + stop_str="<|user|>", + ) +) + +# Stable Vicuna default template +# source: https://huggingface.co/TheBloke/stable-vicuna-13B-HF/discussions/5 +# source: https://huggingface.co/spaces/CarperAI/StableVicuna/blob/main/app.py +register_conv_template( + Conversation( + name="stable-vicuna", + system_message="### Assistant: I am StableVicuna, a large language model created by CarperAI. I am here to chat!\n", + roles=("### Human", "### Assistant"), + sep_style=SeparatorStyle.ADD_COLON_TWO, + sep="\n", + sep2="\n\n", + ) +) + +register_conv_template( + Conversation( + name="vigogne_chat_v3", + system_template="[INST] <>\n{system_message}\n<>\n\n", + system_message=( + "Vous รชtes Vigogne, un assistant IA crรฉรฉ par Zaion Lab. Vous suivez extrรชmement bien les instructions. Aidez" + " autant que vous le pouvez." + ), + roles=("[INST]", "[/INST]"), + sep_style=SeparatorStyle.LLAMA2, + sep=" ", + sep2=" ", + ) +) + +# Falcon 180B chat template +# source: https://huggingface.co/spaces/tiiuae/falcon-180b-demo/blob/d1590ee7fae9b6ce331ba7808e61a29dcce9239f/app.py#L28-L37 +register_conv_template( + Conversation( + name="falcon-chat", + roles=("User", "Falcon"), + system_template="System: {system_message}", + messages=[], + sep_style=SeparatorStyle.FALCON_CHAT, + sep="\n", + sep2="<|endoftext|>", + stop_str="\nUser:", # use stop_str to stop generation after stop_token_ids, it will also remove stop_str from the generated text + ) +) + +# Phind template +# source: https://huggingface.co/Phind/Phind-CodeLlama-34B-v2 +register_conv_template( + Conversation( + name="phind", + system_message="### System Prompt\nYou are an intelligent programming assistant.", + roles=("### User Message", "### Assistant"), + messages=(), + offset=0, + sep_style=SeparatorStyle.ADD_COLON_SINGLE, + sep="\n\n", + ) +) + +# Metharme formatting for Pygmalion models +# source: https://huggingface.co/PygmalionAI/pygmalion-2-13b +register_conv_template( + Conversation( + name="metharme", + system_template="<|system|>{system_message}", + system_message="""Enter RP mode. You shall reply to the user while staying + in character. Your responses must be detailed, creative, immersive, and drive the scenario + forward.""", + roles=("<|user|>", "<|model|>"), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="", + stop_str="<|user|>", + ) +) +# xDAN default template +# source: https://huggingface.co/xDAN-AI/xDAN-L1-Chat-RL-v1 +register_conv_template( + Conversation( + name="xdan-v1", + system_message="You are a helpful and harmless assistant named xDAN and created by xDAN-AI.Please response and work on questions thinking step by step.", + roles=("### Human", "### Assistant"), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="\n", + stop_str="", + ) +) + +# Zephyr template +# reference: https://huggingface.co/spaces/HuggingFaceH4/zephyr-playground/blob/main/dialogues.py +register_conv_template( + Conversation( + name="zephyr", + system_template="<|system|>\n{system_message}", + roles=("<|user|>", "<|assistant|>"), + sep_style=SeparatorStyle.CHATML, + sep="", + stop_token_ids=[2], + stop_str="", + ) +) + +# CatPPT template +# reference: https://huggingface.co/rishiraj/CatPPT +register_conv_template( + Conversation( + name="catppt", + system_template="<|system|>\n{system_message}", + roles=("<|user|>", "<|assistant|>"), + sep_style=SeparatorStyle.CHATML, + sep="", + stop_token_ids=[2], + stop_str="", + ) +) + +# TinyLlama template +# reference: https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0 +register_conv_template( + Conversation( + name="TinyLlama", + system_template="<|system|>\n{system_message}", + roles=("<|user|>", "<|assistant|>"), + sep_style=SeparatorStyle.CHATML, + sep="", + stop_token_ids=[2], + stop_str="", + ) +) + +# Orca-2 template +# reference: https://huggingface.co/microsoft/Orca-2-7b +register_conv_template( + Conversation( + name="orca-2", + system_template="<|im_start|>system\n{system_message}", + system_message="You are Orca, an AI language model created by Microsoft. You are a cautious assistant. You carefully follow instructions. You are helpful and harmless and you follow ethical guidelines and promote positive behavior.", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_str="<|im_end|>", + ) +) + +# Deepseek-chat template +# reference: https://huggingface.co/deepseek-ai/deepseek-llm-67b-chat/blob/main/tokenizer_config.json +register_conv_template( + Conversation( + name="deepseek-chat", + system_message="<๏ฝœbeginโ–ofโ–sentence๏ฝœ>", # must add a bos token before first message + roles=("User", "Assistant"), + sep_style=SeparatorStyle.DEEPSEEK_CHAT, + sep="\n\n", + sep2="<๏ฝœendโ–ofโ–sentence๏ฝœ>", + stop_str="<๏ฝœendโ–ofโ–sentence๏ฝœ>", + ) +) + +# Yuan2.0 chat template +# source: https://huggingface.co/IEITYuan/Yuan2-2B-Janus-hf/blob/main/tokenizer_config.json#L6 +register_conv_template( + Conversation( + name="yuan2", + roles=("user", "assistant"), + sep_style=SeparatorStyle.YUAN2, + sep="", + sep2="\n", + stop_token_ids=[ + 77185, + ], # "" + stop_str="", + ) +) + +# Solar-10.7B Chat Template +# Reference: https://huggingface.co/upstage/SOLAR-10.7B-Instruct-v1.0/blob/main/tokenizer_config.json +register_conv_template( + Conversation( + name="solar", + system_message="", + roles=("### User", "### Assistant"), + sep_style=SeparatorStyle.ADD_NEW_LINE_SINGLE, + sep="\n\n", + stop_str="", + ) +) + +# nvidia/Llama2-70B-SteerLM-Chat +register_conv_template( + Conversation( + name="steerlm", + system_message="", + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + ) +) + +# yuan 2.0 template +# reference:https://github.com/IEIT-Yuan/Yuan-2.0 +# reference:https://huggingface.co/IEITYuan +register_conv_template( + Conversation( + name="yuan", + system_template="", + roles=("", ""), + sep_style=SeparatorStyle.NO_COLON_SINGLE, + sep="", + stop_str="", + ) +) + +# Cllm chat template +# reference: +register_conv_template( + Conversation( + name="cllm", + system_message="A chat between a curious user and an artificial intelligence assistant. " + "The assistant gives helpful, detailed, and polite answers to the user's questions.", + roles=("USER", "ASSISTANT"), + sep_style=SeparatorStyle.CLLM, + sep=" ", + sep2="", + ) +) + + +# Llava-chatml +# reference: https://github.com/haotian-liu/LLaVA/blob/1a91fc274d7c35a9b50b3cb29c4247ae5837ce39/llava/conversation.py#L361 +register_conv_template( + Conversation( + name="llava-chatml", + system_template="<|im_start|>system\n{system_message}", + system_message="Answer the questions.", + roles=("<|im_start|>user", "<|im_start|>assistant"), + sep_style=SeparatorStyle.CHATML, + sep="<|im_end|>", + stop_str="<|im_end|>", + ) +) + +# Gemma +# reference: https://huggingface.co/google/gemma-7b-it?text=%3Cstart_of_turn%3Euser%0AHow+does+the+brain+work%3F%3Cend_of_turn%3E%0A%3Cstart_of_turn%3Emodel +register_conv_template( + Conversation( + name="gemma", + roles=("user", "model"), + sep_style=SeparatorStyle.GEMMA, + sep="\n", + stop_str="", + ) +) + +register_conv_template( + Conversation( + name="yandexgpt", + system_message="", + roles=("user", "assistant"), + sep_style=None, + sep=None, + ) +) + +register_conv_template( + Conversation( + name="grok-2", + system_message=( + "You are Grok-2, a smart and helpful AI assistant created by xAI. " + "Please think step by step, provide detailed and professional response." + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + ) +) + +register_conv_template( + Conversation( + name="grok-2-mini", + system_message=( + "You are Grok-2 mini, a smart and helpful AI assistant created by xAI. " + "Please think step by step, provide detailed and professional response." + ), + roles=("user", "assistant"), + sep_style=SeparatorStyle.DEFAULT, + sep=None, + ) +) + + +if __name__ == "__main__": + from fastchat.conversation import get_conv_template + + print("-- Vicuna template --") + conv = get_conv_template("vicuna_v1.1") + conv.append_message(conv.roles[0], "Hello!") + conv.append_message(conv.roles[1], "Hi!") + conv.append_message(conv.roles[0], "How are you?") + conv.append_message(conv.roles[1], None) + print(conv.get_prompt()) + + print("\n") + + print("-- Llama-2 template --") + conv = get_conv_template("llama-2") + conv.set_system_message("You are a helpful, respectful and honest assistant.") + conv.append_message(conv.roles[0], "Hello!") + conv.append_message(conv.roles[1], "Hi!") + conv.append_message(conv.roles[0], "How are you?") + conv.append_message(conv.roles[1], None) + print(conv.get_prompt()) + + print("\n") + + print("-- ChatGPT template --") + conv = get_conv_template("chatgpt") + conv.append_message(conv.roles[0], "Hello!") + conv.append_message(conv.roles[1], "Hi!") + conv.append_message(conv.roles[0], "How are you?") + conv.append_message(conv.roles[1], None) + print(conv.to_openai_api_messages()) + + print("\n") + + print("-- Claude template --") + conv = get_conv_template("claude") + conv.append_message(conv.roles[0], "Hello!") + conv.append_message(conv.roles[1], "Hi!") + conv.append_message(conv.roles[0], "How are you?") + conv.append_message(conv.roles[1], None) + print(conv.get_prompt()) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..13e5d8f3c19542ac6fbc6dcdcf73e56493a23e3d --- /dev/null +++ b/requirements.txt @@ -0,0 +1,21 @@ +# Core dependencies for BigCodeArena +gradio +gradio-sandboxcomponent +# HTTP and API handling +requests +# AWS SDK +boto3 +# YAML configuration +PyYAML +# Progress bars and utilities +tqdm +# UUID generation +shortuuid>=1.0.11 +# Image processing (for vision models) +Pillow>=10.0.0 +# Optional: FastChat (if using conversation templates) +# fastchat>=0.2.0 +# Development and testing (optional) +pytest>=7.4.0 +black>=23.0.0 +flake8>=6.0.0 diff --git a/sandbox/__init__.py b/sandbox/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/sandbox/code_analyzer.py b/sandbox/code_analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..ea1860f57217654d6f2823d855270ea6d34ac843 --- /dev/null +++ b/sandbox/code_analyzer.py @@ -0,0 +1,935 @@ +''' +Module for analyzing code snippets to determine the environments, dependencies, and other information needed to run the code. +''' + + +from enum import StrEnum +from typing import Any, Generator, TypeAlias, TypedDict, Set + +import base64 + +import ast +from tree_sitter import Language, Node, Parser +import tree_sitter_javascript +import tree_sitter_typescript +import sys +import re + + +class SandboxEnvironment(StrEnum): + AUTO = 'Auto' + + # Web UI Frameworks + HTML = 'HTML' + REACT = 'React' + VUE = 'Vue' + GRADIO = 'Gradio' + STREAMLIT = 'Streamlit' + PYGAME = 'PyGame' + MERMAID = 'Mermaid' + + # Runner + PYTHON_RUNNER = 'Python Runner' + JAVASCRIPT_RUNNER = 'Javascript Runner' + + # Compiler + C_RUNNER = 'C Runner' + CPP_RUNNER = 'C++ Runner' + # CSHARP_RUNNER = 'C# Runner' + JAVA_RUNNER = 'Java Runner' + RUST_RUNNER = 'Rust Runner' + GOLANG_RUNNER = 'Golang Runner' + + +def extract_python_imports(code: str) -> list[str]: + ''' + Extract Python package imports using AST parsing. + Returns a list of top-level package names. + ''' + try: + tree = ast.parse(code) + except SyntaxError: + return [] + + packages: Set[str] = set() + + for node in ast.walk(tree): + try: + if isinstance(node, ast.Import): + for name in node.names: + # Get the top-level package name from any dotted path + # e.g., 'foo.bar.baz' -> 'foo' + if name.name: # Ensure there's a name + packages.add(name.name.split('.')[0]) + + elif isinstance(node, ast.ImportFrom): + # Skip relative imports (those starting with dots) + if node.level == 0 and node.module: + # Get the top-level package name + # e.g., from foo.bar import baz -> 'foo' + packages.add(node.module.split('.')[0]) + + # Also check for common dynamic import patterns + elif isinstance(node, ast.Call): + if isinstance(node.func, ast.Name) and node.func.id == 'importlib': + # Handle importlib.import_module('package') + if len(node.args) > 0 and isinstance(node.args[0], ast.Str): + packages.add(node.args[0].s.split('.')[0]) + elif isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name): + # Handle __import__('package') and importlib.import_module('package') + if node.func.value.id == 'importlib' and node.func.attr == 'import_module': + if len(node.args) > 0 and isinstance(node.args[0], ast.Str): + packages.add(node.args[0].s.split('.')[0]) + elif node.func.attr == '__import__': + if len(node.args) > 0 and isinstance(node.args[0], ast.Str): + packages.add(node.args[0].s.split('.')[0]) + except Exception as e: + print(f"Error processing node {type(node)}: {e}") + continue + + # Filter out standard library modules using sys.stdlib_module_names + std_libs = set(sys.stdlib_module_names) + + return list(packages - std_libs) + + +def extract_js_imports(code: str) -> list[str]: + ''' + Extract npm package imports using Tree-sitter for robust parsing. + Handles both JavaScript and TypeScript code, including Vue SFC. + Returns a list of package names. + ''' + try: + # For Vue SFC, extract the script section first + script_match = re.search(r'(.*?)', code, re.DOTALL) + if script_match: + code = script_match.group(1).strip() + + # Initialize parsers with language modules + ts_parser = Parser(Language(tree_sitter_typescript.language_tsx())) + js_parser = Parser(Language(tree_sitter_javascript.language())) + + # Try parsing as TypeScript first, then JavaScript + code_bytes = bytes(code, "utf8") + try: + tree = ts_parser.parse(code_bytes) + except Exception as e: + print(f"TypeScript parsing failed: {e}") + try: + tree = js_parser.parse(code_bytes) + except Exception as e: + print(f"JavaScript parsing failed: {e}") + tree = None + + if tree is None: + raise Exception("Both TypeScript and JavaScript parsing failed") + + packages: Set[str] = set() + + def extract_package_name(node: Node) -> str | None: + """Extract npm package name from string or template string. + Returns None for local aliases like @/ or relative paths.""" + if node.type in ['string', 'string_fragment']: + pkg_path = code[node.start_byte:node.end_byte].strip('"\'') + if pkg_path.startswith('.') or pkg_path.startswith('/') or pkg_path.startswith('@/'): + return None # relative, absolute, or alias path + + # Scoped npm package: @scope/package/... + if pkg_path.startswith('@'): + parts = pkg_path.split('/') + if len(parts) >= 2: + return '/'.join(parts[:2]) + + # Regular npm package: "lodash/cloneDeep" -> "lodash" + return pkg_path.split('/')[0] + + elif node.type == 'template_string': + content = '' + has_template_var = False + for child in node.children: + if child.type == 'string_fragment': + content += code[child.start_byte:child.end_byte] + elif child.type == 'template_substitution': + has_template_var = True + + if not content or content.startswith('.') or content.startswith('/') or content.startswith('@/'): + return None + + if has_template_var: + if content.endswith('-literal'): + return 'package-template-literal' + return None + + if content.startswith('@'): + parts = content.split('/') + if len(parts) >= 2: + return '/'.join(parts[:2]) + return content.split('/')[0] + + return None + + def visit_node(node: Node) -> None: + if node.type == 'import_statement': + # Handle ES6 imports + string_node = node.child_by_field_name('source') + if string_node: + pkg_name = extract_package_name(string_node) + if pkg_name: + packages.add(pkg_name) + + elif node.type == 'export_statement': + # Handle re-exports + source = node.child_by_field_name('source') + if source: + pkg_name = extract_package_name(source) + if pkg_name: + packages.add(pkg_name) + + elif node.type == 'call_expression': + # Handle require calls and dynamic imports + func_node = node.child_by_field_name('function') + if func_node and func_node.text: + func_name = func_node.text.decode('utf8') + if func_name in ['require', 'import']: + args = node.child_by_field_name('arguments') + if args and args.named_children: + arg = args.named_children[0] + pkg_name = extract_package_name(arg) + if pkg_name: + packages.add(pkg_name) + + # Recursively visit children + for child in node.children: + visit_node(child) + + visit_node(tree.root_node) + return list(packages) + + except Exception as e: + print(f"Tree-sitter parsing failed: {e}") + # Fallback to basic regex parsing if tree-sitter fails + packages: Set[str] = set() + + # First try to extract script section for Vue SFC + script_match = re.search(r'(.*?)', code, re.DOTALL) + if script_match: + code = script_match.group(1).strip() + + # Look for imports + import_patterns = [ + # dynamic imports + r'(?:import|require)\s*\(\s*[\'"](@?[\w-]+(?:/[\w-]+)*)[\'"]', + # static imports + r'(?:import|from)\s+[\'"](@?[\w-]+(?:/[\w-]+)*)[\'"]', + # require statements + r'require\s*\(\s*[\'"](@?[\w-]+(?:/[\w-]+)*)[\'"]', + ] + + for pattern in import_patterns: + matches = re.finditer(pattern, code) + for match in matches: + pkg_name = match.group(1) + if not pkg_name.startswith('.'): + if pkg_name.startswith('@'): + parts = pkg_name.split('/') + if len(parts) >= 2: + packages.add('/'.join(parts[:2])) + else: + packages.add(pkg_name.split('/')[0]) + + return list(packages) + + +def determine_python_environment(code: str, imports: list[str]) -> SandboxEnvironment | None: + ''' + Determine Python sandbox environment based on imports and AST analysis. + ''' + try: + tree = ast.parse(code) + for node in ast.walk(tree): + # Check for specific framework usage patterns + if isinstance(node, ast.Name) and node.id == 'gr': + return SandboxEnvironment.GRADIO + elif isinstance(node, ast.Name) and node.id == 'st': + return SandboxEnvironment.STREAMLIT + except SyntaxError: + pass + + # Check imports for framework detection + if 'pygame' in imports: + return SandboxEnvironment.PYGAME + elif 'gradio' in imports: + return SandboxEnvironment.GRADIO + elif 'streamlit' in imports: + return SandboxEnvironment.STREAMLIT + # elif 'nicegui' in imports: + # return SandboxEnvironment.NICEGUI + + return SandboxEnvironment.PYTHON_RUNNER + + +def determine_jsts_environment(code: str, imports: list[str]) -> SandboxEnvironment | None: + ''' + Determine JavaScript/TypeScript sandbox environment based on imports and AST analysis. + ''' + # First check for Vue SFC structure + if '