@hazeljs/ai 0.2.0-alpha.1

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.
Files changed (93) hide show
  1. package/LICENSE +192 -0
  2. package/README.md +497 -0
  3. package/dist/ai-enhanced.service.d.ts +108 -0
  4. package/dist/ai-enhanced.service.d.ts.map +1 -0
  5. package/dist/ai-enhanced.service.js +345 -0
  6. package/dist/ai-enhanced.service.test.d.ts +2 -0
  7. package/dist/ai-enhanced.service.test.d.ts.map +1 -0
  8. package/dist/ai-enhanced.service.test.js +501 -0
  9. package/dist/ai-enhanced.test.d.ts +2 -0
  10. package/dist/ai-enhanced.test.d.ts.map +1 -0
  11. package/dist/ai-enhanced.test.js +587 -0
  12. package/dist/ai-enhanced.types.d.ts +277 -0
  13. package/dist/ai-enhanced.types.d.ts.map +1 -0
  14. package/dist/ai-enhanced.types.js +2 -0
  15. package/dist/ai.decorator.d.ts +4 -0
  16. package/dist/ai.decorator.d.ts.map +1 -0
  17. package/dist/ai.decorator.js +57 -0
  18. package/dist/ai.decorator.test.d.ts +2 -0
  19. package/dist/ai.decorator.test.d.ts.map +1 -0
  20. package/dist/ai.decorator.test.js +189 -0
  21. package/dist/ai.module.d.ts +12 -0
  22. package/dist/ai.module.d.ts.map +1 -0
  23. package/dist/ai.module.js +44 -0
  24. package/dist/ai.module.test.d.ts +2 -0
  25. package/dist/ai.module.test.d.ts.map +1 -0
  26. package/dist/ai.module.test.js +23 -0
  27. package/dist/ai.service.d.ts +11 -0
  28. package/dist/ai.service.d.ts.map +1 -0
  29. package/dist/ai.service.js +266 -0
  30. package/dist/ai.service.test.d.ts +2 -0
  31. package/dist/ai.service.test.d.ts.map +1 -0
  32. package/dist/ai.service.test.js +222 -0
  33. package/dist/ai.types.d.ts +30 -0
  34. package/dist/ai.types.d.ts.map +1 -0
  35. package/dist/ai.types.js +2 -0
  36. package/dist/context/context.manager.d.ts +69 -0
  37. package/dist/context/context.manager.d.ts.map +1 -0
  38. package/dist/context/context.manager.js +168 -0
  39. package/dist/context/context.manager.test.d.ts +2 -0
  40. package/dist/context/context.manager.test.d.ts.map +1 -0
  41. package/dist/context/context.manager.test.js +180 -0
  42. package/dist/decorators/ai-function.decorator.d.ts +42 -0
  43. package/dist/decorators/ai-function.decorator.d.ts.map +1 -0
  44. package/dist/decorators/ai-function.decorator.js +80 -0
  45. package/dist/decorators/ai-validate.decorator.d.ts +46 -0
  46. package/dist/decorators/ai-validate.decorator.d.ts.map +1 -0
  47. package/dist/decorators/ai-validate.decorator.js +83 -0
  48. package/dist/index.d.ts +18 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +40 -0
  51. package/dist/prompts/task.prompt.d.ts +12 -0
  52. package/dist/prompts/task.prompt.d.ts.map +1 -0
  53. package/dist/prompts/task.prompt.js +12 -0
  54. package/dist/providers/anthropic.provider.d.ts +48 -0
  55. package/dist/providers/anthropic.provider.d.ts.map +1 -0
  56. package/dist/providers/anthropic.provider.js +194 -0
  57. package/dist/providers/anthropic.provider.test.d.ts +2 -0
  58. package/dist/providers/anthropic.provider.test.d.ts.map +1 -0
  59. package/dist/providers/anthropic.provider.test.js +222 -0
  60. package/dist/providers/cohere.provider.d.ts +57 -0
  61. package/dist/providers/cohere.provider.d.ts.map +1 -0
  62. package/dist/providers/cohere.provider.js +230 -0
  63. package/dist/providers/cohere.provider.test.d.ts +2 -0
  64. package/dist/providers/cohere.provider.test.d.ts.map +1 -0
  65. package/dist/providers/cohere.provider.test.js +267 -0
  66. package/dist/providers/gemini.provider.d.ts +45 -0
  67. package/dist/providers/gemini.provider.d.ts.map +1 -0
  68. package/dist/providers/gemini.provider.js +180 -0
  69. package/dist/providers/gemini.provider.test.d.ts +2 -0
  70. package/dist/providers/gemini.provider.test.d.ts.map +1 -0
  71. package/dist/providers/gemini.provider.test.js +219 -0
  72. package/dist/providers/ollama.provider.d.ts +45 -0
  73. package/dist/providers/ollama.provider.d.ts.map +1 -0
  74. package/dist/providers/ollama.provider.js +232 -0
  75. package/dist/providers/ollama.provider.test.d.ts +2 -0
  76. package/dist/providers/ollama.provider.test.d.ts.map +1 -0
  77. package/dist/providers/ollama.provider.test.js +267 -0
  78. package/dist/providers/openai.provider.d.ts +57 -0
  79. package/dist/providers/openai.provider.d.ts.map +1 -0
  80. package/dist/providers/openai.provider.js +320 -0
  81. package/dist/providers/openai.provider.test.d.ts +2 -0
  82. package/dist/providers/openai.provider.test.d.ts.map +1 -0
  83. package/dist/providers/openai.provider.test.js +364 -0
  84. package/dist/tracking/token.tracker.d.ts +72 -0
  85. package/dist/tracking/token.tracker.d.ts.map +1 -0
  86. package/dist/tracking/token.tracker.js +222 -0
  87. package/dist/tracking/token.tracker.test.d.ts +2 -0
  88. package/dist/tracking/token.tracker.test.d.ts.map +1 -0
  89. package/dist/tracking/token.tracker.test.js +272 -0
  90. package/dist/vector/vector.service.d.ts +50 -0
  91. package/dist/vector/vector.service.d.ts.map +1 -0
  92. package/dist/vector/vector.service.js +163 -0
  93. package/package.json +60 -0
