batch_update_doc
Execute multiple document edits in a single batch operation for Google Docs, including text insertion, formatting, table creation, and page breaks, ensuring atomic updates.
Instructions
Executes multiple document operations in a single atomic batch update.
Args: user_google_email: User's Google email address document_id: ID of the document to update operations: List of operation dictionaries. Each operation should contain: - type: Operation type ('insert_text', 'delete_text', 'replace_text', 'format_text', 'insert_table', 'insert_page_break') - Additional parameters specific to each operation type
Example operations: [ {"type": "insert_text", "index": 1, "text": "Hello World"}, {"type": "format_text", "start_index": 1, "end_index": 12, "bold": true}, {"type": "insert_table", "index": 20, "rows": 2, "columns": 3} ]
Returns: str: Confirmation message with batch operation results
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| document_id | Yes | ||
| operations | Yes | ||
| user_google_email | Yes |
Implementation Reference
- gdocs/docs_tools.py:701-756 (handler)Primary handler function for 'batch_update_doc' tool. Decorated with @server.tool() for registration, performs input validation, delegates execution to BatchOperationManager, and returns formatted response with document link.@server.tool() @handle_http_errors("batch_update_doc", service_type="docs") @require_google_service("docs", "docs_write") async def batch_update_doc( service, user_google_email: str, document_id: str, operations: list, ) -> str: """ Executes multiple document operations in a single atomic batch update. Args: user_google_email: User's Google email address document_id: ID of the document to update operations: List of operation dictionaries. Each operation should contain: - type: Operation type ('insert_text', 'delete_text', 'replace_text', 'format_text', 'insert_table', 'insert_page_break') - Additional parameters specific to each operation type Example operations: [ {"type": "insert_text", "index": 1, "text": "Hello World"}, {"type": "format_text", "start_index": 1, "end_index": 12, "bold": true}, {"type": "insert_table", "index": 20, "rows": 2, "columns": 3} ] Returns: str: Confirmation message with batch operation results """ logger.debug(f"[batch_update_doc] Doc={document_id}, operations={len(operations)}") # Input validation validator = ValidationManager() is_valid, error_msg = validator.validate_document_id(document_id) if not is_valid: return f"Error: {error_msg}" is_valid, error_msg = validator.validate_batch_operations(operations) if not is_valid: return f"Error: {error_msg}" # Use BatchOperationManager to handle the complex logic batch_manager = BatchOperationManager(service) success, message, metadata = await batch_manager.execute_batch_operations( document_id, operations ) if success: link = f"https://docs.google.com/document/d/{document_id}/edit" replies_count = metadata.get('replies_count', 0) return f"{message} on document {document_id}. API replies: {replies_count}. Link: {link}" else: return f"Error: {message}"
- Core helper method in BatchOperationManager that orchestrates validation, request building from operations list, batch API execution via documents.batchUpdate, result processing, and metadata generation. Extracts complex logic from the main handler.async def execute_batch_operations( self, document_id: str, operations: list[dict[str, Any]] ) -> tuple[bool, str, dict[str, Any]]: """ Execute multiple document operations in a single atomic batch. This method extracts the complex logic from batch_update_doc tool function. Args: document_id: ID of the document to update operations: List of operation dictionaries Returns: Tuple of (success, message, metadata) """ logger.info(f"Executing batch operations on document {document_id}") logger.info(f"Operations count: {len(operations)}") if not operations: return False, "No operations provided. Please provide at least one operation.", {} try: # Validate and build requests requests, operation_descriptions = await self._validate_and_build_requests(operations) if not requests: return False, "No valid requests could be built from operations", {} # Execute the batch result = await self._execute_batch_requests(document_id, requests) # Process results metadata = { 'operations_count': len(operations), 'requests_count': len(requests), 'replies_count': len(result.get('replies', [])), 'operation_summary': operation_descriptions[:5] # First 5 operations } summary = self._build_operation_summary(operation_descriptions) return True, f"Successfully executed {len(operations)} operations ({summary})", metadata except Exception as e: logger.error(f"Failed to execute batch operations: {str(e)}") return False, f"Batch operation failed: {str(e)}", {}
- gdocs/docs_tools.py:704-756 (schema)Function signature with type hints and comprehensive docstring defining input schema (especially 'operations' list structure with examples) and output format.async def batch_update_doc( service, user_google_email: str, document_id: str, operations: list, ) -> str: """ Executes multiple document operations in a single atomic batch update. Args: user_google_email: User's Google email address document_id: ID of the document to update operations: List of operation dictionaries. Each operation should contain: - type: Operation type ('insert_text', 'delete_text', 'replace_text', 'format_text', 'insert_table', 'insert_page_break') - Additional parameters specific to each operation type Example operations: [ {"type": "insert_text", "index": 1, "text": "Hello World"}, {"type": "format_text", "start_index": 1, "end_index": 12, "bold": true}, {"type": "insert_table", "index": 20, "rows": 2, "columns": 3} ] Returns: str: Confirmation message with batch operation results """ logger.debug(f"[batch_update_doc] Doc={document_id}, operations={len(operations)}") # Input validation validator = ValidationManager() is_valid, error_msg = validator.validate_document_id(document_id) if not is_valid: return f"Error: {error_msg}" is_valid, error_msg = validator.validate_batch_operations(operations) if not is_valid: return f"Error: {error_msg}" # Use BatchOperationManager to handle the complex logic batch_manager = BatchOperationManager(service) success, message, metadata = await batch_manager.execute_batch_operations( document_id, operations ) if success: link = f"https://docs.google.com/document/d/{document_id}/edit" replies_count = metadata.get('replies_count', 0) return f"{message} on document {document_id}. API replies: {replies_count}. Link: {link}" else: return f"Error: {message}"
- Method providing detailed schema documentation for all supported operation types, their required/optional parameters, descriptions, and examples - serves as runtime schema reference.def get_supported_operations(self) -> dict[str, Any]: """ Get information about supported batch operations. Returns: Dictionary with supported operation types and their required parameters """ return { 'supported_operations': { 'insert_text': { 'required': ['index', 'text'], 'description': 'Insert text at specified index' }, 'delete_text': { 'required': ['start_index', 'end_index'], 'description': 'Delete text in specified range' }, 'replace_text': { 'required': ['start_index', 'end_index', 'text'], 'description': 'Replace text in range with new text' }, 'format_text': { 'required': ['start_index', 'end_index'], 'optional': ['bold', 'italic', 'underline', 'font_size', 'font_family'], 'description': 'Apply formatting to text range' }, 'insert_table': { 'required': ['index', 'rows', 'columns'], 'description': 'Insert table at specified index' }, 'insert_page_break': { 'required': ['index'], 'description': 'Insert page break at specified index' }, 'find_replace': { 'required': ['find_text', 'replace_text'], 'optional': ['match_case'], 'description': 'Find and replace text throughout document' } }, 'example_operations': [ {"type": "insert_text", "index": 1, "text": "Hello World"}, {"type": "format_text", "start_index": 1, "end_index": 12, "bold": True}, {"type": "insert_table", "index": 20, "rows": 2, "columns": 3} ] }