All guides

Gradio code artifacts: send a chat reply to a separate editor

Use additional_outputs to show a Python snippet in Code, checking return order and clearing it when the next reply has no code.

AINavWritten / Updated Sources checked
On this page

At a glance

A separate code editor makes a snippet from a chat reply easier to inspect line by line. Gradio ChatInterface accepts additional_outputs so its callback can return the chat text and values for other components. This task extracts Python from a fixed teaching reply: python produces a snippet and other inputs produce a reply without code. Check that the original chat text and editor belong to the same turn. The example calls no model and executes no extracted code.

Chat and code output paths

  1. Input and teaching reply

    Input python produces a fixed fenced reply; other inputs produce text without code.

  2. Extract the snippet

    Extract the first complete Python fence under the example rule while retaining the chat text.

  3. Additional output

    Return the reply and Code update in order, using an empty editor when no code matches.

The callback returns the chat reply and the additional component value; extraction rules are explained below.

Define the snippet to deliver

Use an existing Python environment that can run Gradio. The teaching inputs are python and hello, without private data or API credentials. This parser handles only the first complete Python fence, with a newline after its opening marker and a closing marker. Other formats are not guessed to be Python. Real model replies may contain several fences or explanations, so extend the rule only after defining that task.

Match chat and additional return values

The ChatInterface callback still receives message and history; this example does not read history. The first return value is the full chat reply. Later values correspond in order to the additional_outputs list. One Code component therefore needs two returned values on every call. Returning only a snippet updates the chat reply without delivering a separate editor value.

1. Define the extra component in Blocks

Additional output components must already be defined in the same gr.Blocks() context. ChatInterface does not render them automatically. Define artifact with render=False, pass it through additional_outputs=[artifact], and call artifact.render() after the chat interface. This follows the documented layout approach and places the code editor below chat.

2. Run the complete page

Example: chat text and a separate Python editor
python
import re

import gradio as gr


SAMPLE_REPLY = 'A teaching snippet:\n\n```python\nprint("paper cup")\n```'


def chat(message, history):
    reply = (
        SAMPLE_REPLY
        if message.strip().lower() == "python"
        else "No code in this reply."
    )
    match = re.search(
        r"```python[ \t]*\n(.*?)```", reply, flags=re.DOTALL
    )
    snippet = match.group(1).rstrip() if match else ""
    return reply, gr.Code(value=snippet, language="python")


with gr.Blocks() as demo:
    artifact = gr.Code(label="Python snippet", language="python", render=False)
    gr.ChatInterface(
        fn=chat,
        examples=["python", "hello"],
        additional_outputs=[artifact],
    )
    artifact.render()


demo.launch()

Save the script as chat_artifact.py, run python chat_artifact.py in your existing environment, and open the address actually printed in the startup log. SAMPLE_REPLY is fixed teaching material and the callback calls no model. The regular expression extracts text. gr.Code(value=snippet, language="python") updates the component value and language; it neither runs the snippet nor proves it correct.

3. Check the current turn with two inputs

Expected outputs for teaching inputs
InputChatCode editor
pythonThe complete fenced teaching replyprint("paper cup")
helloNo code in this reply.Empty string, replacing the previous snippet

These values follow from the code, not an observed screenshot. Enter python and then hello, checking that the second turn does not retain the earlier snippet. Every call returns an empty string or a new extracted value, so a reply without code does not leave stale code beside it. A populated editor alone does not establish that it belongs to the latest reply.

Extraction failure and code review

Without a complete match, return an empty editor while preserving the chat text. The function does not add a missing closing fence. If the callback fails or returns the wrong number of values, check the output-to-component contract without inventing an artifact. Code display and editing do not replace syntax checks, dependency checks or permission to execute. Review model code separately before any execution; do not pass the extracted text directly to eval or exec.

Completion and shutdown

  • The extra component is defined in Blocks and appears below chat without assumed automatic rendering.
  • Each callback returns two matching values, retains chat text and shows the current turn’s matched snippet.
  • A reply without code or with an incomplete fence leaves an empty editor rather than a stale snippet or invented function body.
  • Teaching replies remain distinct from model output and the component executes no extracted text.

After checking the page, stop the script in its terminal. The official ChatInterface guide was read to verify extra return values, Code updates and rendering placement. Gradio was not installed or launched, no model was called and no UI output observed. This original teaching example follows documented interfaces; verify it under your own version before integration.

Article sources

Original editorial content; official descriptions and checking suggestions are distinguished.

  1. Gradio · Official sources
    View details