@aigne/transport 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.
Files changed (37) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE.md +93 -0
  3. package/README.md +162 -0
  4. package/README.zh.md +162 -0
  5. package/lib/cjs/http-client/client.d.ts +97 -0
  6. package/lib/cjs/http-client/client.js +87 -0
  7. package/lib/cjs/http-client/index.d.ts +1 -0
  8. package/lib/cjs/http-client/index.js +17 -0
  9. package/lib/cjs/http-server/error.d.ts +15 -0
  10. package/lib/cjs/http-server/error.js +22 -0
  11. package/lib/cjs/http-server/index.d.ts +2 -0
  12. package/lib/cjs/http-server/index.js +18 -0
  13. package/lib/cjs/http-server/server.d.ts +135 -0
  14. package/lib/cjs/http-server/server.js +187 -0
  15. package/lib/cjs/index.d.ts +1 -0
  16. package/lib/cjs/index.js +2 -0
  17. package/lib/cjs/package.json +1 -0
  18. package/lib/dts/http-client/client.d.ts +97 -0
  19. package/lib/dts/http-client/index.d.ts +1 -0
  20. package/lib/dts/http-server/error.d.ts +15 -0
  21. package/lib/dts/http-server/index.d.ts +2 -0
  22. package/lib/dts/http-server/server.d.ts +135 -0
  23. package/lib/dts/index.d.ts +1 -0
  24. package/lib/esm/http-client/client.d.ts +97 -0
  25. package/lib/esm/http-client/client.js +83 -0
  26. package/lib/esm/http-client/index.d.ts +1 -0
  27. package/lib/esm/http-client/index.js +1 -0
  28. package/lib/esm/http-server/error.d.ts +15 -0
  29. package/lib/esm/http-server/error.js +18 -0
  30. package/lib/esm/http-server/index.d.ts +2 -0
  31. package/lib/esm/http-server/index.js +2 -0
  32. package/lib/esm/http-server/server.d.ts +135 -0
  33. package/lib/esm/http-server/server.js +180 -0
  34. package/lib/esm/index.d.ts +1 -0
  35. package/lib/esm/index.js +1 -0
  36. package/lib/esm/package.json +1 -0
  37. package/package.json +66 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,23 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0](https://github.com/AIGNE-io/aigne-framework/compare/transport-v0.0.1...transport-v0.1.0) (2025-05-23)
4
+
5
+
6
+ ### Features
7
+
8
+ * **models:** publish model adapters as standalone packages ([#126](https://github.com/AIGNE-io/aigne-framework/issues/126)) ([588b8ae](https://github.com/AIGNE-io/aigne-framework/commit/588b8aea6abcee5fa87def1358bf51f84021c6ef))
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * automatically convert tool names to a valid format ([#128](https://github.com/AIGNE-io/aigne-framework/issues/128)) ([e9ee91d](https://github.com/AIGNE-io/aigne-framework/commit/e9ee91d9d782fa19000adb4cf95b9d65196ab651))
14
+
15
+
16
+ ### Dependencies
17
+
18
+ * The following workspace dependencies were updated
19
+ * dependencies
20
+ * @aigne/openai bumped to 0.1.0
21
+ * devDependencies
22
+ * @aigne/core bumped to 1.16.0
23
+ * @aigne/test-utils bumped to 0.3.0
package/LICENSE.md ADDED
@@ -0,0 +1,93 @@
1
+ Elastic License 2.0
2
+
3
+ URL: https://www.elastic.co/licensing/elastic-license
4
+
5
+ ## Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ ## Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
12
+ non-sublicensable, non-transferable license to use, copy, distribute, make
13
+ available, and prepare derivative works of the software, in each case subject to
14
+ the limitations and conditions below.
15
+
16
+ ## Limitations
17
+
18
+ You may not provide the software to third parties as a hosted or managed
19
+ service, where the service provides users with access to any substantial set of
20
+ the features or functionality of the software.
21
+
22
+ You may not move, change, disable, or circumvent the license key functionality
23
+ in the software, and you may not remove or obscure any functionality in the
24
+ software that is protected by the license key.
25
+
26
+ You may not alter, remove, or obscure any licensing, copyright, or other notices
27
+ of the licensor in the software. Any use of the licensor’s trademarks is subject
28
+ to applicable law.
29
+
30
+ ## Patents
31
+
32
+ The licensor grants you a license, under any patent claims the licensor can
33
+ license, or becomes able to license, to make, have made, use, sell, offer for
34
+ sale, import and have imported the software, in each case subject to the
35
+ limitations and conditions in this license. This license does not cover any
36
+ patent claims that you cause to be infringed by modifications or additions to
37
+ the software. If you or your company make any written claim that the software
38
+ infringes or contributes to infringement of any patent, your patent license for
39
+ the software granted under these terms ends immediately. If your company makes
40
+ such a claim, your patent license ends immediately for work on behalf of your
41
+ company.
42
+
43
+ ## Notices
44
+
45
+ You must ensure that anyone who gets a copy of any part of the software from you
46
+ also gets a copy of these terms.
47
+
48
+ If you modify the software, you must include in any modified copies of the
49
+ software prominent notices stating that you have modified the software.
50
+
51
+ ## No Other Rights
52
+
53
+ These terms do not imply any licenses other than those expressly granted in
54
+ these terms.
55
+
56
+ ## Termination
57
+
58
+ If you use the software in violation of these terms, such use is not licensed,
59
+ and your licenses will automatically terminate. If the licensor provides you
60
+ with a notice of your violation, and you cease all violation of this license no
61
+ later than 30 days after you receive that notice, your licenses will be
62
+ reinstated retroactively. However, if you violate these terms after such
63
+ reinstatement, any additional violation of these terms will cause your licenses
64
+ to terminate automatically and permanently.
65
+
66
+ ## No Liability
67
+
68
+ *As far as the law allows, the software comes as is, without any warranty or
69
+ condition, and the licensor will not be liable to you for any damages arising
70
+ out of these terms or the use or nature of the software, under any kind of
71
+ legal claim.*
72
+
73
+ ## Definitions
74
+
75
+ The **licensor** is the entity offering these terms, and the **software** is the
76
+ software the licensor makes available under these terms, including any portion
77
+ of it.
78
+
79
+ **you** refers to the individual or entity agreeing to these terms.
80
+
81
+ **your company** is any legal entity, sole proprietorship, or other kind of
82
+ organization that you work for, plus all organizations that have control over,
83
+ are under the control of, or are under common control with that
84
+ organization. **control** means ownership of substantially all the assets of an
85
+ entity, or the power to direct its management and policies by vote, contract, or
86
+ otherwise. Control can be direct or indirect.
87
+
88
+ **your licenses** are all the licenses granted to you for the software under
89
+ these terms.
90
+
91
+ **use** means anything you do with the software requiring one of your licenses.
92
+
93
+ **trademark** means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,162 @@
1
+ # @aigne/transport
2
+
3
+ [![GitHub star chart](https://img.shields.io/github/stars/AIGNE-io/aigne-framework?style=flat-square)](https://star-history.com/#AIGNE-io/aigne-framework)
4
+ [![Open Issues](https://img.shields.io/github/issues-raw/AIGNE-io/aigne-framework?style=flat-square)](https://github.com/AIGNE-io/aigne-framework/issues)
5
+ [![codecov](https://codecov.io/gh/AIGNE-io/aigne-framework/graph/badge.svg?token=DO07834RQL)](https://codecov.io/gh/AIGNE-io/aigne-framework)
6
+ [![NPM Version](https://img.shields.io/npm/v/@aigne/transport)](https://www.npmjs.com/package/@aigne/transport)
7
+ [![Elastic-2.0 licensed](https://img.shields.io/npm/l/@aigne/transport)](https://github.com/AIGNE-io/aigne-framework/blob/main/LICENSE.md)
8
+
9
+ **English** | [中文](README.zh.md)
10
+
11
+ AIGNE Transport SDK providing HTTP client and server implementations for communication between AIGNE components within the [AIGNE Framework](https://github.com/AIGNE-io/aigne-framework).
12
+
13
+ ## Introduction
14
+
15
+ `@aigne/transport` provides a robust communication layer for AIGNE components, enabling seamless interaction between different parts of your AI applications. This package offers both HTTP client and server implementations that adhere to a consistent protocol, making it easy to build distributed AI systems with the AIGNE Framework.
16
+
17
+ ## Features
18
+
19
+ * **HTTP Client Implementation**: Easy-to-use client for communicating with AIGNE servers
20
+ * **HTTP Server Implementation**: Flexible server implementation that integrates with popular Node.js frameworks
21
+ * **Framework Agnostic**: Supports Express, Hono, and other Node.js HTTP frameworks
22
+ * **Streaming Support**: First-class support for streaming responses
23
+ * **Type Safety**: Comprehensive TypeScript typings for all APIs
24
+ * **Error Handling**: Robust error handling with detailed error messages
25
+ * **Middleware Support**: Compatible with common HTTP middleware like compression
26
+
27
+ ## Installation
28
+
29
+ ### Using npm
30
+
31
+ ```bash
32
+ npm install @aigne/transport @aigne/core
33
+ ```
34
+
35
+ ### Using yarn
36
+
37
+ ```bash
38
+ yarn add @aigne/transport @aigne/core
39
+ ```
40
+
41
+ ### Using pnpm
42
+
43
+ ```bash
44
+ pnpm add @aigne/transport @aigne/core
45
+ ```
46
+
47
+ ## Basic Usage
48
+
49
+ ### Server Usage
50
+
51
+ You can use the AIGNE HTTP server with either Express or Hono frameworks.
52
+
53
+ #### Express Example
54
+
55
+ ```typescript file="test/http-server/http-server.test.ts" region="example-aigne-server-express"
56
+ import { AIAgent, AIGNE } from "@aigne/core";
57
+ import { AIGNEHTTPClient } from "@aigne/transport/http-client/index.js";
58
+ import { AIGNEHTTPServer } from "@aigne/transport/http-server/index.js";
59
+ import express from "express";
60
+ import { OpenAIChatModel } from "../_mocks_/mock-models.js";
61
+
62
+ const model = new OpenAIChatModel();
63
+
64
+ const chat = AIAgent.from({
65
+ name: "chat",
66
+ });
67
+
68
+ // AIGNE: Main execution engine of AIGNE Framework.
69
+ const aigne = new AIGNE({ model, agents: [chat] });
70
+
71
+ // Create an AIGNEServer instance
72
+ const aigneServer = new AIGNEHTTPServer(aigne);
73
+
74
+ // Setup the server to handle incoming requests
75
+ const server = express();
76
+ server.post("/aigne/invoke", async (req, res) => {
77
+ await aigneServer.invoke(req, res);
78
+ });
79
+ const httpServer = server.listen(port);
80
+
81
+ // Create an AIGNEClient instance
82
+ const client = new AIGNEHTTPClient({ url });
83
+
84
+ // Invoke the agent by client
85
+ const response = await client.invoke("chat", { $message: "hello" });
86
+
87
+ console.log(response); // Output: {$message: "Hello world!"}
88
+ ```
89
+
90
+ #### Hono Example
91
+
92
+ ```typescript file="test/http-server/http-server.test.ts" region="example-aigne-server-hono"
93
+ import { AIAgent, AIGNE } from "@aigne/core";
94
+ import { AIGNEHTTPClient } from "@aigne/transport/http-client/index.js";
95
+ import { AIGNEHTTPServer } from "@aigne/transport/http-server/index.js";
96
+ import { serve } from "bun";
97
+ import { Hono } from "hono";
98
+ import { OpenAIChatModel } from "../_mocks_/mock-models.js";
99
+
100
+ const model = new OpenAIChatModel();
101
+
102
+ const chat = AIAgent.from({
103
+ name: "chat",
104
+ });
105
+
106
+ // AIGNE: Main execution engine of AIGNE Framework.
107
+ const aigne = new AIGNE({ model, agents: [chat] });
108
+
109
+ // Create an AIGNEServer instance
110
+ const aigneServer = new AIGNEHTTPServer(aigne);
111
+
112
+ // Setup the server to handle incoming requests
113
+ const honoApp = new Hono();
114
+ honoApp.post("/aigne/invoke", async (c) => {
115
+ return aigneServer.invoke(c.req.raw);
116
+ });
117
+ const server = serve({ port, fetch: honoApp.fetch });
118
+
119
+ // Create an AIGNEClient instance
120
+ const client = new AIGNEHTTPClient({ url });
121
+
122
+ // Invoke the agent by client
123
+ const response = await client.invoke("chat", { $message: "hello" });
124
+ console.log(response); // Output: {$message: "Hello world!"}
125
+ ```
126
+
127
+ ### HTTP Client
128
+
129
+ ```typescript file="test/http-client/http-client.test.ts" region="example-aigne-client-simple"
130
+ import { AIGNEHTTPClient } from "@aigne/transport/http-client/index.js";
131
+
132
+ const client = new AIGNEHTTPClient({ url });
133
+
134
+ const response = await client.invoke("chat", { $message: "hello" });
135
+
136
+ console.log(response); // Output: {$message: "Hello world!"}
137
+ ```
138
+
139
+ ### Streaming Responses
140
+
141
+ ```typescript file="test/http-client/http-client.test.ts" region="example-aigne-client-streaming"
142
+ import { AIGNEHTTPClient } from "@aigne/transport/http-client/index.js";
143
+
144
+ const client = new AIGNEHTTPClient({ url });
145
+
146
+ const stream = await client.invoke(
147
+ "chat",
148
+ { $message: "hello" },
149
+ { streaming: true },
150
+ );
151
+
152
+ let text = "";
153
+ for await (const chunk of stream) {
154
+ if (chunk.delta.text?.$message) text += chunk.delta.text.$message;
155
+ }
156
+
157
+ console.log(text); // Output: "Hello world!"
158
+ ```
159
+
160
+ ## License
161
+
162
+ Elastic-2.0
package/README.zh.md ADDED
@@ -0,0 +1,162 @@
1
+ # @aigne/transport
2
+
3
+ [![GitHub star chart](https://img.shields.io/github/stars/AIGNE-io/aigne-framework?style=flat-square)](https://star-history.com/#AIGNE-io/aigne-framework)
4
+ [![Open Issues](https://img.shields.io/github/issues-raw/AIGNE-io/aigne-framework?style=flat-square)](https://github.com/AIGNE-io/aigne-framework/issues)
5
+ [![codecov](https://codecov.io/gh/AIGNE-io/aigne-framework/graph/badge.svg?token=DO07834RQL)](https://codecov.io/gh/AIGNE-io/aigne-framework)
6
+ [![NPM Version](https://img.shields.io/npm/v/@aigne/transport)](https://www.npmjs.com/package/@aigne/transport)
7
+ [![Elastic-2.0 licensed](https://img.shields.io/npm/l/@aigne/transport)](https://github.com/AIGNE-io/aigne-framework/blob/main/LICENSE.md)
8
+
9
+ [English](README.md) | **中文**
10
+
11
+ AIGNE Transport SDK,为 [AIGNE 框架](https://github.com/AIGNE-io/aigne-framework) 中的 AIGNE 组件之间的通信提供 HTTP 客户端和服务器实现。
12
+
13
+ ## 简介
14
+
15
+ `@aigne/transport` 为 AIGNE 组件提供了一个强大的通信层,使 AI 应用程序的不同部分之间能够无缝交互。该包提供了遵循一致协议的 HTTP 客户端和服务器实现,使用 AIGNE 框架构建分布式 AI 系统变得简单。
16
+
17
+ ## 特性
18
+
19
+ * **HTTP 客户端实现**:易于使用的客户端,用于与 AIGNE 服务器通信
20
+ * **HTTP 服务器实现**:灵活的服务器实现,可与流行的 Node.js 框架集成
21
+ * **框架无关**:支持 Express、Hono 和其他 Node.js HTTP 框架
22
+ * **流式响应支持**:对流式响应的一流支持
23
+ * **类型安全**:为所有 API 提供全面的 TypeScript 类型定义
24
+ * **错误处理**:健壮的错误处理机制,提供详细的错误信息
25
+ * **中间件支持**:兼容常见的 HTTP 中间件,如压缩中间件
26
+
27
+ ## 安装
28
+
29
+ ### 使用 npm
30
+
31
+ ```bash
32
+ npm install @aigne/transport @aigne/core
33
+ ```
34
+
35
+ ### 使用 yarn
36
+
37
+ ```bash
38
+ yarn add @aigne/transport @aigne/core
39
+ ```
40
+
41
+ ### 使用 pnpm
42
+
43
+ ```bash
44
+ pnpm add @aigne/transport @aigne/core
45
+ ```
46
+
47
+ ## 基本用法
48
+
49
+ ### 服务端用法
50
+
51
+ AIGNE HTTP 服务器可用于 Express 或 Hono 框架。
52
+
53
+ #### Express 示例
54
+
55
+ ```typescript file="test/http-server/http-server.test.ts" region="example-aigne-server-express"
56
+ import { AIAgent, AIGNE } from "@aigne/core";
57
+ import { AIGNEHTTPClient } from "@aigne/transport/http-client/index.js";
58
+ import { AIGNEHTTPServer } from "@aigne/transport/http-server/index.js";
59
+ import express from "express";
60
+ import { OpenAIChatModel } from "../_mocks_/mock-models.js";
61
+
62
+ const model = new OpenAIChatModel();
63
+
64
+ const chat = AIAgent.from({
65
+ name: "chat",
66
+ });
67
+
68
+ // AIGNE: Main execution engine of AIGNE Framework.
69
+ const aigne = new AIGNE({ model, agents: [chat] });
70
+
71
+ // Create an AIGNEServer instance
72
+ const aigneServer = new AIGNEHTTPServer(aigne);
73
+
74
+ // Setup the server to handle incoming requests
75
+ const server = express();
76
+ server.post("/aigne/invoke", async (req, res) => {
77
+ await aigneServer.invoke(req, res);
78
+ });
79
+ const httpServer = server.listen(port);
80
+
81
+ // Create an AIGNEClient instance
82
+ const client = new AIGNEHTTPClient({ url });
83
+
84
+ // Invoke the agent by client
85
+ const response = await client.invoke("chat", { $message: "hello" });
86
+
87
+ console.log(response); // Output: {$message: "Hello world!"}
88
+ ```
89
+
90
+ #### Hono 示例
91
+
92
+ ```typescript file="test/http-server/http-server.test.ts" region="example-aigne-server-hono"
93
+ import { AIAgent, AIGNE } from "@aigne/core";
94
+ import { AIGNEHTTPClient } from "@aigne/transport/http-client/index.js";
95
+ import { AIGNEHTTPServer } from "@aigne/transport/http-server/index.js";
96
+ import { serve } from "bun";
97
+ import { Hono } from "hono";
98
+ import { OpenAIChatModel } from "../_mocks_/mock-models.js";
99
+
100
+ const model = new OpenAIChatModel();
101
+
102
+ const chat = AIAgent.from({
103
+ name: "chat",
104
+ });
105
+
106
+ // AIGNE: Main execution engine of AIGNE Framework.
107
+ const aigne = new AIGNE({ model, agents: [chat] });
108
+
109
+ // Create an AIGNEServer instance
110
+ const aigneServer = new AIGNEHTTPServer(aigne);
111
+
112
+ // Setup the server to handle incoming requests
113
+ const honoApp = new Hono();
114
+ honoApp.post("/aigne/invoke", async (c) => {
115
+ return aigneServer.invoke(c.req.raw);
116
+ });
117
+ const server = serve({ port, fetch: honoApp.fetch });
118
+
119
+ // Create an AIGNEClient instance
120
+ const client = new AIGNEHTTPClient({ url });
121
+
122
+ // Invoke the agent by client
123
+ const response = await client.invoke("chat", { $message: "hello" });
124
+ console.log(response); // Output: {$message: "Hello world!"}
125
+ ```
126
+
127
+ ### HTTP 客户端
128
+
129
+ ```typescript file="test/http-client/http-client.test.ts" region="example-aigne-client-simple"
130
+ import { AIGNEHTTPClient } from "@aigne/transport/http-client/index.js";
131
+
132
+ const client = new AIGNEHTTPClient({ url });
133
+
134
+ const response = await client.invoke("chat", { $message: "hello" });
135
+
136
+ console.log(response); // Output: {$message: "Hello world!"}
137
+ ```
138
+
139
+ ### 流式响应
140
+
141
+ ```typescript file="test/http-client/http-client.test.ts" region="example-aigne-client-streaming"
142
+ import { AIGNEHTTPClient } from "@aigne/transport/http-client/index.js";
143
+
144
+ const client = new AIGNEHTTPClient({ url });
145
+
146
+ const stream = await client.invoke(
147
+ "chat",
148
+ { $message: "hello" },
149
+ { streaming: true },
150
+ );
151
+
152
+ let text = "";
153
+ for await (const chunk of stream) {
154
+ if (chunk.delta.text?.$message) text += chunk.delta.text.$message;
155
+ }
156
+
157
+ console.log(text); // Output: "Hello world!"
158
+ ```
159
+
160
+ ## 许可证
161
+
162
+ Elastic-2.0
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Client module used to interact with the AIGNE framework.
3
+ */
4
+ import type { AgentInvokeOptions, AgentResponse, AgentResponseStream, Message } from "@aigne/core";
5
+ /**
6
+ * Configuration options for the AIGNEHTTPClient.
7
+ */
8
+ export interface AIGNEHTTPClientOptions {
9
+ /**
10
+ * The URL of the AIGNE server to connect to.
11
+ * This should point to the base endpoint where the AIGNEServer is hosted.
12
+ */
13
+ url: string;
14
+ }
15
+ /**
16
+ * Options for invoking an agent through the AIGNEHTTPClient.
17
+ * Extends the standard AgentInvokeOptions with client-specific options.
18
+ */
19
+ export interface AIGNEHTTPClientInvokeOptions extends AgentInvokeOptions {
20
+ /**
21
+ * Additional fetch API options to customize the HTTP request.
22
+ * These options will be merged with the default options used by the client.
23
+ */
24
+ fetchOptions?: Partial<RequestInit>;
25
+ }
26
+ /**
27
+ * Http client for interacting with a remote AIGNE server.
28
+ * AIGNEHTTPClient provides a client-side interface that matches the AIGNE API,
29
+ * allowing applications to invoke agents and receive responses from a remote AIGNE instance.
30
+ *
31
+ * @example
32
+ * Here's a simple example of how to use AIGNEClient:
33
+ * {@includeCode ../../test/http-client/http-client.test.ts#example-aigne-client-simple}
34
+ *
35
+ * @example
36
+ * Here's an example of how to use AIGNEClient with streaming response:
37
+ * {@includeCode ../../test/http-client/http-client.test.ts#example-aigne-client-streaming}
38
+ */
39
+ export declare class AIGNEHTTPClient {
40
+ options: AIGNEHTTPClientOptions;
41
+ /**
42
+ * Creates a new AIGNEClient instance.
43
+ *
44
+ * @param options - Configuration options for connecting to the AIGNE server
45
+ */
46
+ constructor(options: AIGNEHTTPClientOptions);
47
+ /**
48
+ * Invokes an agent in non-streaming mode and returns the complete response.
49
+ *
50
+ * @param agent - Name of the agent to invoke
51
+ * @param input - Input message for the agent
52
+ * @param options - Options with streaming mode explicitly set to false or omitted
53
+ * @returns The complete agent response
54
+ *
55
+ * @example
56
+ * Here's a simple example of how to use AIGNEClient:
57
+ * {@includeCode ../../test/http-client/http-client.test.ts#example-aigne-client-simple}
58
+ */
59
+ invoke<I extends Message, O extends Message>(agent: string, input: string | I, options?: AIGNEHTTPClientInvokeOptions & {
60
+ streaming?: false;
61
+ }): Promise<O>;
62
+ /**
63
+ * Invokes an agent with streaming mode enabled and returns a stream of response chunks.
64
+ *
65
+ * @param agent - Name of the agent to invoke
66
+ * @param input - Input message for the agent
67
+ * @param options - Options with streaming mode explicitly set to true
68
+ * @returns A stream of agent response chunks
69
+ *
70
+ * @example
71
+ * Here's an example of how to use AIGNEClient with streaming response:
72
+ * {@includeCode ../../test/http-client/http-client.test.ts#example-aigne-client-streaming}
73
+ */
74
+ invoke<I extends Message, O extends Message>(agent: string, input: string | I, options: AIGNEHTTPClientInvokeOptions & {
75
+ streaming: true;
76
+ }): Promise<AgentResponseStream<O>>;
77
+ /**
78
+ * Invokes an agent with the given input and options.
79
+ *
80
+ * @param agent - Name of the agent to invoke
81
+ * @param input - Input message for the agent
82
+ * @param options - Options for the invocation
83
+ * @returns Either a complete response or a response stream depending on the streaming option
84
+ */
85
+ invoke<I extends Message, O extends Message>(agent: string, input: string | I, options?: AIGNEHTTPClientInvokeOptions): Promise<AgentResponse<O>>;
86
+ /**
87
+ * Enhanced fetch method that handles error responses from the AIGNE server.
88
+ * This method wraps the standard fetch API to provide better error handling and reporting.
89
+ *
90
+ * @param args - Standard fetch API arguments (url and options)
91
+ * @returns A Response object if the request was successful
92
+ * @throws Error with detailed information if the request failed
93
+ *
94
+ * @private
95
+ */
96
+ fetch(...args: Parameters<typeof globalThis.fetch>): Promise<Response>;
97
+ }
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ /**
3
+ * Client module used to interact with the AIGNE framework.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AIGNEHTTPClient = void 0;
7
+ const event_stream_js_1 = require("@aigne/core/utils/event-stream.js");
8
+ const type_utils_js_1 = require("@aigne/core/utils/type-utils.js");
9
+ /**
10
+ * Http client for interacting with a remote AIGNE server.
11
+ * AIGNEHTTPClient provides a client-side interface that matches the AIGNE API,
12
+ * allowing applications to invoke agents and receive responses from a remote AIGNE instance.
13
+ *
14
+ * @example
15
+ * Here's a simple example of how to use AIGNEClient:
16
+ * {@includeCode ../../test/http-client/http-client.test.ts#example-aigne-client-simple}
17
+ *
18
+ * @example
19
+ * Here's an example of how to use AIGNEClient with streaming response:
20
+ * {@includeCode ../../test/http-client/http-client.test.ts#example-aigne-client-streaming}
21
+ */
22
+ class AIGNEHTTPClient {
23
+ options;
24
+ /**
25
+ * Creates a new AIGNEClient instance.
26
+ *
27
+ * @param options - Configuration options for connecting to the AIGNE server
28
+ */
29
+ constructor(options) {
30
+ this.options = options;
31
+ }
32
+ async invoke(agent, input, options) {
33
+ // Send the agent invocation request to the AIGNE server
34
+ const response = await this.fetch(this.options.url, {
35
+ ...options?.fetchOptions,
36
+ method: "POST",
37
+ headers: {
38
+ "Content-Type": "application/json",
39
+ ...options?.fetchOptions?.headers,
40
+ },
41
+ body: JSON.stringify({ agent, input, options }),
42
+ });
43
+ // For non-streaming responses, simply parse the JSON response and return it
44
+ if (!options?.streaming) {
45
+ return await response.json();
46
+ }
47
+ // For streaming responses, set up the streaming pipeline
48
+ const stream = response.body;
49
+ if (!stream)
50
+ throw new Error("Response body is not a stream");
51
+ // Process the stream through a series of transforms:
52
+ // 1. Convert bytes to text
53
+ // 2. Parse SSE format into structured events
54
+ // 3. Convert events into a standardized agent response stream
55
+ return stream
56
+ .pipeThrough(new TextDecoderStream())
57
+ .pipeThrough(new event_stream_js_1.EventStreamParser())
58
+ .pipeThrough(new event_stream_js_1.AgentResponseStreamParser());
59
+ }
60
+ /**
61
+ * Enhanced fetch method that handles error responses from the AIGNE server.
62
+ * This method wraps the standard fetch API to provide better error handling and reporting.
63
+ *
64
+ * @param args - Standard fetch API arguments (url and options)
65
+ * @returns A Response object if the request was successful
66
+ * @throws Error with detailed information if the request failed
67
+ *
68
+ * @private
69
+ */
70
+ async fetch(...args) {
71
+ const result = await globalThis.fetch(...args);
72
+ if (!result.ok) {
73
+ let message;
74
+ try {
75
+ const text = await result.text();
76
+ const json = (0, type_utils_js_1.tryOrThrow)(() => JSON.parse(text));
77
+ message = json?.error?.message || text;
78
+ }
79
+ catch {
80
+ // ignore
81
+ }
82
+ throw new Error(`Failed to fetch url ${args[0]} with status ${result.status}: ${message}`);
83
+ }
84
+ return result;
85
+ }
86
+ }
87
+ exports.AIGNEHTTPClient = AIGNEHTTPClient;
@@ -0,0 +1 @@
1
+ export * from "./client.js";
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./client.js"), exports);
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Custom error class for AIGNEServer HTTP-related errors.
3
+ * Extends the standard Error class with an HTTP status code property.
4
+ * This allows error responses to include appropriate HTTP status codes.
5
+ */
6
+ export declare class ServerError extends Error {
7
+ status: number;
8
+ /**
9
+ * Creates a new ServerError instance.
10
+ *
11
+ * @param status - The HTTP status code for this error (e.g., 400, 404, 500)
12
+ * @param message - The error message describing what went wrong
13
+ */
14
+ constructor(status: number, message: string);
15
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ServerError = void 0;
4
+ /**
5
+ * Custom error class for AIGNEServer HTTP-related errors.
6
+ * Extends the standard Error class with an HTTP status code property.
7
+ * This allows error responses to include appropriate HTTP status codes.
8
+ */
9
+ class ServerError extends Error {
10
+ status;
11
+ /**
12
+ * Creates a new ServerError instance.
13
+ *
14
+ * @param status - The HTTP status code for this error (e.g., 400, 404, 500)
15
+ * @param message - The error message describing what went wrong
16
+ */
17
+ constructor(status, message) {
18
+ super(message);
19
+ this.status = status;
20
+ }
21
+ }
22
+ exports.ServerError = ServerError;