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
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# πŸ’¬ Example Action

> **Interactive message input action for OpenWebUI with real-time status updates**

[![Version](https://img.shields.io/badge/version-0.1.0-blue.svg)](https://github.com/open-webui/functions)
[![OpenWebUI](https://img.shields.io/badge/OpenWebUI-0.3.9+-green.svg)](https://github.com/open-webui/open-webui)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
[![Python](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org)

---

## 🌟 Overview

**Example Action** is a foundational OpenWebUI action that demonstrates interactive user input capabilities with real-time status updates. This action provides a clean interface for collecting user messages and displaying them with proper event handling and status feedback.

### ✨ Key Features

- πŸ“ **Interactive Input** - Clean modal dialog for message collection
- ⚑ **Real-time Status** - Live status updates during processing
- πŸ”„ **Async Processing** - Non-blocking operation with proper event handling
- πŸ’« **Event Emitter Integration** - Native OpenWebUI event system support
- 🎯 **Simple & Extensible** - Perfect foundation for custom actions
- πŸ›‘οΈ **Error Handling** - Robust async operation management

---

## πŸ“‹ Table of Contents

- [πŸš€ Quick Start](#-quick-start)
- [πŸ—οΈ Installation](#️-installation)
- [🎯 Core Concepts](#-core-concepts)
  - [Action Architecture](#action-architecture)
  - [Event System](#event-system)
  - [Async Processing](#async-processing)
- [πŸ› οΈ Configuration](#️-configuration)
  - [Basic Settings](#basic-settings)
  - [Advanced Options](#advanced-options)
- [πŸ’‘ Usage Guide](#-usage-guide)
  - [Basic Usage](#basic-usage)
  - [Status Messages](#status-messages)
  - [Event Handling](#event-handling)
- [πŸ—οΈ System Architecture](#️-system-architecture)
  - [Code Structure](#code-structure)
  - [Event Flow](#event-flow)
  - [Response Handling](#response-handling)
- [πŸ”§ Troubleshooting](#-troubleshooting)
- [πŸš€ Advanced Features](#-advanced-features)
- [🀝 Contributing](#-contributing)

---

## πŸš€ Quick Start

### 1️⃣ Install the Action
1. Copy the complete action code
2. Add as a new action in OpenWebUI
3. Enable the action in your workspace

### 2️⃣ Trigger the Action
- Click the action button in the chat interface
- Or use the action through the OpenWebUI actions menu

### 3️⃣ Enter Your Message
- Fill in the input dialog that appears
- Click submit to process your message

### 4️⃣ View Real-time Updates
- Watch status updates as the action processes
- See your message displayed in the chat

---

## πŸ—οΈ Installation

### Prerequisites
- OpenWebUI version 0.3.9 or higher
- Python 3.8+ environment
- Administrator access to add actions

### Step-by-Step Installation

1. **Access Action Management**
   - Navigate to OpenWebUI Settings
   - Go to Admin Panel β†’ Actions
   - Click "Add Action"

2. **Install Example Action**
   - Copy the complete action code
   - Paste into the action editor
   - Set action name: "Example Action"
   - Save and enable the action

3. **Verify Installation**
   - Check that the action appears in your actions list
   - Test by triggering the action in a chat
   - Confirm input dialog appears correctly

---

## 🎯 Core Concepts

### Action Architecture

The **Example Action** follows OpenWebUI's standard action pattern:

#### πŸ—οΈ Component Structure
```python
class Action:
    class Valves(BaseModel):
        # Configuration settings (currently empty)
        pass
    
    def __init__(self):
        # Initialize action with valve settings
        self.valves = self.Valves()
    
    async def action(self, body, __user__, __event_emitter__, __event_call__):
        # Main action logic with async processing
```

#### πŸ”§ Core Components
- **Valves**: Configuration management system
- **Event Emitter**: Real-time status and message broadcasting
- **Event Call**: Interactive input collection
- **Async Processing**: Non-blocking operation handling

### Event System

The action integrates deeply with OpenWebUI's event system:

#### πŸ“‘ Event Types
| Event Type | Purpose | Data Structure |
|------------|---------|----------------|
| `input` | Collect user input | `{title, message, placeholder}` |
| `status` | Show processing state | `{description, done}` |
| `message` | Display content | `{content}` |

#### πŸ”„ Event Flow
1. **Input Request** β†’ User sees modal dialog
2. **Status Update** β†’ "adding message" with progress indicator  
3. **Processing Delay** β†’ Simulated work with `asyncio.sleep(1)`
4. **Message Emission** β†’ User input displayed in chat
5. **Completion Status** β†’ "added message" with done flag

### Async Processing

#### ⚑ Async Benefits
- **Non-blocking UI** - Interface remains responsive
- **Parallel Operations** - Multiple actions can run simultaneously
- **Real-time Updates** - Status changes broadcast immediately
- **Error Isolation** - Failed actions don't crash the system

---

## πŸ› οΈ Configuration

### Basic Settings

#### πŸŽ›οΈ Valves Configuration
```python
class Valves(BaseModel):
    # Currently no configuration options
    # Can be extended for customization
    pass
```

The Example Action currently uses minimal configuration, making it perfect for:
- **Learning & Development** - Simple structure for understanding actions
- **Prototyping** - Quick foundation for custom actions
- **Testing** - Reliable base for experimenting with features

### Advanced Options

#### πŸ”§ Potential Extensions
```python
class Valves(BaseModel):
    input_title: str = Field(default="write a message", description="Title for input dialog")
    input_message: str = Field(default="here write a message to append", description="Input dialog message")
    input_placeholder: str = Field(default="enter your message", description="Input placeholder text")
    processing_delay: float = Field(default=1.0, description="Simulated processing delay in seconds")
    status_adding: str = Field(default="adding message", description="Status message while processing")
    status_completed: str = Field(default="added message", description="Status message when done")
```

---

## πŸ’‘ Usage Guide

### Basic Usage

#### 🎯 Triggering the Action
1. **From Chat Interface**
   - Click the actions button in the chat
   - Select "Example Action" from the menu
   - Action will immediately prompt for input

2. **Action Flow**
   ```
   User Clicks Action β†’ Input Dialog β†’ User Types β†’ Processing β†’ Message Display
   ```

#### πŸ“ Input Dialog
The action presents a user-friendly input interface:
- **Title**: "write a message"
- **Message**: "here write a message to append"  
- **Placeholder**: "enter your message"
- **Input Field**: Text area for user message

### Status Messages

#### πŸ”„ Processing Feedback
The action provides real-time status updates:

1. **Initial Status**: "adding message" (done: false)
   - Shows processing spinner
   - Indicates work in progress

2. **Final Status**: "added message" (done: true)
   - Confirms completion
   - Removes loading indicator

### Event Handling

#### πŸ“‘ Event Sequence
```python
# 1. Collect input
response = await __event_call__({
    "type": "input",
    "data": {
        "title": "write a message",
        "message": "here write a message to append", 
        "placeholder": "enter your message"
    }
})

# 2. Show processing status
await __event_emitter__({
    "type": "status",
    "data": {"description": "adding message", "done": False}
})

# 3. Simulate processing
await asyncio.sleep(1)

# 4. Emit user message
await __event_emitter__({
    "type": "message", 
    "data": {"content": response}
})

# 5. Show completion status
await __event_emitter__({
    "type": "status",
    "data": {"description": "added message", "done": True}
})
```

---

## πŸ—οΈ System Architecture

### Code Structure

```
Example Action/
β”œβ”€β”€ Action Class
β”‚   β”œβ”€β”€ Valves (Configuration)
β”‚   β”œβ”€β”€ __init__ (Initialization)
β”‚   └── action() (Main Logic)
β”œβ”€β”€ Dependencies
β”‚   β”œβ”€β”€ pydantic (Data Validation)
β”‚   β”œβ”€β”€ typing (Type Hints)
β”‚   β”œβ”€β”€ os (System Access)
β”‚   β”œβ”€β”€ requests (HTTP Requests)
β”‚   └── asyncio (Async Operations)
└── Event Integration
    β”œβ”€β”€ __event_emitter__ (Status/Messages)
    β”œβ”€β”€ __event_call__ (User Input)
    └── __user__ (User Context)
```

### Event Flow

#### πŸ”„ Processing Pipeline
```mermaid
graph TD
    A[User Triggers Action] --> B[Input Dialog Displayed]
    B --> C[User Enters Message]
    C --> D[Status: Adding Message]
    D --> E[Processing Delay]
    E --> F[Emit User Message]
    F --> G[Status: Added Message]
    G --> H[Action Complete]
```

### Response Handling

#### πŸ“¨ Response Types
- **Input Response** - User's message text
- **Status Response** - Processing state updates
- **Message Response** - Content displayed in chat
- **Error Response** - Exception handling (implicit)

---

## πŸ”§ Troubleshooting

### Common Issues

#### ❌ Action Not Appearing
**Problem**: Example Action doesn't show in actions menu
```
Solution: Verify installation and permissions
1. Check action is properly saved in OpenWebUI
2. Ensure action is enabled
3. Refresh browser/restart OpenWebUI
4. Verify minimum version requirement (0.3.9+)
```

#### ❌ Input Dialog Not Opening
**Problem**: Clicking action doesn't show input dialog
```
Solution: Check event call configuration
1. Verify __event_call__ is available
2. Check browser console for JavaScript errors
3. Test with a fresh browser session
4. Ensure OpenWebUI is up to date
```

#### ❌ Status Updates Not Showing
**Problem**: No status messages during processing
```
Solution: Verify event emitter functionality
1. Check __event_emitter__ is available
2. Ensure status data structure is correct
3. Verify async/await syntax is proper
4. Test with simpler status messages
```

### Debug Mode

#### πŸ› Adding Debug Output
```python
async def action(self, body: dict, __user__=None, __event_emitter__=None, __event_call__=None):
    print(f"action:{__name__}")  # Current debug output
    print(f"User: {__user__}")   # Add user debug info
    print(f"Body: {body}")       # Add body debug info
    
    # Your existing code...
```

#### πŸ“Š Debug Information
- **Action Name** - Confirms action is executing
- **User Context** - Validates user permissions
- **Request Body** - Shows incoming data structure
- **Event Responses** - Logs event call results

---

## πŸš€ Advanced Features

### Custom Extensions

#### 🎨 Enhanced Input Validation
```python
from pydantic import BaseModel, Field, validator

class Valves(BaseModel):
    min_message_length: int = Field(default=1, description="Minimum message length")
    max_message_length: int = Field(default=1000, description="Maximum message length")
    
    @validator('min_message_length')
    def validate_min_length(cls, v):
        if v < 1:
            raise ValueError('Minimum length must be at least 1')
        return v
```

#### πŸ”§ Message Processing
```python
async def action(self, body: dict, __user__=None, __event_emitter__=None, __event_call__=None):
    # Enhanced input validation
    if len(response) < self.valves.min_message_length:
        await __event_emitter__({
            "type": "status",
            "data": {"description": "Message too short", "done": True}
        })
        return
    
    # Message transformation
    processed_message = f"πŸ“ {__user__.get('name', 'User')}: {response}"
    
    # Enhanced status updates
    await __event_emitter__({
        "type": "message",
        "data": {"content": processed_message}
    })
```

### Integration Patterns

#### πŸ”— API Integration
```python
import requests

async def action(self, body: dict, **kwargs):
    # External API call example
    api_response = requests.get("https://api.example.com/process", 
                               json={"message": response})
    
    # Process API response
    if api_response.status_code == 200:
        result = api_response.json()
        await __event_emitter__({
            "type": "message",
            "data": {"content": f"API Result: {result}"}
        })
```

#### πŸ—„οΈ Data Storage
```python
import os
import json

async def action(self, body: dict, **kwargs):
    # Save message to file
    data_dir = "/app/backend/data/messages"
    os.makedirs(data_dir, exist_ok=True)
    
    message_data = {
        "timestamp": datetime.now().isoformat(),
        "user": __user__.get('name', 'Unknown'),
        "message": response
    }
    
    with open(f"{data_dir}/messages.jsonl", "a") as f:
        f.write(json.dumps(message_data) + "\n")
```

---

## 🀝 Contributing

### Development Setup

#### πŸ› οΈ Local Development
1. **Clone Repository** - Set up local OpenWebUI development environment
2. **Install Dependencies** - Ensure pydantic, asyncio are available
3. **Test Changes** - Use OpenWebUI development instance
4. **Submit PR** - Follow OpenWebUI contribution guidelines

### Action Guidelines

#### πŸ“ Best Practices
- **Clear Purpose** - Well-defined action functionality
- **Proper Async** - Use async/await correctly
- **Error Handling** - Graceful failure management
- **User Feedback** - Informative status messages
- **Code Documentation** - Clear comments and docstrings

#### πŸ§ͺ Testing Requirements
- **Functionality** - Action works as expected
- **Performance** - No blocking operations
- **Compatibility** - Works with target OpenWebUI version
- **Error Handling** - Graceful failure modes

### Bug Reports

#### πŸ› Reporting Issues
Include the following information:
- **OpenWebUI Version** - Your OpenWebUI version
- **Action Code** - Complete action implementation
- **Error Messages** - Full error text and console logs
- **Reproduction Steps** - How to recreate the issue
- **Expected Behavior** - What should happen instead

---

## πŸ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

## πŸ™ Acknowledgments

- **OpenWebUI Team** - For the amazing platform and action system
- **Community Contributors** - For feedback and improvements
- **Beta Testers** - For early testing and bug reports

---

## πŸ“ž Support

- **GitHub Issues** - [Report bugs and request features](https://github.com/open-webui/functions/issues)
- **Discussions** - [Community support and questions](https://github.com/open-webui/functions/discussions)
- **Documentation** - [OpenWebUI Actions Documentation](https://docs.openwebui.com)

---

<div align="center">

**πŸ’¬ Enhance your OpenWebUI experience with interactive actions!**

*Simple setup β€’ Real-time feedback β€’ Extensible foundation*

</div>