# /// script # requires-python = ">=3.10" # dependencies = [ # "gradio==5.49.1", # "openai", # ] # /// import argparse import re import gradio as gr from openai import OpenAI def chat_function(message, history, endpoint, model_name, key, temperature, top_p, max_tokens): """ Chat function that communicates with OpenAI-compatible endpoint. """ client = OpenAI(api_key=key, base_url=f"http://{endpoint}/v1" if not endpoint.startswith("http") else endpoint) messages = [] for msg in history: if msg["role"] in ["user", "assistant"]: msg_content = msg["content"] if "" in msg_content: msg_content = msg_content.split("")[-1] messages.append({"role": msg["role"], "content": msg_content}) messages.append({"role": "user", "content": message}) try: stream = client.chat.completions.create( model=model_name, messages=messages, stream=True, temperature=temperature, top_p=top_p, max_tokens=int(max_tokens), ) # Initialize buffers current_buffer = "" in_thinking = False thinking_content = "" final_content = "" thinking_blocks = [] seen_non_whitespace = False # Process the stream for chunk in stream: content = chunk.choices[0].delta.content if content is not None: current_buffer += content # Process buffer for complete tags processed = True while processed: processed = False if not in_thinking: # First check if we have enough content to make decisions # Look for first non-whitespace content non_ws_match = re.search(r"\S", current_buffer) if non_ws_match: # We found non-whitespace, now check what it is seen_non_whitespace = True # Check if the non-whitespace starts with a thinking tag think_at_start = re.match(r"^(\s*)", current_buffer) if think_at_start: # Save any whitespace before thinking final_content += think_at_start.group(1) current_buffer = current_buffer[think_at_start.end() :] in_thinking = True thinking_content = "" processed = True continue # Check for thinking tag later in buffer think_match = re.search(r"", current_buffer) if think_match: # Save content before thinking final_content += current_buffer[: think_match.start()] current_buffer = current_buffer[think_match.end() :] in_thinking = True thinking_content = "" processed = True continue # Check if we might be building up to a thinking tag if not seen_non_whitespace or re.search(r"", current_buffer) if end_match: # Extract thinking content thinking_content += current_buffer[: end_match.start()] current_buffer = current_buffer[end_match.end() :] in_thinking = False # Store the thinking block if thinking_content.strip(): thinking_blocks.append(thinking_content.strip()) thinking_content = "" processed = True continue # Check if buffer might contain partial closing tag if re.search(r"