package/LICENSE ADDED
@@ -0,0 +1,192 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ Copyright 2024 HazelJS Team
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+
19
+ ---
20
+
21
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
22
+
23
+ 1. Definitions.
24
+
25
+ "License" shall mean the terms and conditions for use, reproduction,
26
+ and distribution as defined by Sections 1 through 9 of this document.
27
+
28
+ "Licensor" shall mean the copyright owner or entity authorized by
29
+ the copyright owner that is granting the License.
30
+
31
+ "Legal Entity" shall mean the union of the acting entity and all
32
+ other entities that control, are controlled by, or are under common
33
+ control with that entity. For the purposes of this definition,
34
+ "control" means (i) the power, direct or indirect, to cause the
35
+ direction or management of such entity, whether by contract or
36
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
37
+ outstanding shares, or (iii) beneficial ownership of such entity.
38
+
39
+ "You" (or "Your") shall mean an individual or Legal Entity
40
+ exercising permissions granted by this License.
41
+
42
+ "Source" form shall mean the preferred form for making modifications,
43
+ including but not limited to software source code, documentation
44
+ source, and configuration files.
45
+
46
+ "Object" form shall mean any form resulting from mechanical
47
+ transformation or translation of a Source form, including but
48
+ not limited to compiled object code, generated documentation,
49
+ and conversions to other media types.
50
+
51
+ "Work" shall mean the work of authorship, whether in Source or
52
+ Object form, made available under the License, as indicated by a
53
+ copyright notice that is included in or attached to the work
54
+ (an example is provided in the Appendix below).
55
+
56
+ "Derivative Works" shall mean any work, whether in Source or Object
57
+ form, that is based on (or derived from) the Work and for which the
58
+ editorial revisions, annotations, elaborations, or other modifications
59
+ represent, as a whole, an original work of authorship. For the purposes
60
+ of this License, Derivative Works shall not include works that remain
61
+ separable from, or merely link (or bind by name) to the interfaces of,
62
+ the Work and Derivative Works thereof.
63
+
64
+ "Contribution" shall mean any work of authorship, including
65
+ the original version of the Work and any modifications or additions
66
+ to that Work or Derivative Works thereof, that is intentionally
67
+ submitted to Licensor for inclusion in the Work by the copyright owner
68
+ or by an individual or Legal Entity authorized to submit on behalf of
69
+ the copyright owner. For the purposes of this definition, "submitted"
70
+ means any form of electronic, verbal, or written communication sent
71
+ to the Licensor or its representatives, including but not limited to
72
+ communication on electronic mailing lists, source code control systems,
73
+ and issue tracking systems that are managed by, or on behalf of, the
74
+ Licensor for the purpose of discussing and improving the Work, but
75
+ excluding communication that is conspicuously marked or otherwise
76
+ designated in writing by the copyright owner as "Not a Contribution."
77
+
78
+ "Contributor" shall mean Licensor and any individual or Legal Entity
79
+ on behalf of whom a Contribution has been received by Licensor and
80
+ subsequently incorporated within the Work.
81
+
82
+ 2. Grant of Copyright License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ copyright license to reproduce, prepare Derivative Works of,
86
+ publicly display, publicly perform, sublicense, and distribute the
87
+ Work and such Derivative Works in Source or Object form.
88
+
89
+ 3. Grant of Patent License. Subject to the terms and conditions of
90
+ this License, each Contributor hereby grants to You a perpetual,
91
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
92
+ (except as stated in this section) patent license to make, have made,
93
+ use, offer to sell, sell, import, and otherwise transfer the Work,
94
+ where such license applies only to those patent claims licensable
95
+ by such Contributor that are necessarily infringed by their
96
+ Contribution(s) alone or by combination of their Contribution(s)
97
+ with the Work to which such Contribution(s) was submitted. If You
98
+ institute patent litigation against any entity (including a
99
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
100
+ or a Contribution incorporated within the Work constitutes direct
101
+ or contributory patent infringement, then any patent licenses
102
+ granted to You under this License for that Work shall terminate
103
+ as of the date such litigation is filed.
104
+
105
+ 4. Redistribution. You may reproduce and distribute copies of the
106
+ Work or Derivative Works thereof in any medium, with or without
107
+ modifications, and in Source or Object form, provided that You
108
+ meet the following conditions:
109
+
110
+ (a) You must give any other recipients of the Work or
111
+ Derivative Works a copy of this License; and
112
+
113
+ (b) You must cause any modified files to carry prominent notices
114
+ stating that You changed the files; and
115
+
116
+ (c) You must retain, in the Source form of any Derivative Works
117
+ that You distribute, all copyright, patent, trademark, and
118
+ attribution notices from the Source form of the Work,
119
+ excluding those notices that do not pertain to any part of
120
+ the Derivative Works; and
121
+
122
+ (d) If the Work includes a "NOTICE" text file as part of its
123
+ distribution, then any Derivative Works that You distribute must
124
+ include a readable copy of the attribution notices contained
125
+ within such NOTICE file, excluding those notices that do not
126
+ pertain to any part of the Derivative Works, in at least one
127
+ of the following places: within a NOTICE text file distributed
128
+ as part of the Derivative Works; within the Source form or
129
+ documentation, if provided along with the Derivative Works; or,
130
+ within a display generated by the Derivative Works, if and
131
+ wherever such third-party notices normally appear. The contents
132
+ of the NOTICE file are for informational purposes only and
133
+ do not modify the License. You may add Your own attribution
134
+ notices within Derivative Works that You distribute, alongside
135
+ or as an addendum to the NOTICE text from the Work, provided
136
+ that such additional attribution notices cannot be construed
137
+ as modifying the License.
138
+
139
+ You may add Your own copyright statement to Your modifications and
140
+ may provide additional or different license terms and conditions
141
+ for use, reproduction, or distribution of Your modifications, or
142
+ for any such Derivative Works as a whole, provided Your use,
143
+ reproduction, and distribution of the Work otherwise complies with
144
+ the conditions stated in this License.
145
+
146
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
147
+ any Contribution intentionally submitted for inclusion in the Work
148
+ by You to the Licensor shall be under the terms and conditions of
149
+ this License, without any additional terms or conditions.
150
+ Notwithstanding the above, nothing herein shall supersede or modify
151
+ the terms of any separate license agreement you may have executed
152
+ with Licensor regarding such Contributions.
153
+
154
+ 6. Trademarks. This License does not grant permission to use the trade
155
+ names, trademarks, service marks, or product names of the Licensor,
156
+ except as required for reasonable and customary use in describing the
157
+ origin of the Work and reproducing the content of the NOTICE file.
158
+
159
+ 7. Disclaimer of Warranty. Unless required by applicable law or
160
+ agreed to in writing, Licensor provides the Work (and each
161
+ Contributor provides its Contributions) on an "AS IS" BASIS,
162
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
163
+ implied, including, without limitation, any warranties or conditions
164
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
165
+ PARTICULAR PURPOSE. You are solely responsible for determining the
166
+ appropriateness of using or redistributing the Work and assume any
167
+ risks associated with Your exercise of permissions under this License.
168
+
169
+ 8. Limitation of Liability. In no event and under no legal theory,
170
+ whether in tort (including negligence), contract, or otherwise,
171
+ unless required by applicable law (such as deliberate and grossly
172
+ negligent acts) or agreed to in writing, shall any Contributor be
173
+ liable to You for damages, including any direct, indirect, special,
174
+ incidental, or consequential damages of any character arising as a
175
+ result of this License or out of the use or inability to use the
176
+ Work (including but not limited to damages for loss of goodwill,
177
+ work stoppage, computer failure or malfunction, or any and all
178
+ other commercial damages or losses), even if such Contributor
179
+ has been advised of the possibility of such damages.
180
+
181
+ 9. Accepting Warranty or Additional Liability. While redistributing
182
+ the Work or Derivative Works thereof, You may choose to offer,
183
+ and charge a fee for, acceptance of support, warranty, indemnity,
184
+ or other liability obligations and/or rights consistent with this
185
+ License. However, in accepting such obligations, You may act only
186
+ on Your own behalf and on Your sole responsibility, not on behalf
187
+ of any other Contributor, and only if You agree to indemnify,
188
+ defend, and hold each Contributor harmless for any liability
189
+ incurred by, or claims asserted against, such Contributor by reason
190
+ of your accepting any such warranty or additional liability.
191
+
192
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,497 @@
1
+ # @hazeljs/ai
2
+
3
+ **Add AI to your API in minutes — not days.**
4
+
5
+ OpenAI, Anthropic, Gemini, Cohere, Ollama. One decorator, one config. Streaming, caching, retries, and type-safe outputs. Ship AI features without the glue code.
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@hazeljs/ai.svg)](https://www.npmjs.com/package/@hazeljs/ai)
8
+ [![npm downloads](https://img.shields.io/npm/dm/@hazeljs/ai)](https://www.npmjs.com/package/@hazeljs/ai)
9
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
10
+
11
+ ## Features
12
+
13
+ - 🤖 **Multiple Providers** - OpenAI, Anthropic, Gemini, Cohere, Ollama
14
+ - 🎨 **Decorator-Based API** - `@AITask` decorator for clean integration
15
+ - 📡 **Streaming Support** - Real-time response streaming
16
+ - 🔄 **Retry Logic** - Automatic retries with exponential backoff
17
+ - 💾 **Response Caching** - Built-in caching with @hazeljs/cache
18
+ - 🎯 **Type Safety** - Full TypeScript support with output types
19
+ - 🔧 **Flexible Configuration** - Per-task or global configuration
20
+ - 📊 **Token Tracking** - Monitor usage and costs
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install @hazeljs/ai
26
+ ```
27
+
28
+ ### Peer Dependencies
29
+
30
+ Install the provider(s) you want to use:
31
+
32
+ ```bash
33
+ # OpenAI
34
+ npm install openai
35
+
36
+ # Anthropic
37
+ npm install @anthropic-ai/sdk
38
+
39
+ # Google Gemini
40
+ npm install @google/generative-ai
41
+
42
+ # Cohere
43
+ npm install cohere-ai
44
+
45
+ # Ollama (local LLMs)
46
+ npm install ollama
47
+ ```
48
+
49
+ ## Quick Start
50
+
51
+ ### Basic Usage with Decorator
52
+
53
+ ```typescript
54
+ import { Injectable } from '@hazeljs/core';
55
+ import { AIService, AITask } from '@hazeljs/ai';
56
+
57
+ @Injectable()
58
+ export class ChatService {
59
+ constructor(private aiService: AIService) {}
60
+
61
+ @AITask({
62
+ name: 'chat',
63
+ prompt: 'You are a helpful assistant. Respond to: {{input}}',
64
+ provider: 'openai',
65
+ model: 'gpt-4',
66
+ outputType: 'string',
67
+ })
68
+ async chat(message: string): Promise<string> {
69
+ return message; // Decorator handles AI execution
70
+ }
71
+ }
72
+
73
+ // Usage
74
+ const response = await chatService.chat('Hello, how are you?');
75
+ console.log(response);
76
+ ```
77
+
78
+ ### Direct AI Service Usage
79
+
80
+ ```typescript
81
+ import { AIEnhancedService } from '@hazeljs/ai';
82
+
83
+ const aiService = new AIEnhancedService();
84
+
85
+ const response = await aiService.complete({
86
+ messages: [
87
+ { role: 'system', content: 'You are a helpful assistant' },
88
+ { role: 'user', content: 'What is TypeScript?' }
89
+ ],
90
+ model: 'gpt-4',
91
+ provider: 'openai',
92
+ temperature: 0.7,
93
+ maxTokens: 500,
94
+ });
95
+
96
+ console.log(response.content);
97
+ console.log('Tokens used:', response.usage);
98
+ ```
99
+
100
+ ## Providers
101
+
102
+ ### OpenAI
103
+
104
+ ```typescript
105
+ import { AIEnhancedService } from '@hazeljs/ai';
106
+
107
+ const aiService = new AIEnhancedService();
108
+
109
+ // GPT-4
110
+ const response = await aiService.complete({
111
+ messages: [{ role: 'user', content: 'Hello!' }],
112
+ model: 'gpt-4',
113
+ provider: 'openai',
114
+ });
115
+
116
+ // GPT-3.5 Turbo
117
+ const response2 = await aiService.complete({
118
+ messages: [{ role: 'user', content: 'Hello!' }],
119
+ model: 'gpt-3.5-turbo',
120
+ provider: 'openai',
121
+ });
122
+ ```
123
+
124
+ ### Anthropic Claude
125
+
126
+ ```typescript
127
+ const response = await aiService.complete({
128
+ messages: [{ role: 'user', content: 'Explain quantum computing' }],
129
+ model: 'claude-3-opus-20240229',
130
+ provider: 'anthropic',
131
+ maxTokens: 1000,
132
+ });
133
+ ```
134
+
135
+ ### Google Gemini
136
+
137
+ ```typescript
138
+ const response = await aiService.complete({
139
+ messages: [{ role: 'user', content: 'Write a poem' }],
140
+ model: 'gemini-pro',
141
+ provider: 'gemini',
142
+ });
143
+ ```
144
+
145
+ ### Cohere
146
+
147
+ ```typescript
148
+ const response = await aiService.complete({
149
+ messages: [{ role: 'user', content: 'Summarize this text' }],
150
+ model: 'command',
151
+ provider: 'cohere',
152
+ });
153
+ ```
154
+
155
+ ### Ollama (Local LLMs)
156
+
157
+ ```typescript
158
+ const response = await aiService.complete({
159
+ messages: [{ role: 'user', content: 'Hello!' }],
160
+ model: 'llama2',
161
+ provider: 'ollama',
162
+ baseURL: 'http://localhost:11434',
163
+ });
164
+ ```
165
+
166
+ ## Streaming
167
+
168
+ ```typescript
169
+ import { AIEnhancedService } from '@hazeljs/ai';
170
+
171
+ const aiService = new AIEnhancedService();
172
+
173
+ // Stream responses in real-time
174
+ for await (const chunk of aiService.streamComplete({
175
+ messages: [{ role: 'user', content: 'Tell me a long story' }],
176
+ provider: 'openai',
177
+ model: 'gpt-4',
178
+ })) {
179
+ process.stdout.write(chunk.delta);
180
+ }
181
+ ```
182
+
183
+ ### Streaming with Decorator
184
+
185
+ ```typescript
186
+ @AITask({
187
+ name: 'stream-chat',
188
+ prompt: 'You are a storyteller. Tell a story about: {{topic}}',
189
+ provider: 'openai',
190
+ model: 'gpt-4',
191
+ stream: true,
192
+ })
193
+ async streamStory(topic: string): AsyncGenerator<string> {
194
+ return topic; // Returns async generator
195
+ }
196
+
197
+ // Usage
198
+ for await (const chunk of chatService.streamStory('dragons')) {
199
+ console.log(chunk);
200
+ }
201
+ ```
202
+
203
+ ## Advanced Features
204
+
205
+ ### Response Caching
206
+
207
+ ```typescript
208
+ import { AITask } from '@hazeljs/ai';
209
+
210
+ @AITask({
211
+ name: 'cached-completion',
212
+ prompt: 'Explain {{concept}}',
213
+ provider: 'openai',
214
+ model: 'gpt-4',
215
+ cache: {
216
+ enabled: true,
217
+ ttl: 3600, // 1 hour
218
+ key: 'explain-{{concept}}',
219
+ },
220
+ })
221
+ async explainConcept(concept: string): Promise<string> {
222
+ return concept;
223
+ }
224
+ ```
225
+
226
+ ### Retry Logic
227
+
228
+ ```typescript
229
+ const response = await aiService.complete({
230
+ messages: [{ role: 'user', content: 'Hello' }],
231
+ provider: 'openai',
232
+ model: 'gpt-4',
233
+ retry: {
234
+ maxRetries: 3,
235
+ initialDelay: 1000,
236
+ maxDelay: 10000,
237
+ backoffMultiplier: 2,
238
+ },
239
+ });
240
+ ```
241
+
242
+ ### Output Type Validation
243
+
244
+ ```typescript
245
+ interface UserProfile {
246
+ name: string;
247
+ age: number;
248
+ interests: string[];
249
+ }
250
+
251
+ @AITask({
252
+ name: 'extract-profile',
253
+ prompt: 'Extract user profile from: {{text}}',
254
+ provider: 'openai',
255
+ model: 'gpt-4',
256
+ outputType: 'json',
257
+ })
258
+ async extractProfile(text: string): Promise<UserProfile> {
259
+ return text;
260
+ }
261
+
262
+ const profile = await service.extractProfile('John is 25 and loves coding');
263
+ console.log(profile.name); // Type-safe!
264
+ ```
265
+
266
+ ### Function Calling
267
+
268
+ ```typescript
269
+ const response = await aiService.complete({
270
+ messages: [{ role: 'user', content: 'What is the weather in NYC?' }],
271
+ provider: 'openai',
272
+ model: 'gpt-4',
273
+ functions: [
274
+ {
275
+ name: 'get_weather',
276
+ description: 'Get the current weather in a location',
277
+ parameters: {
278
+ type: 'object',
279
+ properties: {
280
+ location: {
281
+ type: 'string',
282
+ description: 'The city and state, e.g. San Francisco, CA',
283
+ },
284
+ unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
285
+ },
286
+ required: ['location'],
287
+ },
288
+ },
289
+ ],
290
+ functionCall: 'auto',
291
+ });
292
+
293
+ if (response.functionCall) {
294
+ console.log('Function:', response.functionCall.name);
295
+ console.log('Arguments:', response.functionCall.arguments);
296
+ }
297
+ ```
298
+
299
+ ## Configuration
300
+
301
+ ### Global Configuration
302
+
303
+ ```typescript
304
+ import { AIModule } from '@hazeljs/ai';
305
+
306
+ @HazelModule({
307
+ imports: [
308
+ AIModule.forRoot({
309
+ providers: {
310
+ openai: {
311
+ apiKey: process.env.OPENAI_API_KEY,
312
+ organization: process.env.OPENAI_ORG,
313
+ },
314
+ anthropic: {
315
+ apiKey: process.env.ANTHROPIC_API_KEY,
316
+ },
317
+ gemini: {
318
+ apiKey: process.env.GEMINI_API_KEY,
319
+ },
320
+ },
321
+ defaultProvider: 'openai',
322
+ defaultModel: 'gpt-4',
323
+ cache: {
324
+ enabled: true,
325
+ ttl: 3600,
326
+ },
327
+ }),
328
+ ],
329
+ })
330
+ export class AppModule {}
331
+ ```
332
+
333
+ ### Per-Task Configuration
334
+
335
+ ```typescript
336
+ @AITask({
337
+ name: 'custom-task',
338
+ prompt: 'Process: {{input}}',
339
+ provider: 'openai',
340
+ model: 'gpt-4',
341
+ temperature: 0.7,
342
+ maxTokens: 1000,
343
+ topP: 0.9,
344
+ frequencyPenalty: 0.5,
345
+ presencePenalty: 0.5,
346
+ stop: ['\n\n'],
347
+ })
348
+ async processInput(input: string): Promise<string> {
349
+ return input;
350
+ }
351
+ ```
352
+
353
+ ## Use Cases
354
+
355
+ ### Chatbot
356
+
357
+ ```typescript
358
+ @Injectable()
359
+ export class ChatbotService {
360
+ private conversationHistory: Array<{ role: string; content: string }> = [];
361
+
362
+ @AITask({
363
+ name: 'chat',
364
+ provider: 'openai',
365
+ model: 'gpt-4',
366
+ })
367
+ async chat(message: string): Promise<string> {
368
+ this.conversationHistory.push({ role: 'user', content: message });
369
+
370
+ const response = await this.aiService.complete({
371
+ messages: this.conversationHistory,
372
+ provider: 'openai',
373
+ model: 'gpt-4',
374
+ });
375
+
376
+ this.conversationHistory.push({
377
+ role: 'assistant',
378
+ content: response.content
379
+ });
380
+
381
+ return response.content;
382
+ }
383
+ }
384
+ ```
385
+
386
+ ### Content Generation
387
+
388
+ ```typescript
389
+ @Injectable()
390
+ export class ContentService {
391
+ @AITask({
392
+ name: 'generate-blog',
393
+ prompt: `Write a blog post about {{topic}}.
394
+
395
+ Requirements:
396
+ - Length: {{length}} words
397
+ - Tone: {{tone}}
398
+ - Include SEO keywords: {{keywords}}`,
399
+ provider: 'openai',
400
+ model: 'gpt-4',
401
+ outputType: 'string',
402
+ })
403
+ async generateBlogPost(
404
+ topic: string,
405
+ length: number,
406
+ tone: string,
407
+ keywords: string[]
408
+ ): Promise<string> {
409
+ return topic;
410
+ }
411
+ }
412
+ ```
413
+
414
+ ### Data Extraction
415
+
416
+ ```typescript
417
+ interface ExtractedData {
418
+ entities: string[];
419
+ sentiment: 'positive' | 'negative' | 'neutral';
420
+ summary: string;
421
+ }
422
+
423
+ @Injectable()
424
+ export class AnalysisService {
425
+ @AITask({
426
+ name: 'analyze-text',
427
+ prompt: `Analyze the following text and extract:
428
+ 1. Named entities (people, places, organizations)
429
+ 2. Overall sentiment
430
+ 3. Brief summary
431
+
432
+ Text: {{text}}
433
+
434
+ Return as JSON.`,
435
+ provider: 'openai',
436
+ model: 'gpt-4',
437
+ outputType: 'json',
438
+ })
439
+ async analyzeText(text: string): Promise<ExtractedData> {
440
+ return text;
441
+ }
442
+ }
443
+ ```
444
+
445
+ ## API Reference
446
+
447
+ ### AIEnhancedService
448
+
449
+ ```typescript
450
+ class AIEnhancedService {
451
+ complete(options: AICompletionOptions): Promise<AIResponse>;
452
+ streamComplete(options: AICompletionOptions): AsyncGenerator<AIStreamChunk>;
453
+ embed(text: string, options?: EmbedOptions): Promise<number[]>;
454
+ }
455
+ ```
456
+
457
+ ### @AITask Decorator
458
+
459
+ ```typescript
460
+ @AITask({
461
+ name: string;
462
+ prompt?: string;
463
+ provider: 'openai' | 'anthropic' | 'gemini' | 'cohere' | 'ollama';
464
+ model: string;
465
+ outputType?: 'string' | 'json' | 'number' | 'boolean';
466
+ stream?: boolean;
467
+ temperature?: number;
468
+ maxTokens?: number;
469
+ cache?: CacheOptions;
470
+ retry?: RetryOptions;
471
+ })
472
+ ```
473
+
474
+ ## Examples
475
+
476
+ See the [examples](../../example/src/ai) directory for complete working examples.
477
+
478
+ ## Testing
479
+
480
+ ```bash
481
+ npm test
482
+ ```
483
+
484
+ ## Contributing
485
+
486
+ Contributions are welcome! Please read our [Contributing Guide](../../CONTRIBUTING.md) for details.
487
+
488
+ ## License
489
+
490
+ Apache 2.0 © [HazelJS](https://hazeljs.com)
491
+
492
+ ## Links
493
+
494
+ - [Documentation](https://hazeljs.com/docs/packages/ai)
495
+ - [GitHub](https://github.com/hazel-js/hazeljs)
496
+ - [Issues](https://github.com/hazel-js/hazeljs/issues)
497
+ - [Discord](https://discord.com/channels/1448263814238965833/1448263814859456575)