MCPcopy Index your code
hub / github.com/OpenBMB/ChatDev / save_file

Function save_file

functions/function_calling/file.py:358–409  ·  view source on GitHub ↗

Persist data to a workspace file while optionally registering it as an attachment. Args: path: Relative path where the file will be written. content: Plain-text payload encoded with `encoding`. encoding: Text encoding used when `content` is provided. mode: W

(
    path: str,
    content: str,
    *,
    encoding: str = "utf-8",
    mode: Literal["overwrite", "append"] = "overwrite",
    _context: Dict[str, Any] | None = None,
)

Source from the content-addressed store, hash-verified

356
357
358def save_file(
359 path: str,
360 content: str,
361 *,
362 encoding: str = "utf-8",
363 mode: Literal["overwrite", "append"] = "overwrite",
364 _context: Dict[str, Any] | None = None,
365) -> Dict[str, Any]:
366 """
367 Persist data to a workspace file while optionally registering it as an attachment.
368
369 Args:
370 path: Relative path where the file will be written.
371 content: Plain-text payload encoded with `encoding`.
372 encoding: Text encoding used when `content` is provided.
373 mode: Whether to replace the file (`overwrite`) or append to it (`append`).
374
375 Returns:
376 A dictionary describing the persisted file, including workspace path, absolute path,
377 and byte size.
378
379 Raises:
380 ValueError: If arguments are missing/invalid or the path escapes the workspace.
381 OSError: If the file cannot be written.
382 """
383
384 if mode not in {"overwrite", "append"}:
385 raise ValueError("mode must be either 'overwrite' or 'append'")
386
387 ctx = FileToolContext(_context)
388 target = ctx.resolve_under_workspace(path)
389 if target.exists() and target.is_dir():
390 raise ValueError("Target path points to a directory")
391 target.parent.mkdir(parents=True, exist_ok=True)
392
393 data = content.encode(encoding)
394
395 write_mode = "wb" if mode == "overwrite" else "ab"
396 try:
397 with target.open(write_mode) as handle:
398 handle.write(data)
399 except OSError as exc:
400 raise OSError(f"Failed to write file '{target}': {exc}") from exc
401
402 size = target.stat().st_size if target.exists() else None
403 return {
404 "path": ctx.to_workspace_relative(target),
405 "absolute_path": str(target),
406 "size": size,
407 # "mode": mode,
408 # "encoding": encoding if content is not None else None,
409 }
410
411
412def read_text_file_snippet(

Callers

nothing calls this directly

Calls 3

to_workspace_relativeMethod · 0.95
FileToolContextClass · 0.85

Tested by

no test coverage detected