Streaming Output

更新时间:
复制 MD 格式

Code Interpreter can receive stdout, stderr, and rich-result callbacks while code is running. Streaming output is useful for real-time frontend display, server-side log collection, and progress feedback for long analysis tasks.

stdout and stderr

JavaScript and TypeScript use onStdout and onStderr:

await sandbox.runCode(
  `
import sys
import time

print("start")
time.sleep(3)
print("warning", file=sys.stderr)
time.sleep(3)
print("done")
`,
  {
    onStdout: (data) => console.log("stdout:", data),
    onStderr: (data) => console.error("stderr:", data),
    onError: (error) => console.error("error:", error),
  },
);

The Python SDK uses on_stdout and on_stderr. Callback parameters are output chunks and usually include content, whether the chunk is stderr, and a timestamp. Do not assume a single callback corresponds to one complete business log line.

sandbox.run_code(
    """
import sys
import time

print("start")
time.sleep(3)
print("warning", file=sys.stderr)
time.sleep(3)
print("done")
""",
    on_stdout=lambda data: print("stdout:", data),
    on_stderr=lambda data: print("stderr:", data),
    on_error=lambda error: print("error:", error),
)

Rich results

Rich results such as tables and text can also be received through callbacks before the final result is returned. For charts, write files and retrieve them through Filesystem.

await sandbox.runCode(
  `
import pandas as pd

df = pd.DataFrame({"value": [1, 2, 3]})
df
`,
  {
    onResult: (result) => console.log("result:", result),
  },
);

The Python SDK uses the corresponding snake_case callback parameters. Follow the parameter names exposed by your current SDK version.

sandbox.run_code(
    """
import pandas as pd

df = pd.DataFrame({"value": [1, 2, 3]})
df
""",
    on_result=lambda result: print("result:", result),
)

Recommendations

  • Use streaming callbacks for user experience and log observation, but determine success from the final execution.error and returned result.

  • When log volume is high, truncate, sample, or persist logs on the business side instead of keeping the full output in memory.

  • In frontend displays, separate stdout, stderr, rich results, and final status.

  • If the current FC Agent Sandbox template or SDK does not trigger rich-result callbacks, fall back to waiting for the final execution.results.