ox-ai-workers 0.8.7 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.cursorrules +88 -2
- data/CHANGELOG.md +21 -11
- data/README.md +135 -38
- data/config/locales/en.oxaiworkers.assistant.yml +39 -5
- data/config/locales/en.oxaiworkers.iterator.yml +1 -9
- data/config/locales/en.oxaiworkers.tool.yml +16 -1
- data/config/locales/ru.oxaiworkers.assistant.yml +39 -5
- data/config/locales/ru.oxaiworkers.iterator.yml +2 -11
- data/config/locales/ru.oxaiworkers.tool.yml +16 -1
- data/lib/ox-ai-workers.rb +16 -6
- data/lib/oxaiworkers/assistant/coder.rb +16 -8
- data/lib/oxaiworkers/assistant/localizer.rb +16 -9
- data/lib/oxaiworkers/assistant/module_base.rb +14 -5
- data/lib/oxaiworkers/assistant/orchestrator.rb +44 -0
- data/lib/oxaiworkers/assistant/painter.rb +37 -0
- data/lib/oxaiworkers/assistant/sysop.rb +15 -7
- data/lib/oxaiworkers/delayed_request.rb +2 -2
- data/lib/oxaiworkers/image_iterator.rb +41 -0
- data/lib/oxaiworkers/iterator.rb +34 -54
- data/lib/oxaiworkers/models/deepseek_max.rb +16 -0
- data/lib/oxaiworkers/models/module_base.rb +17 -0
- data/lib/oxaiworkers/models/openai_max.rb +15 -0
- data/lib/oxaiworkers/models/openai_mini.rb +12 -0
- data/lib/oxaiworkers/models/openai_nano.rb +12 -0
- data/lib/oxaiworkers/module_request.rb +11 -15
- data/lib/oxaiworkers/tool/eval.rb +19 -8
- data/lib/oxaiworkers/tool/file_system.rb +30 -15
- data/lib/oxaiworkers/tool/pipeline.rb +106 -0
- data/lib/oxaiworkers/tool/pixels.rb +76 -0
- data/lib/oxaiworkers/version.rb +1 -1
- data/template/start +4 -6
- metadata +11 -1
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA256:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 716fe34f8c0ee4841a0788a04febee87e885af815d30cf533e46d55c4fa76e54
|
4
|
+
data.tar.gz: ee4e89522ba6b8ae4484298e810b321af3f7a4d15bbd70dd0b2118dfd070b26c
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: e17ecef126df8779d99e3b4de595cd590c3abf6e24e74a85dcbaefaf6daade38541348fe12477b029ea94de2c2cb29b312be8ee7543a154b575bcd32a876b4f2
|
7
|
+
data.tar.gz: 0fbd6beee90840ba1c3490edcc7f2e670881d3b81765c42b1829109f456a77e0120f153f444e0ac85e3201a9e451015b9601d021f845ec608365234c71852d22
|
data/.cursorrules
CHANGED
@@ -1,6 +1,9 @@
|
|
1
|
+
# Overview
|
2
|
+
|
1
3
|
OxAiWorkers is a Ruby gem that implements a finite state machine (using the `state_machine` gem) to solve tasks using generative intelligence (with the `ruby-openai` gem). This approach enhances the final result by utilizing internal monologue and external tools.
|
2
4
|
|
3
5
|
## Architecture Principles
|
6
|
+
|
4
7
|
- The library is built on the finite state machine (FSM) pattern using the 'state_machine' gem
|
5
8
|
- Integration with generative models is implemented using the 'ruby-openai' gem
|
6
9
|
- DRY (Don't Repeat Yourself) principle is applied throughout all components
|
@@ -9,6 +12,7 @@ OxAiWorkers is a Ruby gem that implements a finite state machine (using the `sta
|
|
9
12
|
- Implementation of the "Composition" pattern for flexible tool integration
|
10
13
|
|
11
14
|
## Core Components
|
15
|
+
|
12
16
|
- `Request` and `DelayedRequest` - classes for executing API requests (immediate and delayed)
|
13
17
|
- `Iterator` - main class for iterative task execution with tools
|
14
18
|
- `Assistant` - high-level wrappers over Iterator (Sysop, Coder, Localizer, etc.)
|
@@ -18,6 +22,7 @@ OxAiWorkers is a Ruby gem that implements a finite state machine (using the `sta
|
|
18
22
|
- `ContextualLogger` - logging system with contextual information support
|
19
23
|
|
20
24
|
## Code Conventions
|
25
|
+
|
21
26
|
- Use `snake_case` for method and variable names
|
22
27
|
- Functions for generative models should also be in `snake_case` (inner_monologue, outer_voice, etc.)
|
23
28
|
- All public methods must have documentation with usage examples
|
@@ -28,15 +33,15 @@ OxAiWorkers is a Ruby gem that implements a finite state machine (using the `sta
|
|
28
33
|
- Follow the "Fail fast" principle for early error detection
|
29
34
|
|
30
35
|
## Interaction Patterns
|
36
|
+
|
31
37
|
- The system uses internal monologue (inner_monologue) for planning actions
|
32
38
|
- External voice (outer_voice) is used for communication with the user
|
33
|
-
- Actions (action_request) are executed through tools
|
34
|
-
- Summary (summarize) is used to compress dialog history
|
35
39
|
- Execution flow management through finite state machine
|
36
40
|
- Implementation of callback mechanisms for flexible event handling
|
37
41
|
- Isolation of error handling functions at the tool level
|
38
42
|
|
39
43
|
## Integration
|
44
|
+
|
40
45
|
- CLI interface through `oxaiworkers init` and `oxaiworkers run` commands
|
41
46
|
- Rails support via ActiveRecord for storing delayed requests
|
42
47
|
- Configuration through the `OxAiWorkers.configure` block
|
@@ -46,6 +51,7 @@ OxAiWorkers is a Ruby gem that implements a finite state machine (using the `sta
|
|
46
51
|
- Support for various language models (OpenAI, Anthropic, Gemini)
|
47
52
|
|
48
53
|
## Best Practices
|
54
|
+
|
49
55
|
- Use callbacks to handle various states (on_inner_monologue, on_outer_voice)
|
50
56
|
- Handle errors at the tool level, preventing them from interrupting the main execution flow
|
51
57
|
- When creating new assistants, inherit from the base Assistant class
|
@@ -55,6 +61,7 @@ OxAiWorkers is a Ruby gem that implements a finite state machine (using the `sta
|
|
55
61
|
- Use localization mechanisms for multilingual support
|
56
62
|
|
57
63
|
## Tools Architecture
|
64
|
+
|
58
65
|
- Each tool should be a self-contained module
|
59
66
|
- Tools are registered through the `define_function` interface
|
60
67
|
- All tools should handle their own errors and return readable messages
|
@@ -62,8 +69,87 @@ OxAiWorkers is a Ruby gem that implements a finite state machine (using the `sta
|
|
62
69
|
- Maintain a unified format for return values
|
63
70
|
|
64
71
|
## Performance and Scaling
|
72
|
+
|
65
73
|
- Cache API request results when possible
|
66
74
|
- Use asynchronous processing for long operations
|
67
75
|
- Apply backoff strategies for repeated requests
|
68
76
|
- Break large tasks into atomic operations
|
69
77
|
- Provide monitoring and profiling mechanisms
|
78
|
+
|
79
|
+
## Finite State Machine Implementation
|
80
|
+
|
81
|
+
- Core FSM based on `state_machine` gem with states: idle → prepared → requested → analyzed → finished → idle
|
82
|
+
- State transitions managed by events: prepare, request, analyze, complete, iterate, end
|
83
|
+
- `StateTools` - base class for FSM implementation with event hooks and transition callbacks
|
84
|
+
- `StateBatch` - FSM extension for batch request processing with additional states
|
85
|
+
- Automatic error recovery and retry mechanisms for failed API requests
|
86
|
+
|
87
|
+
## Request Processing
|
88
|
+
|
89
|
+
- `ModuleRequest` - base class for all API requests with parsing and response handling
|
90
|
+
- Support for streaming responses with callback processing
|
91
|
+
- Built-in token usage tracking and truncation detection
|
92
|
+
- Error handling with automatic retries for server errors
|
93
|
+
|
94
|
+
## Iterator Lifecycle
|
95
|
+
|
96
|
+
- 3 core functions: inner_monologue, outer_voice, finish_it
|
97
|
+
- Configurable message queue for stateful conversation history
|
98
|
+
- Callback system for processing each state transition
|
99
|
+
- Context and milestone management for optimizing token usage
|
100
|
+
- Support for custom steps and instruction templating
|
101
|
+
|
102
|
+
## Additional Tools
|
103
|
+
|
104
|
+
- `Converter` - tools for data format conversion and transformation
|
105
|
+
- Support for custom tool development through inheritance and composition
|
106
|
+
- Automatic function name resolution and parameter validation
|
107
|
+
|
108
|
+
## Assistants Details
|
109
|
+
|
110
|
+
- `ModuleBase` - shared functionality for all assistant types
|
111
|
+
- `Sysop` - system administration and shell command execution
|
112
|
+
- `Coder` - specialized for code generation and analysis
|
113
|
+
- `Localizer` - translation and localization support
|
114
|
+
|
115
|
+
## Development Guidelines
|
116
|
+
|
117
|
+
- Use dependency injection for testability
|
118
|
+
- Follow the FSM pattern for all stateful operations
|
119
|
+
- Implement proper error boundaries at the tool level
|
120
|
+
- Use monologue for complex reasoning and planning
|
121
|
+
- Apply callbacks for event-driven architecture
|
122
|
+
- Utilize templates in the CLI for rapid prototyping
|
123
|
+
- Extend the base classes rather than modifying them
|
124
|
+
|
125
|
+
## Internationalization and Localization
|
126
|
+
|
127
|
+
- All code comments, variable names, and documentation MUST be written in English
|
128
|
+
- All user-facing strings MUST be properly localized using I18n
|
129
|
+
- Use I18n.t for all text that will be shown to users or appears in assistant prompts
|
130
|
+
- Store translations in YAML files within the config/locales directory
|
131
|
+
- Follow the naming convention of language.namespace.key (e.g., en.oxaiworkers.assistant.role)
|
132
|
+
- Use named parameters (%{variable}) instead of positional parameters (%s) in translation strings
|
133
|
+
- Use the with_locale method to ensure proper locale context when processing localized text
|
134
|
+
- Implement locale-aware classes by including the OxAiWorkers::LoadI18n module
|
135
|
+
- Store the current locale on initialization and preserve it across method calls
|
136
|
+
- Support multiple languages simultaneously through careful locale management
|
137
|
+
- Default to English for developer-facing messages and logs
|
138
|
+
- Ensure that all assistant classes properly handle localization in their format_role methods
|
139
|
+
|
140
|
+
## LoadI18n Module Usage
|
141
|
+
|
142
|
+
- The `OxAiWorkers::LoadI18n` module provides two key methods for localization:
|
143
|
+
- `store_locale` - saves the current locale at initialization time
|
144
|
+
- `with_locale` - executes a block of code in the context of the saved locale
|
145
|
+
- Always include the `OxAiWorkers::LoadI18n` module in classes that need localization capabilities
|
146
|
+
- Call `store_locale` in the initialization methods of locale-aware classes
|
147
|
+
- Wrap all locale-dependent code in `with_locale` blocks
|
148
|
+
- NEVER redefine the `with_locale` method in classes that include LoadI18n
|
149
|
+
- All methods that produce user-visible text must use the locale context via `with_locale` blocks
|
150
|
+
- Regular method calls from classes including LoadI18n do not require additional locale handling
|
151
|
+
|
152
|
+
## Multi-Language Support
|
153
|
+
|
154
|
+
- Use the store_locale and with_locale methods for consistent localization context
|
155
|
+
- All error messages should be localized and retrieved via I18n.t
|
data/CHANGELOG.md
CHANGED
@@ -1,22 +1,32 @@
|
|
1
|
+
## [0.9.2] - 2025-05-06
|
1
2
|
|
2
|
-
|
3
|
+
- Changed `max_tokens` to `max_completion_tokens` in `params`
|
3
4
|
|
4
|
-
|
5
|
+
## [0.9.1] - 2025-05-04
|
5
6
|
|
6
|
-
|
7
|
+
- Added `current_dir` for `Eval`, `FileSystem`, `Pixels` tools
|
8
|
+
- Added `current_dir` for `Coder`, `Localizer`, `Painter`, `Sysop` assistants
|
9
|
+
- Added `run_task` for Assistants
|
7
10
|
|
8
|
-
|
11
|
+
## [0.9.0] - 2025-05-03
|
9
12
|
|
10
|
-
|
11
|
-
|
12
|
-
-
|
13
|
+
- Added `context` for tools in `Iterator`
|
14
|
+
- Added `Pipeline` tool
|
15
|
+
- Added `Pixels` tool
|
16
|
+
- Added `Painter` assistant
|
17
|
+
- Added `Orchestrator` assistant
|
18
|
+
- Added collaboration between assistants
|
19
|
+
- Added classes for AI models: `OpenaiMini`, `OpenaiNano`, `OpenaiMax`, `DeepseekMax`
|
20
|
+
- Added `default_model` for configuration
|
21
|
+
- Removed `action_request` and `summarize` from `Iterator`
|
22
|
+
- Removed `auto_execute` from `Iterator`
|
23
|
+
- Renamed `add_response` to `add_task` in `Assistant`
|
13
24
|
|
14
|
-
## [0.8.
|
25
|
+
## [0.8.7] - 2025-04-25
|
15
26
|
|
27
|
+
- Fixed tool calls parsing
|
28
|
+
- Refine Russian locale for Iterator with enhanced step descriptions and planning guidance
|
16
29
|
- Update locale for Iterator
|
17
|
-
|
18
|
-
## [0.8.0] - 2025-03-31
|
19
|
-
|
20
30
|
- Added `on_stream` for `Iterator`
|
21
31
|
|
22
32
|
## [0.7.10] - 2025-03-31
|
data/README.md
CHANGED
@@ -44,7 +44,7 @@ sysop = OxAiWorkers::Assistant::Sysop.new(delayed: false, model: "gpt-4o")
|
|
44
44
|
sysop.task = "Add a cron job to synchronize files daily."
|
45
45
|
|
46
46
|
# Provide a response to the assistant's question
|
47
|
-
sysop.
|
47
|
+
sysop.add_task("blah-blah-blah")
|
48
48
|
```
|
49
49
|
|
50
50
|
Alternatively, you can use a lower-level approach for more control:
|
@@ -72,10 +72,12 @@ iterator = OxAiWorkers::Iterator.new(
|
|
72
72
|
iterator.role = "You are a software agent inside my computer"
|
73
73
|
|
74
74
|
# Add a task to the iterator
|
75
|
-
iterator.
|
75
|
+
iterator.task = "Show files in current dir"
|
76
|
+
iterator.execute
|
76
77
|
|
77
78
|
# Provide a response to the gpt's question
|
78
|
-
iterator.
|
79
|
+
iterator.task = "linux"
|
80
|
+
iterator.execute
|
79
81
|
```
|
80
82
|
|
81
83
|
### With Config
|
@@ -84,13 +86,15 @@ For a more robust setup, you can configure the gem with your API keys, for examp
|
|
84
86
|
|
85
87
|
```ruby
|
86
88
|
OxAiWorkers.configure do |config|
|
87
|
-
config.
|
88
|
-
config.
|
89
|
+
config.access_token_openai = ENV.fetch("OPENAI")
|
90
|
+
config.access_token_deepseek = ENV.fetch("DEEPSEEK")
|
89
91
|
config.max_tokens = 4096 # Default
|
90
92
|
config.temperature = 0.7 # Default
|
91
|
-
config.auto_execute = true # Default
|
92
93
|
config.wait_for_complete = true # Default
|
93
94
|
end
|
95
|
+
|
96
|
+
# Set the default model
|
97
|
+
OxAiWorkers.default_model = OxAiWorkers::Models::OpenaiMini.new
|
94
98
|
```
|
95
99
|
|
96
100
|
Then you can create an assistant like this:
|
@@ -98,11 +102,11 @@ Then you can create an assistant like this:
|
|
98
102
|
```ruby
|
99
103
|
assistant = OxAiWorkers::Assistant::Sysop.new()
|
100
104
|
assistant.task = "Remove all cron jobs."
|
101
|
-
|
105
|
+
assistant.execute
|
102
106
|
|
103
107
|
# Provide a response to the assistant's question
|
104
|
-
assistant.
|
105
|
-
|
108
|
+
assistant.add_task("blah-blah-blah")
|
109
|
+
assistant.execute
|
106
110
|
```
|
107
111
|
|
108
112
|
Besides, you can create assistants with different locales
|
@@ -111,7 +115,7 @@ Besides, you can create assistants with different locales
|
|
111
115
|
I18n.with_locale(:en) { @sysop_en = OxAiWorkers::Assistant::Sysop.new() }
|
112
116
|
|
113
117
|
# Assign tasks and responses in different languages
|
114
|
-
@sysop_en.
|
118
|
+
@sysop_en.run_task "Remove all cron jobs."
|
115
119
|
```
|
116
120
|
|
117
121
|
Or you can create a lower-level iterator for more control:
|
@@ -126,20 +130,14 @@ iterator = OxAiWorkers::Iterator.new(
|
|
126
130
|
role: "You are a software agent inside my computer",
|
127
131
|
on_inner_monologue: ->(text:) { puts "monologue: #{text}".colorize(:yellow) },
|
128
132
|
on_outer_voice: ->(text:) { puts "voice: #{text}".colorize(:green) },
|
129
|
-
on_action_request: ->(text:) { puts "action: #{text}".colorize(:red) },
|
130
|
-
on_summarize: ->(text:) { puts "summary: #{text}".colorize(:blue) },
|
131
133
|
on_finish: -> { puts "finish".colorize(:magenta) }
|
132
134
|
)
|
133
135
|
|
134
|
-
iterator.
|
136
|
+
iterator.task = "Show files in current directory."
|
137
|
+
iterator.execute
|
135
138
|
# ...
|
136
|
-
iterator.add_task
|
137
|
-
|
138
|
-
|
139
|
-
If `auto_execute` is set to false in the configuration, don't forget to manually execute the iterator or assistant.
|
140
|
-
|
141
|
-
```ruby
|
142
|
-
iterator.execute # if auto_execute is false
|
139
|
+
iterator.add_task "linux"
|
140
|
+
iterator.execute
|
143
141
|
```
|
144
142
|
|
145
143
|
This way, you have the flexibility to choose between a higher-level assistant for simplicity or a lower-level iterator for finer control over the tasks and tools used.
|
@@ -151,8 +149,7 @@ steps = []
|
|
151
149
|
steps << 'Step 1. Develop your own solution to the problem, taking initiative and making assumptions.'
|
152
150
|
steps << "Step 2. Enclose all your developments from the previous step in the #{OxAiWorkers::Iterator.full_function_name(:inner_monologue)} function."
|
153
151
|
steps << 'Step 3. Call the necessary functions one after another until the desired result is achieved.'
|
154
|
-
steps << "Step 4. When
|
155
|
-
steps << "Step 5. When the solution is ready, notify about it and wait for the user's response."
|
152
|
+
steps << "Step 4. When the solution is ready, notify about it and wait for the user's response."
|
156
153
|
|
157
154
|
# To retain the locale if you have assistants in different languages in your project.
|
158
155
|
store_locale # Optional
|
@@ -163,12 +160,10 @@ store_locale # Optional
|
|
163
160
|
tools: [MyTool.new],
|
164
161
|
locale: @locale || I18n.locale,
|
165
162
|
steps: steps,
|
166
|
-
# def_except: [:
|
163
|
+
# def_except: [:outer_voice], # It's except steps with that functions
|
167
164
|
# def_only: [:inner_monologue, :outer_voice], # Use it only with your steps
|
168
165
|
on_inner_monologue: ->(text:) { puts "monologue: #{text}".colorize(:yellow) },
|
169
|
-
on_outer_voice: ->(text:) { puts "voice: #{text}".colorize(:green) }
|
170
|
-
on_action_request: ->(text:) { puts "action: #{text}".colorize(:red) },
|
171
|
-
on_summarize: ->(text:) { puts "summary: #{text}".colorize(:blue) }
|
166
|
+
on_outer_voice: ->(text:) { puts "voice: #{text}".colorize(:green) }
|
172
167
|
)
|
173
168
|
```
|
174
169
|
|
@@ -185,17 +180,16 @@ As a worker, you can use different classes depending on your needs:
|
|
185
180
|
OxAiWorkers supports alternative compatible models like DeepSeek. To use these models, specify the appropriate base URI in the initializer:
|
186
181
|
|
187
182
|
```ruby
|
188
|
-
|
189
|
-
|
190
|
-
uri_base: "https://api.deepseek.com/"
|
183
|
+
# Use the closest available model and override its parameters
|
184
|
+
model = OxAiWorkers::Models::OpenaiMini.new(
|
185
|
+
uri_base: "https://api.deepseek.com/",
|
186
|
+
api_key: ENV.fetch("DEEPSEEK"),
|
187
|
+
model: "deepseek-chat"
|
191
188
|
)
|
192
189
|
|
193
|
-
|
194
|
-
|
195
|
-
|
196
|
-
config.model = "deepseek-chat"
|
197
|
-
# Other configuration options...
|
198
|
-
end
|
190
|
+
worker = OxAiWorkers::Request.new(
|
191
|
+
model: model,
|
192
|
+
)
|
199
193
|
```
|
200
194
|
|
201
195
|
This allows you to use any API-compatible LLM provider by simply changing the base URI.
|
@@ -318,7 +312,7 @@ OxAiWorkers.logger.level = :debug
|
|
318
312
|
5. In the command prompt, type:
|
319
313
|
|
320
314
|
```sh
|
321
|
-
@assistant.
|
315
|
+
@assistant.run_task("Write a snake game")
|
322
316
|
```
|
323
317
|
|
324
318
|
### Running System Operator in Any Directory
|
@@ -347,13 +341,13 @@ Alternatively, you can use IRB (Interactive Ruby):
|
|
347
341
|
Then set a task:
|
348
342
|
|
349
343
|
```ruby
|
350
|
-
@sysop.
|
344
|
+
@sysop.run_task "Show all cron jobs"
|
351
345
|
```
|
352
346
|
|
353
347
|
After these steps you can interact with it using the following method:
|
354
348
|
|
355
349
|
```ruby
|
356
|
-
@sysop.
|
350
|
+
@sysop.run_task "Yes, I want it All"
|
357
351
|
```
|
358
352
|
|
359
353
|
or set a new task.
|
@@ -364,6 +358,109 @@ or set a new task.
|
|
364
358
|
- **Internal Monologue**: Uses inner monologue to plan responses and articulate main points.
|
365
359
|
- **External Tools**: Integrates with external tools and services to complete tasks.
|
366
360
|
- **Finite State Machine**: Implements a robust state machine to manage task states and transitions.
|
361
|
+
- **Multilingual Support**: Complete I18n integration with ready-to-use English and Russian locales.
|
362
|
+
- **Streaming Responses**: Support for streaming responses with callback processing for real-time interaction.
|
363
|
+
- **Error Recovery**: Automatic retries and error handling mechanisms for reliable operation.
|
364
|
+
- **Custom Tool Development**: Flexible framework for creating domain-specific tools and assistants.
|
365
|
+
|
366
|
+
## Advanced Usage Patterns
|
367
|
+
|
368
|
+
### Creating Custom Tools
|
369
|
+
|
370
|
+
You can create custom tools by extending the `ToolDefinition` module:
|
371
|
+
|
372
|
+
```ruby
|
373
|
+
class MyTool
|
374
|
+
include OxAiWorkers::ToolDefinition
|
375
|
+
|
376
|
+
def initialize
|
377
|
+
define_function :hello_world, description: "Says hello to someone" do
|
378
|
+
property :name, type: "string", description: "Name to greet", required: true
|
379
|
+
end
|
380
|
+
end
|
381
|
+
|
382
|
+
def hello_world(name:)
|
383
|
+
"Hello, #{name}!"
|
384
|
+
end
|
385
|
+
end
|
386
|
+
```
|
387
|
+
|
388
|
+
### Handling State Transitions with Callbacks
|
389
|
+
|
390
|
+
You can track and respond to state transitions with callbacks:
|
391
|
+
|
392
|
+
```ruby
|
393
|
+
iterator = OxAiWorkers::Iterator.new(
|
394
|
+
worker: worker,
|
395
|
+
tools: [my_tool],
|
396
|
+
on_inner_monologue: ->(text:) { save_to_database(text) },
|
397
|
+
on_outer_voice: ->(text:) { notify_user(text) },
|
398
|
+
on_finish: -> { mark_task_completed }
|
399
|
+
)
|
400
|
+
```
|
401
|
+
|
402
|
+
### Streaming API Responses
|
403
|
+
|
404
|
+
Enable streaming for real-time feedback:
|
405
|
+
|
406
|
+
```ruby
|
407
|
+
worker = OxAiWorkers::Request.new(
|
408
|
+
on_stream: ->(chunk) {
|
409
|
+
if chunk.dig('choices', 0, 'delta', 'content')
|
410
|
+
print chunk.dig('choices', 0, 'delta', 'content')
|
411
|
+
end
|
412
|
+
}
|
413
|
+
)
|
414
|
+
```
|
415
|
+
|
416
|
+
### Available Assistant Types
|
417
|
+
|
418
|
+
OxAiWorkers provides several specialized assistant types:
|
419
|
+
|
420
|
+
- **Sysop**: System administration and shell command execution
|
421
|
+
|
422
|
+
```ruby
|
423
|
+
sysop = OxAiWorkers::Assistant::Sysop.new
|
424
|
+
sysop.task = "Configure nginx for my Rails application"
|
425
|
+
```
|
426
|
+
|
427
|
+
- **Coder**: Code generation and analysis with language-specific configuration
|
428
|
+
|
429
|
+
```ruby
|
430
|
+
coder = OxAiWorkers::Assistant::Coder.new(language: 'ruby')
|
431
|
+
coder.task = "Create a Sinatra API with three endpoints"
|
432
|
+
```
|
433
|
+
|
434
|
+
- **Localizer**: Translation and localization support
|
435
|
+
|
436
|
+
```ruby
|
437
|
+
localizer = OxAiWorkers::Assistant::Localizer.new(source_lang: 'en', target_lang: 'ru')
|
438
|
+
localizer.task = "Translate my application's interface"
|
439
|
+
```
|
440
|
+
|
441
|
+
### Implementing Your Own Assistant
|
442
|
+
|
443
|
+
Create custom assistants by inheriting from existing ones or composing with the Iterator:
|
444
|
+
|
445
|
+
```ruby
|
446
|
+
module OxAiWorkers
|
447
|
+
module Assistant
|
448
|
+
class DataAnalyst
|
449
|
+
include OxAiWorkers::Assistant::ModuleBase
|
450
|
+
|
451
|
+
def initialize(delayed: false, model: nil)
|
452
|
+
store_locale
|
453
|
+
@iterator = Iterator.new(
|
454
|
+
worker: init_worker(delayed: delayed, model: model),
|
455
|
+
role: "You are a data analysis assistant specialized in processing CSV and JSON data",
|
456
|
+
tools: [Tool::FileSystem.new, Tool::Eval.new(only: [:ruby])],
|
457
|
+
locale: @locale
|
458
|
+
)
|
459
|
+
end
|
460
|
+
end
|
461
|
+
end
|
462
|
+
end
|
463
|
+
```
|
367
464
|
|
368
465
|
## Contributing
|
369
466
|
|
@@ -2,10 +2,44 @@ en:
|
|
2
2
|
oxaiworkers:
|
3
3
|
assistant:
|
4
4
|
sysop:
|
5
|
-
|
5
|
+
title: "System Operator"
|
6
|
+
description: "Executes system commands and file operations"
|
7
|
+
capabilities: "executing shell commands, reading and writing files, analyzing system information"
|
8
|
+
role: "You are an experienced system administrator who can execute shell commands and file system operations. Your task is to safely and efficiently manage the system."
|
6
9
|
coder:
|
7
|
-
|
10
|
+
title: "Programmer"
|
11
|
+
description: "Writes and analyzes code"
|
12
|
+
capabilities: "code generation, refactoring, code analysis, optimization"
|
13
|
+
role: "You are an experienced programmer who writes clean, efficient code and can explain complex technical concepts in simple terms."
|
14
|
+
role_with_language: "You are an experienced %{language} programmer who writes clean, efficient code and can explain complex technical concepts in simple terms."
|
8
15
|
localizer:
|
9
|
-
|
10
|
-
|
11
|
-
|
16
|
+
title: "Localizer"
|
17
|
+
description: "Performs translation and content adaptation"
|
18
|
+
capabilities: "text translation, content adaptation, format preservation"
|
19
|
+
role: "You are an experienced translator and content localizer from %{source_lang}. Your task is to translate content while preserving its meaning, style, and formatting."
|
20
|
+
role_with_target: "You are an experienced translator and content localizer from %{source_lang} to %{target_lang}. Your task is to translate content while preserving its meaning, style, and formatting."
|
21
|
+
source: "Source language: %{source_lang}"
|
22
|
+
locale: "Target language: %{target_lang}"
|
23
|
+
orchestrator:
|
24
|
+
title: "Orchestrator"
|
25
|
+
description: "Manages interaction between assistants"
|
26
|
+
capabilities: "workflow planning, task distribution, execution monitoring"
|
27
|
+
role: "You are an orchestrator, coordinating work between different assistants. Your task is to distribute tasks among assistants and organize their interaction to achieve a common goal."
|
28
|
+
workflow_task: |
|
29
|
+
You need to organize a workflow according to the following description:
|
30
|
+
|
31
|
+
%{workflow_description}
|
32
|
+
|
33
|
+
Develop an action plan by distributing tasks among available assistants, and coordinate their interaction to achieve the goal.
|
34
|
+
|
35
|
+
For each step, send a message to another assistant specifying:
|
36
|
+
1. The ID of the assistant who should perform the task
|
37
|
+
2. Task description for the assistant
|
38
|
+
3. Expected result
|
39
|
+
|
40
|
+
After completing each step, analyze the result and decide on further actions.
|
41
|
+
painter:
|
42
|
+
title: "Painter"
|
43
|
+
description: "Creates and modifies images based on descriptions"
|
44
|
+
capabilities: "image generation, image editing, style adaptation, visual concept creation"
|
45
|
+
role: "You are an experienced digital artist who creates and modifies images based on descriptions. Your task is to generate visually appealing and accurate representations of concepts and ideas. Improve the user's prompt, add details that will help get a more accurate result."
|
@@ -7,19 +7,11 @@ en:
|
|
7
7
|
outer_voice:
|
8
8
|
description: Inform the user of the information without expecting a response.
|
9
9
|
text: Content of the message
|
10
|
-
action_request:
|
11
|
-
description: A function for interactive interaction with the user. Allows you to ask a clarifying question, request actions, or complete the current step. The function waits for the user's response and returns it.
|
12
|
-
action: Text of the request or action
|
13
|
-
summarize:
|
14
|
-
description: The function saves key facts, nuances, and actions from previous messages, including the provided response. After calling this function, all previous messages will be deleted. Use it only after all intermediate steps are completed and when the exact content of previous messages is no longer relevant.
|
15
|
-
text: Enumeration of important facts and nuances
|
16
|
-
result: Messages deleted
|
17
10
|
finish_it:
|
18
11
|
description: Function to complete steps
|
19
12
|
monologue:
|
20
13
|
- Step %d. Develop your own solution to the problem, taking initiative and making assumptions.
|
21
14
|
- Step %d. Enclose all your developments from the previous step in the ox_ai_workers_iterator__inner_monologue function.
|
22
15
|
- Step %d. Call the necessary functions one after another until the desired result is achieved.
|
23
|
-
- Step %d. When all intermediate steps are completed and the exact content of previous messages is no longer relevant, use the ox_ai_workers_iterator__summarize function.
|
24
16
|
- Step %d. When the solution is ready, notify about it and wait for the user's response.
|
25
|
-
- Step %d. In the end, call the ox_ai_workers_iterator__finish_it function.
|
17
|
+
- Step %d. In the end, call the ox_ai_workers_iterator__finish_it function.
|
@@ -29,4 +29,19 @@ en:
|
|
29
29
|
description: 'Database Tool: Returns the database schema'
|
30
30
|
execute:
|
31
31
|
description: 'Database Tool: Executes a SQL query and returns the results'
|
32
|
-
input: 'SQL query to be executed'
|
32
|
+
input: 'SQL query to be executed'
|
33
|
+
pipeline:
|
34
|
+
send_message:
|
35
|
+
description: 'Send a message to another assistant'
|
36
|
+
message: 'Message or task to send'
|
37
|
+
result: 'Description of the expected result, what should be obtained as output'
|
38
|
+
example: 'Example of a good result'
|
39
|
+
to_id: 'Recipient assistant ID'
|
40
|
+
assistant_info: "ID: **%{id}**, Title: %{title}\nRole: %{role}\nDescription: %{description}\nCapabilities: %{capabilities}"
|
41
|
+
pixels:
|
42
|
+
generate_image:
|
43
|
+
description: 'Image Generation Tool: Creates an image based on the provided text prompt. If a file name is provided, the image will be saved in png format. In any case, the url of the generated image will be returned.'
|
44
|
+
prompt: 'Text description of the image to generate'
|
45
|
+
size: 'Size of the generated image (1024x1792, 1792x1024, 1024x1024)'
|
46
|
+
quality: 'Quality of the generated image (standard, hd)'
|
47
|
+
file_name: 'File name for saving the generated image in png format. For example: image.png'
|
@@ -2,10 +2,44 @@ ru:
|
|
2
2
|
oxaiworkers:
|
3
3
|
assistant:
|
4
4
|
sysop:
|
5
|
-
|
5
|
+
title: "Системный оператор"
|
6
|
+
description: "Выполняет системные команды и операции с файлами"
|
7
|
+
capabilities: "выполнение shell-команд, чтение и запись файлов, анализ системной информации"
|
8
|
+
role: "Ты опытный системный администратор, который может выполнять shell-команды и операции с файловой системой. Твоя задача - безопасно и эффективно управлять системой."
|
6
9
|
coder:
|
7
|
-
|
10
|
+
title: "Программист"
|
11
|
+
description: "Пишет и анализирует код"
|
12
|
+
capabilities: "генерация кода, рефакторинг, анализ кода, оптимизация"
|
13
|
+
role: "Ты опытный программист, который пишет чистый, эффективный код и может объяснить сложные технические концепции простым языком."
|
14
|
+
role_with_language: "Ты опытный программист на %{language}, который пишет чистый, эффективный код и может объяснить сложные технические концепции простым языком."
|
8
15
|
localizer:
|
9
|
-
|
10
|
-
|
11
|
-
|
16
|
+
title: "Локализатор"
|
17
|
+
description: "Выполняет перевод и адаптацию контента"
|
18
|
+
capabilities: "перевод текста, адаптация контента, сохранение форматирования"
|
19
|
+
role: "Ты опытный переводчик и локализатор контента с языка %{source_lang}. Твоя задача - перевести контент, сохраняя его смысл, стиль и форматирование."
|
20
|
+
role_with_target: "Ты опытный переводчик и локализатор контента с языка %{source_lang} на %{target_lang}. Твоя задача - перевести контент, сохраняя его смысл, стиль и форматирование."
|
21
|
+
source: "Исходный язык: %{source_lang}"
|
22
|
+
locale: "Целевой язык: %{target_lang}"
|
23
|
+
orchestrator:
|
24
|
+
title: "Оркестратор"
|
25
|
+
description: "Управляет взаимодействием между ассистентами"
|
26
|
+
capabilities: "планирование рабочего процесса, распределение задач, мониторинг выполнения"
|
27
|
+
role: "Ты оркестратор, координирующий работу между различными ассистентами. Твоя задача - распределять задачи между ассистентами и организовывать их взаимодействие для достижения общей цели."
|
28
|
+
workflow_task: |
|
29
|
+
Тебе необходимо организовать рабочий процесс согласно следующему описанию:
|
30
|
+
|
31
|
+
%{workflow_description}
|
32
|
+
|
33
|
+
Разработай план действий, распределив задачи между доступными ассистентами, и координируй их взаимодействие для достижения цели.
|
34
|
+
|
35
|
+
Для каждого шага отправляй сообщение другому ассистенту, указав:
|
36
|
+
1. ID ассистента, который должен выполнить задачу
|
37
|
+
2. Описание задачи для ассистента
|
38
|
+
3. Ожидаемый результат
|
39
|
+
|
40
|
+
После завершения каждого шага анализируй результат и принимай решение о дальнейших действиях.
|
41
|
+
painter:
|
42
|
+
title: "Художник"
|
43
|
+
description: "Создает и изменяет изображения на основе описаний"
|
44
|
+
capabilities: "генерация изображений, редактирование изображений, адаптация стиля, создание визуальных концепций"
|
45
|
+
role: "Ты опытный цифровой художник, который создает и изменяет изображения на основе описаний. Твоя задача - генерировать визуально привлекательные и точные представления концепций и идей. Улучши запрос пользователя, добавь в него детали, которые помогут получить более точный результат."
|
@@ -7,13 +7,6 @@ ru:
|
|
7
7
|
outer_voice:
|
8
8
|
description: Функция для сообщений пользователю промежуточной информации без ожидания ответа.
|
9
9
|
text: Содержимое сообщения
|
10
|
-
action_request:
|
11
|
-
description: Функция для интерактивного взаимодействия с пользователем. Позволяет задать уточняющий вопрос, запросить выполнение действий или завершить текущий шаг. Функция ожидает ответ пользователя и возвращает его.
|
12
|
-
action: Текст запроса или действия
|
13
|
-
summarize:
|
14
|
-
description: Функция сохраняет ключевые факты, нюансы и действия из предыдущих сообщений, включая предоставленный ответ. После вызова этой функции все предыдущие сообщения будут удалены. Используйте её только после завершения всех промежуточных шагов и когда точное содержание предыдущих сообщений больше не имеет значения.
|
15
|
-
text: Перечисление важных фактов и нюансов
|
16
|
-
result: Сообщения удалены
|
17
10
|
finish_it:
|
18
11
|
description: Функция для завершения шагов
|
19
12
|
monologue:
|
@@ -23,8 +16,6 @@ ru:
|
|
23
16
|
- Шаг %d. Последовательно выполняй шаги плана, вызывая необходимые пользовательские функции (инструменты) для обработки данных или получения результата.
|
24
17
|
- Шаг %d. Используй ox_ai_workers_iterator__inner_monologue для рефлексии над результатами каждого шага и, при необходимости, корректировки плана.
|
25
18
|
- Шаг %d. Если требуется сообщить пользователю о ходе выполнения *без* ожидания ответа, используй ox_ai_workers_iterator__outer_voice.
|
26
|
-
- Шаг %d. Когда промежуточные шаги завершены и точное содержание предыдущих сообщений больше не важно, сожми историю диалога с помощью ox_ai_workers_iterator__summarize.
|
27
19
|
- Шаг %d. После выполнения всех шагов плана и получения финального результата через вызов соответствующей функции (инструмента), оцени полноту и корректность решения.
|
28
|
-
- Шаг %d.
|
29
|
-
-
|
30
|
-
- Старайся выполнить работу наилучшим образом, используя доступные инструменты максимально эффективно.
|
20
|
+
- Шаг %d. После успешного завершения задачи и получения результата, вызови ox_ai_workers_iterator__finish_it.
|
21
|
+
- Старайся выполнить работу наилучшим образом, используя доступные инструменты максимально эффективно.
|