@agentic-kit/openai 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Dan Lynch <pyramation@gmail.com>
4
+ Copyright (c) 2025 Constructive <developers@constructive.io>
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # @agentic-kit/openai
2
+
3
+ <p align="center" width="100%">
4
+ <img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
5
+ </p>
6
+
7
+ <p align="center" width="100%">
8
+ <a href="https://github.com/constructive-io/agentic-kit/actions/workflows/run-tests.yaml">
9
+ <img height="20" src="https://github.com/constructive-io/agentic-kit/actions/workflows/run-tests.yaml/badge.svg" />
10
+ </a>
11
+ <a href="https://github.com/constructive-io/agentic-kit/blob/main/LICENSE"><img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/></a>
12
+ <a href="https://www.npmjs.com/package/@agentic-kit/openai"><img height="20" src="https://img.shields.io/github/package-json/v/constructive-io/agentic-kit?filename=packages%2Fopenai%2Fpackage.json"/></a>
13
+ </p>
14
+
15
+ OpenAI (and OpenAI-compatible) adapter for agentic-kit. Works with GPT models, LM Studio, vLLM, Together AI, and any OpenAI-compatible endpoint.
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @agentic-kit/openai
21
+ ```
22
+
23
+ ---
24
+
25
+ ## Related Constructive Tooling
26
+
27
+ ### πŸ€– AI & Agent Development
28
+
29
+ * [agentic-kit](https://github.com/constructive-io/agentic-kit): **🧰 Provider-agnostic LLM adapter** with streaming and multi-turn support. Swap between Anthropic, OpenAI, Ollama, and any OpenAI-compatible endpoint.
30
+
31
+ ### πŸ“¦ Package Management
32
+
33
+ * [pgpm](https://github.com/constructive-io/constructive/tree/main/pgpm/pgpm): **πŸ–₯️ PostgreSQL Package Manager** for modular Postgres development. Works with database workspaces, scaffolding, migrations, seeding, and installing database packages.
34
+
35
+ ### πŸ§ͺ Testing
36
+
37
+ * [pgsql-test](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-test): **πŸ“Š Isolated testing environments** with per-test transaction rollbacksβ€”ideal for integration tests, complex migrations, and RLS simulation.
38
+ * [pgsql-seed](https://github.com/constructive-io/constructive/tree/main/postgres/pgsql-seed): **🌱 PostgreSQL seeding utilities** for CSV, JSON, SQL data loading, and pgpm deployment.
39
+ * [supabase-test](https://github.com/constructive-io/constructive/tree/main/postgres/supabase-test): **πŸ§ͺ Supabase-native test harness** preconfigured for the local Supabase stackβ€”per-test rollbacks, JWT/role context helpers, and CI/GitHub Actions ready.
40
+
41
+ ### 🧠 Parsing & AST
42
+
43
+ * [pgsql-parser](https://www.npmjs.com/package/pgsql-parser): **πŸ”„ SQL conversion engine** that interprets and converts PostgreSQL syntax.
44
+ * [libpg-query-node](https://www.npmjs.com/package/libpg-query): **πŸŒ‰ Node.js bindings** for `libpg_query`, converting SQL into parse trees.
45
+ * [@pgsql/types](https://www.npmjs.com/package/@pgsql/types): **πŸ“ Type definitions** for PostgreSQL AST nodes in TypeScript.
46
+ * [@pgsql/utils](https://www.npmjs.com/package/@pgsql/utils): **πŸ› οΈ AST utilities** for constructing and transforming PostgreSQL syntax trees.
47
+
48
+ ## Credits
49
+
50
+ **πŸ›  Built by the [Constructive](https://constructive.io) team β€” creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
51
+
52
+ ## Disclaimer
53
+
54
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
55
+
56
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/esm/index.js ADDED
@@ -0,0 +1,97 @@
1
+ import fetch from 'cross-fetch';
2
+ // ─── OpenAIAdapter ────────────────────────────────────────────────────────────
3
+ export class OpenAIAdapter {
4
+ name = 'openai';
5
+ apiKey;
6
+ baseUrl;
7
+ defaultModel;
8
+ defaultMaxTokens;
9
+ constructor(options) {
10
+ const opts = typeof options === 'string' ? { apiKey: options } : options;
11
+ this.apiKey = opts.apiKey;
12
+ this.baseUrl = opts.baseUrl ?? 'https://api.openai.com';
13
+ this.defaultModel = opts.defaultModel ?? 'gpt-4o';
14
+ this.defaultMaxTokens = opts.maxTokens ?? 4096;
15
+ }
16
+ async generate(input) {
17
+ return this._request(input);
18
+ }
19
+ async generateStreaming(input, onChunk) {
20
+ return this._request(input, onChunk);
21
+ }
22
+ async listModels() {
23
+ return ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'o1', 'o1-mini', 'o3-mini'];
24
+ }
25
+ // ── Private ───────────────────────────────────────────────────────────────────
26
+ async _request(input, onChunk) {
27
+ const body = {
28
+ model: input.model || this.defaultModel,
29
+ messages: this._buildMessages(input),
30
+ stream: !!onChunk,
31
+ max_tokens: input.maxTokens ?? this.defaultMaxTokens,
32
+ ...(input.temperature !== undefined && { temperature: input.temperature }),
33
+ };
34
+ const res = await fetch(`${this.baseUrl}/v1/chat/completions`, {
35
+ method: 'POST',
36
+ headers: {
37
+ 'Content-Type': 'application/json',
38
+ 'Authorization': `Bearer ${this.apiKey}`,
39
+ },
40
+ body: JSON.stringify(body),
41
+ });
42
+ if (!res.ok) {
43
+ const text = await res.text().catch(() => '');
44
+ throw new Error(`OpenAI error ${res.status}: ${text}`);
45
+ }
46
+ if (onChunk)
47
+ return this._stream(res, onChunk);
48
+ const data = await res.json();
49
+ return data.choices[0]?.message?.content ?? '';
50
+ }
51
+ _buildMessages(input) {
52
+ // OpenAI supports system role natively in messages[]
53
+ const msgs = [];
54
+ if (input.system)
55
+ msgs.push({ role: 'system', content: input.system });
56
+ if (input.messages) {
57
+ const filtered = input.system
58
+ ? input.messages.filter((m) => m.role !== 'system')
59
+ : input.messages;
60
+ msgs.push(...filtered);
61
+ }
62
+ else if (input.prompt) {
63
+ msgs.push({ role: 'user', content: input.prompt });
64
+ }
65
+ return msgs;
66
+ }
67
+ async _stream(res, onChunk) {
68
+ const reader = res.body?.getReader();
69
+ if (!reader)
70
+ throw new Error('No response body');
71
+ const decoder = new TextDecoder();
72
+ let buffer = '';
73
+ while (true) {
74
+ const { done, value } = await reader.read();
75
+ if (done)
76
+ break;
77
+ buffer += decoder.decode(value, { stream: true });
78
+ const lines = buffer.split('\n');
79
+ buffer = lines.pop() ?? '';
80
+ for (const line of lines) {
81
+ if (!line.startsWith('data: '))
82
+ continue;
83
+ const payload = line.slice(6).trim();
84
+ if (payload === '[DONE]')
85
+ return;
86
+ try {
87
+ const chunk = JSON.parse(payload);
88
+ const content = chunk.choices[0]?.delta?.content;
89
+ if (content)
90
+ onChunk(content);
91
+ }
92
+ catch { /* malformed β€” skip */ }
93
+ }
94
+ }
95
+ }
96
+ }
97
+ export default OpenAIAdapter;
package/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ export interface ChatMessage {
2
+ role: 'system' | 'user' | 'assistant';
3
+ content: string;
4
+ }
5
+ export interface GenerateInput {
6
+ model: string;
7
+ prompt?: string;
8
+ messages?: ChatMessage[];
9
+ system?: string;
10
+ stream?: boolean;
11
+ temperature?: number;
12
+ maxTokens?: number;
13
+ }
14
+ export interface OpenAIOptions {
15
+ apiKey: string;
16
+ /** Override base URL β€” works with any OpenAI-compatible API (LM Studio, vLLM, Together, etc.) */
17
+ baseUrl?: string;
18
+ /** Default model when GenerateInput.model is not set */
19
+ defaultModel?: string;
20
+ /** Default max_tokens */
21
+ maxTokens?: number;
22
+ }
23
+ export declare class OpenAIAdapter {
24
+ readonly name = "openai";
25
+ private apiKey;
26
+ private baseUrl;
27
+ private defaultModel;
28
+ private defaultMaxTokens;
29
+ constructor(options: OpenAIOptions | string);
30
+ generate(input: GenerateInput): Promise<string>;
31
+ generateStreaming(input: GenerateInput, onChunk: (chunk: string) => void): Promise<void>;
32
+ listModels(): Promise<string[]>;
33
+ private _request;
34
+ private _buildMessages;
35
+ private _stream;
36
+ }
37
+ export default OpenAIAdapter;
package/index.js ADDED
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.OpenAIAdapter = void 0;
7
+ const cross_fetch_1 = __importDefault(require("cross-fetch"));
8
+ // ─── OpenAIAdapter ────────────────────────────────────────────────────────────
9
+ class OpenAIAdapter {
10
+ name = 'openai';
11
+ apiKey;
12
+ baseUrl;
13
+ defaultModel;
14
+ defaultMaxTokens;
15
+ constructor(options) {
16
+ const opts = typeof options === 'string' ? { apiKey: options } : options;
17
+ this.apiKey = opts.apiKey;
18
+ this.baseUrl = opts.baseUrl ?? 'https://api.openai.com';
19
+ this.defaultModel = opts.defaultModel ?? 'gpt-4o';
20
+ this.defaultMaxTokens = opts.maxTokens ?? 4096;
21
+ }
22
+ async generate(input) {
23
+ return this._request(input);
24
+ }
25
+ async generateStreaming(input, onChunk) {
26
+ return this._request(input, onChunk);
27
+ }
28
+ async listModels() {
29
+ return ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'o1', 'o1-mini', 'o3-mini'];
30
+ }
31
+ // ── Private ───────────────────────────────────────────────────────────────────
32
+ async _request(input, onChunk) {
33
+ const body = {
34
+ model: input.model || this.defaultModel,
35
+ messages: this._buildMessages(input),
36
+ stream: !!onChunk,
37
+ max_tokens: input.maxTokens ?? this.defaultMaxTokens,
38
+ ...(input.temperature !== undefined && { temperature: input.temperature }),
39
+ };
40
+ const res = await (0, cross_fetch_1.default)(`${this.baseUrl}/v1/chat/completions`, {
41
+ method: 'POST',
42
+ headers: {
43
+ 'Content-Type': 'application/json',
44
+ 'Authorization': `Bearer ${this.apiKey}`,
45
+ },
46
+ body: JSON.stringify(body),
47
+ });
48
+ if (!res.ok) {
49
+ const text = await res.text().catch(() => '');
50
+ throw new Error(`OpenAI error ${res.status}: ${text}`);
51
+ }
52
+ if (onChunk)
53
+ return this._stream(res, onChunk);
54
+ const data = await res.json();
55
+ return data.choices[0]?.message?.content ?? '';
56
+ }
57
+ _buildMessages(input) {
58
+ // OpenAI supports system role natively in messages[]
59
+ const msgs = [];
60
+ if (input.system)
61
+ msgs.push({ role: 'system', content: input.system });
62
+ if (input.messages) {
63
+ const filtered = input.system
64
+ ? input.messages.filter((m) => m.role !== 'system')
65
+ : input.messages;
66
+ msgs.push(...filtered);
67
+ }
68
+ else if (input.prompt) {
69
+ msgs.push({ role: 'user', content: input.prompt });
70
+ }
71
+ return msgs;
72
+ }
73
+ async _stream(res, onChunk) {
74
+ const reader = res.body?.getReader();
75
+ if (!reader)
76
+ throw new Error('No response body');
77
+ const decoder = new TextDecoder();
78
+ let buffer = '';
79
+ while (true) {
80
+ const { done, value } = await reader.read();
81
+ if (done)
82
+ break;
83
+ buffer += decoder.decode(value, { stream: true });
84
+ const lines = buffer.split('\n');
85
+ buffer = lines.pop() ?? '';
86
+ for (const line of lines) {
87
+ if (!line.startsWith('data: '))
88
+ continue;
89
+ const payload = line.slice(6).trim();
90
+ if (payload === '[DONE]')
91
+ return;
92
+ try {
93
+ const chunk = JSON.parse(payload);
94
+ const content = chunk.choices[0]?.delta?.content;
95
+ if (content)
96
+ onChunk(content);
97
+ }
98
+ catch { /* malformed β€” skip */ }
99
+ }
100
+ }
101
+ }
102
+ }
103
+ exports.OpenAIAdapter = OpenAIAdapter;
104
+ exports.default = OpenAIAdapter;
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "@agentic-kit/openai",
3
+ "version": "0.1.0",
4
+ "author": "Dan Lynch <pyramation@gmail.com>",
5
+ "description": "OpenAI (and OpenAI-compatible) adapter for agentic-kit",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "homepage": "https://github.com/constructive-io/agentic-kit",
10
+ "license": "SEE LICENSE IN LICENSE",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "directory": "dist"
14
+ },
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "https://github.com/constructive-io/agentic-kit"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/constructive-io/agentic-kit/issues"
21
+ },
22
+ "scripts": {
23
+ "clean": "makage clean",
24
+ "build": "makage build",
25
+ "build:dev": "makage build --dev",
26
+ "lint": "eslint . --fix",
27
+ "test": "jest",
28
+ "test:watch": "jest --watch"
29
+ },
30
+ "keywords": [],
31
+ "dependencies": {
32
+ "cross-fetch": "^4.1.0"
33
+ }
34
+ }