Files
2026-05-26 13:00:18 +00:00

64 lines
1.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
import json
from typing import Dict
from duckduckgo_search import DDGS
# Inmemory virtual file system
VIRTUAL_FS: Dict[str, str] = {}
def web_search(query: str) -> str:
"""Search the web via DuckDuckGo and return top5 results.
Each result is formatted as ``Title`` + ``Snippet`` + ``URL``.
The function returns a single string with results separated by newlines.
"""
results = []
with DDGS() as ddgs:
for r in ddgs.text(query, max_results=5):
title = r.get("title", "")
body = r.get("body", "")
href = r.get("href", "")
results.append(f"{title}\n{body}\n{href}")
return "\n\n".join(results)
def create_virtual_file(filename: str, content: str) -> str:
"""Create or overwrite a file in the virtual file system.
Parameters
----------
filename: str
Name of the file to create.
content: str
File content.
"""
VIRTUAL_FS[filename] = content
return f"File {filename} created with {len(content)} characters."
def list_virtual_files() -> str:
"""Return a list of filenames stored in the virtual file system."""
if not VIRTUAL_FS:
return "No files in virtual FS."
return "\n".join(sorted(VIRTUAL_FS.keys()))
def export_files(output_dir: str = "output") -> str:
"""Export all virtual files to the local filesystem.
Parameters
----------
output_dir: str
Directory where files will be written. The directory is created if it
does not exist.
"""
os.makedirs(output_dir, exist_ok=True)
for fname, content in VIRTUAL_FS.items():
path = os.path.join(output_dir, fname)
with open(path, "w", encoding="utf-8") as f:
f.write(content)
return f"Exported {len(VIRTUAL_FS)} files to {output_dir}."
# End of tools module