@tinyweb_dev/agent-framework-tool 0.1.0 → 0.3.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/dist/builtins.cjs +712 -0
- package/dist/builtins.cjs.map +1 -0
- package/dist/builtins.d.ts +52 -0
- package/dist/builtins.d.ts.map +1 -0
- package/dist/builtins.js +710 -0
- package/dist/builtins.js.map +1 -0
- package/dist/display_response.cjs +51 -0
- package/dist/display_response.cjs.map +1 -0
- package/dist/display_response.d.ts +36 -0
- package/dist/display_response.d.ts.map +1 -0
- package/dist/display_response.js +49 -0
- package/dist/display_response.js.map +1 -0
- package/dist/file_read.cjs +28 -0
- package/dist/file_read.cjs.map +1 -0
- package/dist/file_read.d.ts +14 -0
- package/dist/file_read.d.ts.map +1 -0
- package/dist/file_read.js +26 -0
- package/dist/file_read.js.map +1 -0
- package/dist/file_write.cjs +30 -0
- package/dist/file_write.cjs.map +1 -0
- package/dist/file_write.d.ts +16 -0
- package/dist/file_write.d.ts.map +1 -0
- package/dist/file_write.js +28 -0
- package/dist/file_write.js.map +1 -0
- package/dist/image_describe.cjs +69 -0
- package/dist/image_describe.cjs.map +1 -0
- package/dist/image_describe.d.ts +15 -0
- package/dist/image_describe.d.ts.map +1 -0
- package/dist/image_describe.js +67 -0
- package/dist/image_describe.js.map +1 -0
- package/dist/image_edit.cjs +87 -0
- package/dist/image_edit.cjs.map +1 -0
- package/dist/image_edit.d.ts +20 -0
- package/dist/image_edit.d.ts.map +1 -0
- package/dist/image_edit.js +85 -0
- package/dist/image_edit.js.map +1 -0
- package/dist/image_generate.cjs +112 -0
- package/dist/image_generate.cjs.map +1 -0
- package/dist/image_generate.d.ts +21 -0
- package/dist/image_generate.d.ts.map +1 -0
- package/dist/image_generate.js +110 -0
- package/dist/image_generate.js.map +1 -0
- package/dist/index.cjs +1098 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1068 -0
- package/dist/index.js.map +1 -0
- package/dist/info/crypto.cjs +78 -0
- package/dist/info/crypto.cjs.map +1 -0
- package/dist/info/crypto.d.ts +34 -0
- package/dist/info/crypto.d.ts.map +1 -0
- package/dist/info/crypto.js +76 -0
- package/dist/info/crypto.js.map +1 -0
- package/dist/info/time.cjs +60 -0
- package/dist/info/time.cjs.map +1 -0
- package/dist/info/time.d.ts +31 -0
- package/dist/info/time.d.ts.map +1 -0
- package/dist/info/time.js +58 -0
- package/dist/info/time.js.map +1 -0
- package/dist/info/weather.cjs +105 -0
- package/dist/info/weather.cjs.map +1 -0
- package/dist/info/weather.d.ts +41 -0
- package/dist/info/weather.d.ts.map +1 -0
- package/dist/info/weather.js +103 -0
- package/dist/info/weather.js.map +1 -0
- package/dist/search/perplexity.cjs +98 -0
- package/dist/search/perplexity.cjs.map +1 -0
- package/dist/search/perplexity.d.ts +49 -0
- package/dist/search/perplexity.d.ts.map +1 -0
- package/dist/search/perplexity.js +96 -0
- package/dist/search/perplexity.js.map +1 -0
- package/dist/shared/html.cjs +57 -0
- package/dist/shared/html.cjs.map +1 -0
- package/dist/shared/html.d.ts +37 -0
- package/dist/shared/html.d.ts.map +1 -0
- package/dist/shared/html.js +52 -0
- package/dist/shared/html.js.map +1 -0
- package/dist/shared/http.cjs +48 -0
- package/dist/shared/http.cjs.map +1 -0
- package/dist/shared/http.d.ts +11 -0
- package/dist/shared/http.d.ts.map +1 -0
- package/dist/shared/http.js +42 -0
- package/dist/shared/http.js.map +1 -0
- package/dist/shared/s3.cjs +98 -0
- package/dist/shared/s3.cjs.map +1 -0
- package/dist/shared/s3.d.ts +35 -0
- package/dist/shared/s3.d.ts.map +1 -0
- package/dist/shared/s3.js +96 -0
- package/dist/shared/s3.js.map +1 -0
- package/dist/shared/storage.cjs +74 -0
- package/dist/shared/storage.cjs.map +1 -0
- package/dist/shared/storage.d.ts +17 -0
- package/dist/shared/storage.d.ts.map +1 -0
- package/dist/shared/storage.js +70 -0
- package/dist/shared/storage.js.map +1 -0
- package/dist/vn/gold.cjs +198 -0
- package/dist/vn/gold.cjs.map +1 -0
- package/dist/vn/gold.d.ts +36 -0
- package/dist/vn/gold.d.ts.map +1 -0
- package/dist/vn/gold.js +196 -0
- package/dist/vn/gold.js.map +1 -0
- package/dist/vn/lottery.cjs +126 -0
- package/dist/vn/lottery.cjs.map +1 -0
- package/dist/vn/lottery.d.ts +31 -0
- package/dist/vn/lottery.d.ts.map +1 -0
- package/dist/vn/lottery.js +124 -0
- package/dist/vn/lottery.js.map +1 -0
- package/dist/web_fetch.cjs +65 -0
- package/dist/web_fetch.cjs.map +1 -0
- package/dist/web_fetch.d.ts +16 -0
- package/dist/web_fetch.d.ts.map +1 -0
- package/dist/web_fetch.js +63 -0
- package/dist/web_fetch.js.map +1 -0
- package/dist/web_search.cjs +98 -0
- package/dist/web_search.cjs.map +1 -0
- package/dist/web_search.d.ts +19 -0
- package/dist/web_search.d.ts.map +1 -0
- package/dist/web_search.js +96 -0
- package/dist/web_search.js.map +1 -0
- package/package.json +109 -30
- package/src/builtins.ts +0 -78
- package/src/display_response.ts +0 -79
- package/src/file_read.ts +0 -31
- package/src/file_write.ts +0 -33
- package/src/image_describe.ts +0 -58
- package/src/image_edit.ts +0 -74
- package/src/image_generate.ts +0 -102
- package/src/index.ts +0 -47
- package/src/info/crypto.ts +0 -79
- package/src/info/time.ts +0 -83
- package/src/info/weather.ts +0 -134
- package/src/search/perplexity.ts +0 -129
- package/src/shared/html.ts +0 -87
- package/src/shared/http.ts +0 -40
- package/src/shared/s3.ts +0 -157
- package/src/shared/storage.ts +0 -83
- package/src/vn/gold.ts +0 -192
- package/src/vn/lottery.ts +0 -129
- package/src/web_fetch.ts +0 -80
- package/src/web_search.ts +0 -92
package/src/builtins.ts
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `builtinTools(config)` — one-liner bundle that returns a `Record<string, Tool>`
|
|
3
|
-
* suitable for passing straight into `defineAgent({ tools: ... })`.
|
|
4
|
-
*
|
|
5
|
-
* Lets a developer wire common Vietnam-locale chat tools with zero per-tool
|
|
6
|
-
* boilerplate. Default-on: `time_now`, `weather`, `crypto_price`,
|
|
7
|
-
* `vn_lottery`, `vn_gold_price`. Opt-in (because they need an API key):
|
|
8
|
-
* `perplexity` and `web_search`.
|
|
9
|
-
*
|
|
10
|
-
* Pass `false` to a default-on key to disable it:
|
|
11
|
-
*
|
|
12
|
-
* ```ts
|
|
13
|
-
* defineAgent({
|
|
14
|
-
* tools: builtinTools({
|
|
15
|
-
* time: true, // default
|
|
16
|
-
* weather: true, // default
|
|
17
|
-
* crypto: false, // disabled
|
|
18
|
-
* perplexity: { apiKey: process.env.PERPLEXITY_API_KEY! },
|
|
19
|
-
* }),
|
|
20
|
-
* })
|
|
21
|
-
* ```
|
|
22
|
-
*/
|
|
23
|
-
|
|
24
|
-
import type { AnyTool } from "@tinyweb-agent-framework/llm"
|
|
25
|
-
import { timeNow, type TimeNowConfig } from "./info/time"
|
|
26
|
-
import { weather, type WeatherConfig } from "./info/weather"
|
|
27
|
-
import { cryptoPrice, type CryptoPriceConfig } from "./info/crypto"
|
|
28
|
-
import { vnGoldPrice, type VnGoldConfig } from "./vn/gold"
|
|
29
|
-
import { vnLottery, type VnLotteryConfig } from "./vn/lottery"
|
|
30
|
-
import { perplexitySearch, type PerplexitySearchConfig } from "./search/perplexity"
|
|
31
|
-
import { webSearch, type WebSearchConfig } from "./web_search"
|
|
32
|
-
import { webFetch, type WebFetchConfig } from "./web_fetch"
|
|
33
|
-
import { displayResponse, type DisplayResponseConfig } from "./display_response"
|
|
34
|
-
|
|
35
|
-
export type BuiltinToolsConfig = {
|
|
36
|
-
/** Default: `true`. Pass `false` or `TimeNowConfig` to override. */
|
|
37
|
-
readonly time?: boolean | TimeNowConfig
|
|
38
|
-
readonly weather?: boolean | WeatherConfig
|
|
39
|
-
readonly crypto?: boolean | CryptoPriceConfig
|
|
40
|
-
readonly vnGold?: boolean | VnGoldConfig
|
|
41
|
-
readonly vnLottery?: boolean | VnLotteryConfig
|
|
42
|
-
/** Opt-in: requires an API key, so default is OFF unless config supplied. */
|
|
43
|
-
readonly perplexity?: PerplexitySearchConfig
|
|
44
|
-
readonly webSearch?: WebSearchConfig
|
|
45
|
-
readonly webFetch?: boolean | WebFetchConfig
|
|
46
|
-
/**
|
|
47
|
-
* Opt-in: only needed when running under a prompt regime that requires
|
|
48
|
-
* "one tool call per turn" (Roo-style task agents). Default OFF — most
|
|
49
|
-
* chat agents should let the model emit plain assistant text instead.
|
|
50
|
-
*/
|
|
51
|
-
readonly displayResponse?: boolean | DisplayResponseConfig
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const isEnabled = (v: boolean | object | undefined, defaultOn: boolean): boolean => {
|
|
55
|
-
if (v === undefined) return defaultOn
|
|
56
|
-
if (v === false) return false
|
|
57
|
-
return true
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
const cfgOrEmpty = <T>(v: boolean | T | undefined): T => {
|
|
61
|
-
if (typeof v === "object" && v !== null) return v as T
|
|
62
|
-
return {} as T
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
export const builtinTools = (config: BuiltinToolsConfig = {}): Record<string, AnyTool> => {
|
|
66
|
-
const tools: Record<string, AnyTool> = {}
|
|
67
|
-
if (isEnabled(config.time, true)) tools.time_now = timeNow(cfgOrEmpty(config.time))
|
|
68
|
-
if (isEnabled(config.displayResponse, true))
|
|
69
|
-
tools.display_response = displayResponse(cfgOrEmpty(config.displayResponse))
|
|
70
|
-
if (isEnabled(config.weather, false)) tools.weather = weather(cfgOrEmpty(config.weather))
|
|
71
|
-
if (isEnabled(config.crypto, false)) tools.crypto_price = cryptoPrice(cfgOrEmpty(config.crypto))
|
|
72
|
-
if (isEnabled(config.vnGold, false)) tools.vn_gold_price = vnGoldPrice(cfgOrEmpty(config.vnGold))
|
|
73
|
-
if (isEnabled(config.vnLottery, false)) tools.vn_lottery = vnLottery(cfgOrEmpty(config.vnLottery))
|
|
74
|
-
if (isEnabled(config.webFetch, false)) tools.web_fetch = webFetch(cfgOrEmpty(config.webFetch))
|
|
75
|
-
if (config.perplexity) tools.perplexity_search = perplexitySearch(config.perplexity)
|
|
76
|
-
if (config.webSearch) tools.web_search = webSearch(config.webSearch)
|
|
77
|
-
return tools
|
|
78
|
-
}
|
package/src/display_response.ts
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `display_response` — fallback tool for delivering plain conversational
|
|
3
|
-
* or long-form textual content to the user.
|
|
4
|
-
*
|
|
5
|
-
* Adapted from the Roo Code extension's `display_response` native tool
|
|
6
|
-
* (`roo-code-extension/src/core/prompts/tools/native-tools/display_response.ts`).
|
|
7
|
-
*
|
|
8
|
-
* Purpose: some prompt regimes enforce "every assistant turn must call at
|
|
9
|
-
* least one tool" — display_response is the escape hatch the model can
|
|
10
|
-
* use when no domain tool is appropriate (acknowledgements, clarifying
|
|
11
|
-
* remarks, plans, explanations, long-form reports, markdown content).
|
|
12
|
-
* The tool's output is just the `response` argument echoed back, so the
|
|
13
|
-
* model's final user-facing text can be surfaced verbatim by the UI /
|
|
14
|
-
* consumer.
|
|
15
|
-
*
|
|
16
|
-
* NOTE: This is **opt-in**. Most agents in this framework don't need it —
|
|
17
|
-
* the OpenAI Chat protocol already supports plain assistant content
|
|
18
|
-
* alongside tool calls. Use this only when running under a prompt regime
|
|
19
|
-
* (e.g. Roo-style task agents) that strictly requires a tool call per turn.
|
|
20
|
-
*
|
|
21
|
-
* Renderer: not registered in chat-ui's `defaultToolRenderers` because
|
|
22
|
-
* the message is already shown as the assistant bubble's text — surfacing
|
|
23
|
-
* it again as a tool card would duplicate the same content. Consumers
|
|
24
|
-
* who DO want a card can override via `toolRenderers` on `TinywebChat`.
|
|
25
|
-
*/
|
|
26
|
-
|
|
27
|
-
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
28
|
-
import { Schema } from "effect"
|
|
29
|
-
|
|
30
|
-
export type DisplayResponseConfig = {
|
|
31
|
-
readonly name?: string
|
|
32
|
-
readonly description?: string
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
const Parameters = Schema.Struct({
|
|
36
|
-
response: Schema.String,
|
|
37
|
-
})
|
|
38
|
-
|
|
39
|
-
const Success = Schema.Struct({
|
|
40
|
-
response: Schema.String,
|
|
41
|
-
})
|
|
42
|
-
|
|
43
|
-
const DEFAULT_DESCRIPTION = [
|
|
44
|
-
"Deliver a plain textual response to the user when no other tool is appropriate for the current turn.",
|
|
45
|
-
"Use this as a fallback to satisfy the \"every assistant turn must call at least one tool\" constraint",
|
|
46
|
-
"whenever you only need to send textual content — both short conversational replies and long-form",
|
|
47
|
-
"structured output — that does not finish the task. Typical use cases:",
|
|
48
|
-
"- Clarifying remarks, brainstorming, short answers, status updates",
|
|
49
|
-
"- Presenting a plan or proposed approach before implementation",
|
|
50
|
-
"- Explaining code, concepts, errors, or trade-offs in depth",
|
|
51
|
-
"- Delivering a long-form report, summary, analysis, or review",
|
|
52
|
-
"- Showing diagrams, tables, or formatted markdown content to the user",
|
|
53
|
-
"",
|
|
54
|
-
"STRICT OUTPUT RULES (must follow exactly):",
|
|
55
|
-
"- Put the ENTIRE message inside the `response` argument of this tool call.",
|
|
56
|
-
"- Do NOT emit ANY free-form assistant text outside the tool call in the same turn. The assistant",
|
|
57
|
-
" text channel MUST be empty when you call `display_response`.",
|
|
58
|
-
"- This means: no preamble, no recap, no \"Here is…\", no trailing remark before or after the tool",
|
|
59
|
-
" call. Everything the user should see goes inside `response`.",
|
|
60
|
-
"- After you call display_response, STOP. Wait for the user's next message before doing anything",
|
|
61
|
-
" else. Do NOT keep calling tools or generate another turn on your own.",
|
|
62
|
-
"- The `response` must be non-empty.",
|
|
63
|
-
"- Prefer NOT calling display_response if a domain tool (search, weather, etc.) is the right answer.",
|
|
64
|
-
"",
|
|
65
|
-
"Parameters:",
|
|
66
|
-
"- response: (required) The textual message to deliver to the user. Markdown is supported.",
|
|
67
|
-
"",
|
|
68
|
-
"Example (correct — assistant text is empty, all content is inside the tool call):",
|
|
69
|
-
"{ \"response\": \"I looked at the two options and I think Option A is cleaner because it avoids the extra cache lookup.\" }",
|
|
70
|
-
].join("\n")
|
|
71
|
-
|
|
72
|
-
export const displayResponse = (config: DisplayResponseConfig = {}) =>
|
|
73
|
-
defineTool({
|
|
74
|
-
name: config.name ?? "display_response",
|
|
75
|
-
description: config.description ?? DEFAULT_DESCRIPTION,
|
|
76
|
-
parameters: Parameters,
|
|
77
|
-
success: Success,
|
|
78
|
-
execute: async (input) => ({ response: input.response }),
|
|
79
|
-
})
|
package/src/file_read.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
2
|
-
import { Effect, Schema } from "effect"
|
|
3
|
-
import type { FileStorage } from "./shared/storage"
|
|
4
|
-
|
|
5
|
-
export type FileReadConfig = {
|
|
6
|
-
storage: FileStorage
|
|
7
|
-
name?: string
|
|
8
|
-
description?: string
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
const Parameters = Schema.Struct({
|
|
12
|
-
key: Schema.String,
|
|
13
|
-
})
|
|
14
|
-
|
|
15
|
-
const Success = Schema.Struct({
|
|
16
|
-
content: Schema.String,
|
|
17
|
-
bytes: Schema.Number,
|
|
18
|
-
})
|
|
19
|
-
|
|
20
|
-
export const fileRead = (config: FileReadConfig) =>
|
|
21
|
-
defineTool({
|
|
22
|
-
name: config.name ?? "file_read",
|
|
23
|
-
description: config.description ?? "Read a file from configured storage by key. Returns UTF-8 text content.",
|
|
24
|
-
parameters: Parameters,
|
|
25
|
-
success: Success,
|
|
26
|
-
execute: async (input) => {
|
|
27
|
-
const bytes = await Effect.runPromise(config.storage.read(input.key))
|
|
28
|
-
const content = new TextDecoder("utf-8").decode(bytes)
|
|
29
|
-
return { content, bytes: bytes.byteLength }
|
|
30
|
-
},
|
|
31
|
-
})
|
package/src/file_write.ts
DELETED
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
2
|
-
import { Effect, Schema } from "effect"
|
|
3
|
-
import type { FileStorage } from "./shared/storage"
|
|
4
|
-
|
|
5
|
-
export type FileWriteConfig = {
|
|
6
|
-
storage: FileStorage
|
|
7
|
-
name?: string
|
|
8
|
-
description?: string
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
const Parameters = Schema.Struct({
|
|
12
|
-
key: Schema.String,
|
|
13
|
-
content: Schema.String,
|
|
14
|
-
})
|
|
15
|
-
|
|
16
|
-
const Success = Schema.Struct({
|
|
17
|
-
key: Schema.String,
|
|
18
|
-
url: Schema.optional(Schema.String),
|
|
19
|
-
bytes: Schema.Number,
|
|
20
|
-
})
|
|
21
|
-
|
|
22
|
-
export const fileWrite = (config: FileWriteConfig) =>
|
|
23
|
-
defineTool({
|
|
24
|
-
name: config.name ?? "file_write",
|
|
25
|
-
description: config.description ?? "Write a UTF-8 text file to configured storage under the given key.",
|
|
26
|
-
parameters: Parameters,
|
|
27
|
-
success: Success,
|
|
28
|
-
execute: async (input) => {
|
|
29
|
-
const bytes = new TextEncoder().encode(input.content)
|
|
30
|
-
const result = await Effect.runPromise(config.storage.write(input.key, bytes))
|
|
31
|
-
return { key: input.key, url: result.url, bytes: bytes.byteLength }
|
|
32
|
-
},
|
|
33
|
-
})
|
package/src/image_describe.ts
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
2
|
-
import { Schema } from "effect"
|
|
3
|
-
import { postJson } from "./shared/http"
|
|
4
|
-
|
|
5
|
-
export type ImageDescribeConfig = {
|
|
6
|
-
apiKey: string
|
|
7
|
-
baseURL?: string
|
|
8
|
-
model?: string
|
|
9
|
-
name?: string
|
|
10
|
-
description?: string
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
const Parameters = Schema.Struct({
|
|
14
|
-
imageUrl: Schema.String,
|
|
15
|
-
question: Schema.optional(Schema.String),
|
|
16
|
-
})
|
|
17
|
-
|
|
18
|
-
const Success = Schema.Struct({
|
|
19
|
-
description: Schema.String,
|
|
20
|
-
})
|
|
21
|
-
|
|
22
|
-
type ChatMessage = {
|
|
23
|
-
role: "user"
|
|
24
|
-
content: Array<{ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } }>
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
type ChatResponse = {
|
|
28
|
-
choices: Array<{ message: { content?: string } }>
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export const imageDescribe = (config: ImageDescribeConfig) =>
|
|
32
|
-
defineTool({
|
|
33
|
-
name: config.name ?? "image_describe",
|
|
34
|
-
description: config.description ?? "Describe the contents of an image. Pass a question to ask something specific.",
|
|
35
|
-
parameters: Parameters,
|
|
36
|
-
success: Success,
|
|
37
|
-
execute: async (input) => {
|
|
38
|
-
const baseURL = (config.baseURL ?? "https://api.openai.com/v1").replace(/\/$/, "")
|
|
39
|
-
const model = config.model ?? "gpt-4o-mini"
|
|
40
|
-
const question = input.question ?? "Describe this image in 2-3 sentences."
|
|
41
|
-
const messages: ChatMessage[] = [
|
|
42
|
-
{
|
|
43
|
-
role: "user",
|
|
44
|
-
content: [
|
|
45
|
-
{ type: "text", text: question },
|
|
46
|
-
{ type: "image_url", image_url: { url: input.imageUrl } },
|
|
47
|
-
],
|
|
48
|
-
},
|
|
49
|
-
]
|
|
50
|
-
const data = await postJson<ChatResponse>(
|
|
51
|
-
`${baseURL}/chat/completions`,
|
|
52
|
-
{ model, messages, max_tokens: 600 },
|
|
53
|
-
{ headers: { authorization: `Bearer ${config.apiKey}` } },
|
|
54
|
-
)
|
|
55
|
-
const text = data.choices[0]?.message?.content ?? ""
|
|
56
|
-
return { description: text.trim() }
|
|
57
|
-
},
|
|
58
|
-
})
|
package/src/image_edit.ts
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
2
|
-
import { Effect, Schema } from "effect"
|
|
3
|
-
import { fetchBytes } from "./shared/http"
|
|
4
|
-
import type { FileStorage } from "./shared/storage"
|
|
5
|
-
|
|
6
|
-
export type ImageEditConfig = {
|
|
7
|
-
apiKey: string
|
|
8
|
-
model?: string
|
|
9
|
-
storage?: FileStorage
|
|
10
|
-
storagePrefix?: string
|
|
11
|
-
name?: string
|
|
12
|
-
description?: string
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
const Parameters = Schema.Struct({
|
|
16
|
-
imageUrl: Schema.String,
|
|
17
|
-
prompt: Schema.String,
|
|
18
|
-
maskUrl: Schema.optional(Schema.String),
|
|
19
|
-
size: Schema.optional(Schema.String),
|
|
20
|
-
})
|
|
21
|
-
|
|
22
|
-
const Success = Schema.Struct({
|
|
23
|
-
url: Schema.String,
|
|
24
|
-
storageKey: Schema.optional(Schema.String),
|
|
25
|
-
})
|
|
26
|
-
|
|
27
|
-
type OpenAIImageData = { url?: string; b64_json?: string }
|
|
28
|
-
type OpenAIImageResponse = { data: OpenAIImageData[] }
|
|
29
|
-
|
|
30
|
-
const toBlob = async (url: string): Promise<Blob> => {
|
|
31
|
-
const bytes = await fetchBytes(url)
|
|
32
|
-
return new Blob([bytes])
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export const imageEdit = (config: ImageEditConfig) =>
|
|
36
|
-
defineTool({
|
|
37
|
-
name: config.name ?? "image_edit",
|
|
38
|
-
description: config.description ?? "Edit an image using a text prompt (and optional mask). Returns the edited image URL.",
|
|
39
|
-
parameters: Parameters,
|
|
40
|
-
success: Success,
|
|
41
|
-
execute: async (input) => {
|
|
42
|
-
const form = new FormData()
|
|
43
|
-
form.append("model", config.model ?? "gpt-image-1")
|
|
44
|
-
form.append("prompt", input.prompt)
|
|
45
|
-
const imageBlob = await toBlob(input.imageUrl)
|
|
46
|
-
form.append("image", imageBlob, "image.png")
|
|
47
|
-
if (input.maskUrl) {
|
|
48
|
-
const maskBlob = await toBlob(input.maskUrl)
|
|
49
|
-
form.append("mask", maskBlob, "mask.png")
|
|
50
|
-
}
|
|
51
|
-
if (input.size) form.append("size", input.size)
|
|
52
|
-
const res = await fetch("https://api.openai.com/v1/images/edits", {
|
|
53
|
-
method: "POST",
|
|
54
|
-
headers: { authorization: `Bearer ${config.apiKey}` },
|
|
55
|
-
body: form,
|
|
56
|
-
})
|
|
57
|
-
if (!res.ok) {
|
|
58
|
-
const body = await res.text().catch(() => "")
|
|
59
|
-
throw new Error(`OpenAI image edit failed: HTTP ${res.status}: ${body.slice(0, 500)}`)
|
|
60
|
-
}
|
|
61
|
-
const data = (await res.json()) as OpenAIImageResponse
|
|
62
|
-
const first = data.data[0]
|
|
63
|
-
if (!first) throw new Error("OpenAI returned no image data")
|
|
64
|
-
const url = first.url ?? (first.b64_json ? `data:image/png;base64,${first.b64_json}` : "")
|
|
65
|
-
if (!url) throw new Error("OpenAI image_edit response missing url and b64_json")
|
|
66
|
-
if (!config.storage || url.startsWith("data:")) {
|
|
67
|
-
return { url, storageKey: undefined }
|
|
68
|
-
}
|
|
69
|
-
const bytes = await fetchBytes(url)
|
|
70
|
-
const key = `${config.storagePrefix ?? "images"}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.png`
|
|
71
|
-
const written = await Effect.runPromise(config.storage.write(key, bytes))
|
|
72
|
-
return { url: written.url ?? url, storageKey: key }
|
|
73
|
-
},
|
|
74
|
-
})
|
package/src/image_generate.ts
DELETED
|
@@ -1,102 +0,0 @@
|
|
|
1
|
-
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
2
|
-
import { Effect, Schema } from "effect"
|
|
3
|
-
import { fetchBytes, postJson } from "./shared/http"
|
|
4
|
-
import type { FileStorage } from "./shared/storage"
|
|
5
|
-
|
|
6
|
-
export type ImageGenProvider = "openai" | "replicate"
|
|
7
|
-
|
|
8
|
-
export type ImageGenerateConfig = {
|
|
9
|
-
provider: ImageGenProvider
|
|
10
|
-
apiKey: string
|
|
11
|
-
model?: string
|
|
12
|
-
storage?: FileStorage
|
|
13
|
-
storagePrefix?: string
|
|
14
|
-
name?: string
|
|
15
|
-
description?: string
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
const Parameters = Schema.Struct({
|
|
19
|
-
prompt: Schema.String,
|
|
20
|
-
size: Schema.optional(Schema.String),
|
|
21
|
-
n: Schema.optional(Schema.Number),
|
|
22
|
-
})
|
|
23
|
-
|
|
24
|
-
const Success = Schema.Struct({
|
|
25
|
-
url: Schema.String,
|
|
26
|
-
storageKey: Schema.optional(Schema.String),
|
|
27
|
-
})
|
|
28
|
-
|
|
29
|
-
type ImageInput = Schema.Schema.Type<typeof Parameters>
|
|
30
|
-
|
|
31
|
-
type OpenAIImageData = { url?: string; b64_json?: string }
|
|
32
|
-
type OpenAIImageResponse = { data: OpenAIImageData[] }
|
|
33
|
-
type ReplicatePrediction = { id: string; status: string; output?: string | string[]; error?: string | null; urls?: { get?: string } }
|
|
34
|
-
|
|
35
|
-
const generateOpenAI = async (apiKey: string, model: string, input: ImageInput): Promise<string> => {
|
|
36
|
-
const data = await postJson<OpenAIImageResponse>(
|
|
37
|
-
"https://api.openai.com/v1/images/generations",
|
|
38
|
-
{ model, prompt: input.prompt, size: input.size, n: input.n ?? 1 },
|
|
39
|
-
{ headers: { authorization: `Bearer ${apiKey}` } },
|
|
40
|
-
)
|
|
41
|
-
const first = data.data[0]
|
|
42
|
-
if (!first) throw new Error("OpenAI returned no image data")
|
|
43
|
-
if (first.url) return first.url
|
|
44
|
-
if (first.b64_json) return `data:image/png;base64,${first.b64_json}`
|
|
45
|
-
throw new Error("OpenAI image response missing url and b64_json")
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
|
49
|
-
|
|
50
|
-
const generateReplicate = async (apiKey: string, model: string, input: ImageInput): Promise<string> => {
|
|
51
|
-
const initial = await postJson<ReplicatePrediction>(
|
|
52
|
-
"https://api.replicate.com/v1/predictions",
|
|
53
|
-
{ version: model, input: { prompt: input.prompt } },
|
|
54
|
-
{ headers: { authorization: `Token ${apiKey}` } },
|
|
55
|
-
)
|
|
56
|
-
let current = initial
|
|
57
|
-
const pollUrl = initial.urls?.get
|
|
58
|
-
if (!pollUrl) throw new Error("Replicate prediction missing poll url")
|
|
59
|
-
const deadline = Date.now() + 120_000
|
|
60
|
-
while (current.status !== "succeeded" && current.status !== "failed" && current.status !== "canceled") {
|
|
61
|
-
if (Date.now() > deadline) throw new Error("Replicate timeout after 120s")
|
|
62
|
-
await sleep(1500)
|
|
63
|
-
const r = await fetch(pollUrl, { headers: { authorization: `Token ${apiKey}` } })
|
|
64
|
-
if (!r.ok) throw new Error(`Replicate poll failed: HTTP ${r.status}`)
|
|
65
|
-
current = (await r.json()) as ReplicatePrediction
|
|
66
|
-
}
|
|
67
|
-
if (current.status !== "succeeded") throw new Error(`Replicate ${current.status}: ${current.error ?? "unknown"}`)
|
|
68
|
-
const output = current.output
|
|
69
|
-
if (Array.isArray(output)) return output[0] ?? ""
|
|
70
|
-
return output ?? ""
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
const generate = (provider: ImageGenProvider, apiKey: string, model: string, input: ImageInput): Promise<string> => {
|
|
74
|
-
if (provider === "openai") return generateOpenAI(apiKey, model, input)
|
|
75
|
-
if (provider === "replicate") return generateReplicate(apiKey, model, input)
|
|
76
|
-
throw new Error(`Unknown image_generate provider: ${provider as string}`)
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const defaultModel = (provider: ImageGenProvider): string => {
|
|
80
|
-
if (provider === "openai") return "gpt-image-1"
|
|
81
|
-
return "black-forest-labs/flux-schnell"
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export const imageGenerate = (config: ImageGenerateConfig) =>
|
|
85
|
-
defineTool({
|
|
86
|
-
name: config.name ?? "image_generate",
|
|
87
|
-
description: config.description ?? "Generate an image from a prompt. Returns the image URL (and storage key if storage configured).",
|
|
88
|
-
parameters: Parameters,
|
|
89
|
-
success: Success,
|
|
90
|
-
execute: async (input) => {
|
|
91
|
-
const model = config.model ?? defaultModel(config.provider)
|
|
92
|
-
const url = await generate(config.provider, config.apiKey, model, input)
|
|
93
|
-
if (!config.storage || url.startsWith("data:")) {
|
|
94
|
-
return { url, storageKey: undefined }
|
|
95
|
-
}
|
|
96
|
-
const bytes = await fetchBytes(url)
|
|
97
|
-
const ext = url.includes(".webp") ? "webp" : url.includes(".jpg") || url.includes(".jpeg") ? "jpg" : "png"
|
|
98
|
-
const key = `${config.storagePrefix ?? "images"}/${Date.now()}-${Math.random().toString(36).slice(2, 8)}.${ext}`
|
|
99
|
-
const result = await Effect.runPromise(config.storage.write(key, bytes))
|
|
100
|
-
return { url: result.url ?? url, storageKey: key }
|
|
101
|
-
},
|
|
102
|
-
})
|
package/src/index.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
export const VERSION = "0.0.1"
|
|
2
|
-
|
|
3
|
-
// Shared infrastructure
|
|
4
|
-
export { FileError, makeMemoryStore, makeLocalFS, type FileStorage, type WriteResult } from "./shared/storage"
|
|
5
|
-
export {
|
|
6
|
-
makeS3Store,
|
|
7
|
-
type S3ClientLike,
|
|
8
|
-
type S3CommandFactory,
|
|
9
|
-
type S3CommandLike,
|
|
10
|
-
type S3Commands,
|
|
11
|
-
type S3StoreOptions,
|
|
12
|
-
} from "./shared/s3"
|
|
13
|
-
export { HttpToolError, fetchJson, postJson, fetchText, fetchBytes } from "./shared/http"
|
|
14
|
-
export {
|
|
15
|
-
loadHtml,
|
|
16
|
-
firstMatchText,
|
|
17
|
-
collectText,
|
|
18
|
-
parseVndNumber,
|
|
19
|
-
type HtmlRoot,
|
|
20
|
-
type Cheerio,
|
|
21
|
-
type CheerioAPI,
|
|
22
|
-
} from "./shared/html"
|
|
23
|
-
|
|
24
|
-
// Web & file tools (existing)
|
|
25
|
-
export { webSearch, type WebSearchConfig, type WebSearchProvider } from "./web_search"
|
|
26
|
-
export { webFetch, type WebFetchConfig } from "./web_fetch"
|
|
27
|
-
export { imageGenerate, type ImageGenerateConfig, type ImageGenProvider } from "./image_generate"
|
|
28
|
-
export { imageDescribe, type ImageDescribeConfig } from "./image_describe"
|
|
29
|
-
export { imageEdit, type ImageEditConfig } from "./image_edit"
|
|
30
|
-
export { fileRead, type FileReadConfig } from "./file_read"
|
|
31
|
-
export { fileWrite, type FileWriteConfig } from "./file_write"
|
|
32
|
-
export { displayResponse, type DisplayResponseConfig } from "./display_response"
|
|
33
|
-
|
|
34
|
-
// Info & utility tools (new)
|
|
35
|
-
export { timeNow, type TimeNowConfig } from "./info/time"
|
|
36
|
-
export { weather, type WeatherConfig } from "./info/weather"
|
|
37
|
-
export { cryptoPrice, type CryptoPriceConfig } from "./info/crypto"
|
|
38
|
-
|
|
39
|
-
// Vietnam locale tools (new)
|
|
40
|
-
export { vnGoldPrice, type VnGoldConfig } from "./vn/gold"
|
|
41
|
-
export { vnLottery, type VnLotteryConfig } from "./vn/lottery"
|
|
42
|
-
|
|
43
|
-
// Search providers (new)
|
|
44
|
-
export { perplexitySearch, type PerplexitySearchConfig, type PerplexityModel } from "./search/perplexity"
|
|
45
|
-
|
|
46
|
-
// One-liner bundle factory
|
|
47
|
-
export { builtinTools, type BuiltinToolsConfig } from "./builtins"
|
package/src/info/crypto.ts
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `crypto_price` — current spot price for one or more crypto symbols.
|
|
3
|
-
*
|
|
4
|
-
* Adapted from `packages/tool/references/daily-info/crypto` which curls
|
|
5
|
-
* `api.binance.com/api/v3/ticker/price?symbol=BTCUSDT` per coin. We support
|
|
6
|
-
* batch lookup in one call to save round-trips, and quote against USDT by
|
|
7
|
-
* default (closest free proxy for USD).
|
|
8
|
-
*
|
|
9
|
-
* Zero-config: Binance public ticker is key-less. Note Binance occasionally
|
|
10
|
-
* geo-blocks (e.g. some US IPs) — the tool surfaces HTTP errors as-is so
|
|
11
|
-
* the LLM can apologise.
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
15
|
-
import { Schema } from "effect"
|
|
16
|
-
import { fetchJson } from "../shared/http"
|
|
17
|
-
|
|
18
|
-
export type CryptoPriceConfig = {
|
|
19
|
-
/** Quote asset suffix, default "USDT". Use "BUSD" / "USDC" / "BTC" if needed. */
|
|
20
|
-
readonly quote?: string
|
|
21
|
-
readonly timeoutMs?: number
|
|
22
|
-
readonly name?: string
|
|
23
|
-
readonly description?: string
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
const Parameters = Schema.Struct({
|
|
27
|
-
symbols: Schema.Array(Schema.String),
|
|
28
|
-
quote: Schema.optional(Schema.String),
|
|
29
|
-
})
|
|
30
|
-
|
|
31
|
-
const PriceItem = Schema.Struct({
|
|
32
|
-
symbol: Schema.String,
|
|
33
|
-
quote: Schema.String,
|
|
34
|
-
price: Schema.Number,
|
|
35
|
-
pair: Schema.String,
|
|
36
|
-
})
|
|
37
|
-
|
|
38
|
-
const Success = Schema.Struct({
|
|
39
|
-
prices: Schema.Array(PriceItem),
|
|
40
|
-
observed_at: Schema.String,
|
|
41
|
-
source: Schema.Literal("binance"),
|
|
42
|
-
})
|
|
43
|
-
|
|
44
|
-
type BinanceTicker = { symbol: string; price: string }
|
|
45
|
-
|
|
46
|
-
const upper = (s: string): string => s.trim().toUpperCase()
|
|
47
|
-
|
|
48
|
-
export const cryptoPrice = (config: CryptoPriceConfig = {}) => {
|
|
49
|
-
const defaultQuote = upper(config.quote ?? "USDT")
|
|
50
|
-
const timeout = config.timeoutMs ?? 10000
|
|
51
|
-
return defineTool({
|
|
52
|
-
name: config.name ?? "crypto_price",
|
|
53
|
-
description:
|
|
54
|
-
config.description ??
|
|
55
|
-
`Lấy giá spot hiện tại của một hoặc nhiều mã crypto (BTC, ETH, SOL, ...) tính theo ${defaultQuote}. Nguồn: Binance.`,
|
|
56
|
-
parameters: Parameters,
|
|
57
|
-
success: Success,
|
|
58
|
-
execute: async (input) => {
|
|
59
|
-
const quote = upper(input.quote ?? defaultQuote)
|
|
60
|
-
const pairs = input.symbols.map((s) => `${upper(s)}${quote}`)
|
|
61
|
-
if (pairs.length === 0) throw new Error("symbols must be a non-empty array")
|
|
62
|
-
// Binance accepts a JSON-encoded array as the `symbols` query param.
|
|
63
|
-
const arrayParam = encodeURIComponent(JSON.stringify(pairs))
|
|
64
|
-
const url = `https://api.binance.com/api/v3/ticker/price?symbols=${arrayParam}`
|
|
65
|
-
const controller = new AbortController()
|
|
66
|
-
const timer = setTimeout(() => controller.abort(), timeout)
|
|
67
|
-
const data = await fetchJson<BinanceTicker[]>(url, { signal: controller.signal }).finally(() =>
|
|
68
|
-
clearTimeout(timer),
|
|
69
|
-
)
|
|
70
|
-
const prices = data.map((t) => ({
|
|
71
|
-
symbol: t.symbol.endsWith(quote) ? t.symbol.slice(0, -quote.length) : t.symbol,
|
|
72
|
-
quote,
|
|
73
|
-
price: Number(t.price),
|
|
74
|
-
pair: t.symbol,
|
|
75
|
-
}))
|
|
76
|
-
return { prices, observed_at: new Date().toISOString(), source: "binance" as const }
|
|
77
|
-
},
|
|
78
|
-
})
|
|
79
|
-
}
|
package/src/info/time.ts
DELETED
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `time_now` — current time in a given IANA timezone.
|
|
3
|
-
*
|
|
4
|
-
* Zero-config: pure `Intl.DateTimeFormat`, no HTTP, no API key.
|
|
5
|
-
* Default tz is `Asia/Ho_Chi_Minh` because most demos in this repo target
|
|
6
|
-
* a Vietnamese audience; pass an override if you ship elsewhere.
|
|
7
|
-
*
|
|
8
|
-
* Adapted from the spirit of `packages/tool/references/daily-info/`
|
|
9
|
-
* (the bash prototypes used the OS clock; this is the framework port).
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
13
|
-
import { Schema } from "effect"
|
|
14
|
-
|
|
15
|
-
export type TimeNowConfig = {
|
|
16
|
-
/** Default timezone when the LLM doesn't pass one. IANA name. */
|
|
17
|
-
readonly defaultTimezone?: string
|
|
18
|
-
/** Default locale for the `formatted` human-readable string. */
|
|
19
|
-
readonly defaultLocale?: string
|
|
20
|
-
readonly name?: string
|
|
21
|
-
readonly description?: string
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
const Parameters = Schema.Struct({
|
|
25
|
-
timezone: Schema.optional(Schema.String),
|
|
26
|
-
locale: Schema.optional(Schema.String),
|
|
27
|
-
})
|
|
28
|
-
|
|
29
|
-
const Success = Schema.Struct({
|
|
30
|
-
timezone: Schema.String,
|
|
31
|
-
locale: Schema.String,
|
|
32
|
-
iso: Schema.String,
|
|
33
|
-
formatted: Schema.String,
|
|
34
|
-
weekday: Schema.String,
|
|
35
|
-
unix_ms: Schema.Number,
|
|
36
|
-
})
|
|
37
|
-
|
|
38
|
-
const VN_WEEKDAYS = ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"] as const
|
|
39
|
-
|
|
40
|
-
const vietnameseWeekday = (date: Date, timezone: string): string => {
|
|
41
|
-
// Use Intl to derive the weekday index in the target tz, then map to VN label.
|
|
42
|
-
const fmt = new Intl.DateTimeFormat("en-US", { timeZone: timezone, weekday: "short" })
|
|
43
|
-
const short = fmt.format(date)
|
|
44
|
-
const map: Record<string, number> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 }
|
|
45
|
-
const idx = map[short] ?? 0
|
|
46
|
-
return VN_WEEKDAYS[idx]!
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export const timeNow = (config: TimeNowConfig = {}) => {
|
|
50
|
-
const defaultTz = config.defaultTimezone ?? "Asia/Ho_Chi_Minh"
|
|
51
|
-
const defaultLocale = config.defaultLocale ?? "vi-VN"
|
|
52
|
-
return defineTool({
|
|
53
|
-
name: config.name ?? "time_now",
|
|
54
|
-
description:
|
|
55
|
-
config.description ??
|
|
56
|
-
`Lấy thời gian hiện tại theo timezone IANA (mặc định ${defaultTz}). Trả về ISO, định dạng thân thiện, và unix timestamp.`,
|
|
57
|
-
parameters: Parameters,
|
|
58
|
-
success: Success,
|
|
59
|
-
execute: async (input) => {
|
|
60
|
-
const tz = input.timezone ?? defaultTz
|
|
61
|
-
const locale = input.locale ?? defaultLocale
|
|
62
|
-
const now = new Date()
|
|
63
|
-
// Validate tz by attempting to format — invalid tz throws RangeError.
|
|
64
|
-
const dtf = new Intl.DateTimeFormat(locale, {
|
|
65
|
-
timeZone: tz,
|
|
66
|
-
dateStyle: "full",
|
|
67
|
-
timeStyle: "long",
|
|
68
|
-
})
|
|
69
|
-
const formatted = dtf.format(now)
|
|
70
|
-
const weekday = locale.startsWith("vi")
|
|
71
|
-
? vietnameseWeekday(now, tz)
|
|
72
|
-
: new Intl.DateTimeFormat(locale, { timeZone: tz, weekday: "long" }).format(now)
|
|
73
|
-
return {
|
|
74
|
-
timezone: tz,
|
|
75
|
-
locale,
|
|
76
|
-
iso: now.toISOString(),
|
|
77
|
-
formatted,
|
|
78
|
-
weekday,
|
|
79
|
-
unix_ms: now.getTime(),
|
|
80
|
-
}
|
|
81
|
-
},
|
|
82
|
-
})
|
|
83
|
-
}
|