@tinyweb_dev/agent-framework-tool 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 +21 -0
- package/README.md +114 -0
- package/package.json +50 -0
- package/src/builtins.ts +78 -0
- package/src/display_response.ts +79 -0
- package/src/file_read.ts +31 -0
- package/src/file_write.ts +33 -0
- package/src/image_describe.ts +58 -0
- package/src/image_edit.ts +74 -0
- package/src/image_generate.ts +102 -0
- package/src/index.ts +47 -0
- package/src/info/crypto.ts +79 -0
- package/src/info/time.ts +83 -0
- package/src/info/weather.ts +134 -0
- package/src/search/perplexity.ts +129 -0
- package/src/shared/html.ts +87 -0
- package/src/shared/http.ts +40 -0
- package/src/shared/s3.ts +157 -0
- package/src/shared/storage.ts +83 -0
- package/src/vn/gold.ts +192 -0
- package/src/vn/lottery.ts +129 -0
- package/src/web_fetch.ts +80 -0
- package/src/web_search.ts +92 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
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"
|
|
@@ -0,0 +1,79 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `weather` — current weather snapshot via wttr.in JSON.
|
|
3
|
+
*
|
|
4
|
+
* Adapted from `packages/tool/references/daily-info/thoitiet` which curls
|
|
5
|
+
* `wttr.in/${location}?0&m&lang=vi` for plain text. We use the JSON variant
|
|
6
|
+
* (`?format=j1`) instead — LLMs parse structured data more reliably than the
|
|
7
|
+
* ASCII art block returned by `?0`.
|
|
8
|
+
*
|
|
9
|
+
* Zero-config: wttr.in is free and key-less. Be a good citizen — wttr.in
|
|
10
|
+
* asks clients to set a real `User-Agent` so they can rate-limit abusers.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
14
|
+
import { Schema } from "effect"
|
|
15
|
+
import { fetchJson } from "../shared/http"
|
|
16
|
+
|
|
17
|
+
export type WeatherConfig = {
|
|
18
|
+
readonly defaultLocation?: string
|
|
19
|
+
/** Language for `lang_*` description fields. wttr.in supports vi, en, fr, ... */
|
|
20
|
+
readonly defaultLang?: string
|
|
21
|
+
readonly userAgent?: string
|
|
22
|
+
readonly timeoutMs?: number
|
|
23
|
+
readonly name?: string
|
|
24
|
+
readonly description?: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const Parameters = Schema.Struct({
|
|
28
|
+
location: Schema.optional(Schema.String),
|
|
29
|
+
lang: Schema.optional(Schema.String),
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
const Success = Schema.Struct({
|
|
33
|
+
location: Schema.String,
|
|
34
|
+
region: Schema.optional(Schema.String),
|
|
35
|
+
country: Schema.optional(Schema.String),
|
|
36
|
+
observed_at: Schema.String,
|
|
37
|
+
temperature_c: Schema.Number,
|
|
38
|
+
feels_like_c: Schema.Number,
|
|
39
|
+
humidity_percent: Schema.Number,
|
|
40
|
+
wind_kmh: Schema.Number,
|
|
41
|
+
wind_direction: Schema.String,
|
|
42
|
+
condition: Schema.String,
|
|
43
|
+
uv_index: Schema.optional(Schema.Number),
|
|
44
|
+
visibility_km: Schema.optional(Schema.Number),
|
|
45
|
+
pressure_mb: Schema.optional(Schema.Number),
|
|
46
|
+
source: Schema.Literal("wttr.in"),
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
// Subset of the wttr.in `?format=j1` response we care about.
|
|
50
|
+
// Reference: https://github.com/chubin/wttr.in (search "JSON output")
|
|
51
|
+
type WttrCondition = {
|
|
52
|
+
temp_C?: string
|
|
53
|
+
FeelsLikeC?: string
|
|
54
|
+
humidity?: string
|
|
55
|
+
windspeedKmph?: string
|
|
56
|
+
winddir16Point?: string
|
|
57
|
+
weatherDesc?: { value: string }[]
|
|
58
|
+
lang_vi?: { value: string }[]
|
|
59
|
+
uvIndex?: string
|
|
60
|
+
visibilityKm?: string
|
|
61
|
+
visibility?: string
|
|
62
|
+
pressure?: string
|
|
63
|
+
observation_time?: string
|
|
64
|
+
localObsDateTime?: string
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
type WttrArea = {
|
|
68
|
+
areaName?: { value: string }[]
|
|
69
|
+
region?: { value: string }[]
|
|
70
|
+
country?: { value: string }[]
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
type WttrResponse = {
|
|
74
|
+
current_condition?: WttrCondition[]
|
|
75
|
+
nearest_area?: WttrArea[]
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const firstValue = (xs: { value: string }[] | undefined): string | undefined =>
|
|
79
|
+
xs && xs.length > 0 ? xs[0]!.value : undefined
|
|
80
|
+
|
|
81
|
+
const num = (s: string | undefined, fallback = 0): number => {
|
|
82
|
+
if (!s) return fallback
|
|
83
|
+
const n = Number(s)
|
|
84
|
+
return Number.isFinite(n) ? n : fallback
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export const weather = (config: WeatherConfig = {}) => {
|
|
88
|
+
const defaultLocation = config.defaultLocation ?? "Hanoi"
|
|
89
|
+
const defaultLang = config.defaultLang ?? "vi"
|
|
90
|
+
const ua = config.userAgent ?? "tinyweb-agent-framework/0.1 (+https://github.com/anomalyco/tinyweb-agent)"
|
|
91
|
+
const timeout = config.timeoutMs ?? 15000
|
|
92
|
+
return defineTool({
|
|
93
|
+
name: config.name ?? "weather",
|
|
94
|
+
description:
|
|
95
|
+
config.description ??
|
|
96
|
+
`Lấy thời tiết hiện tại của một địa điểm (city, tỉnh, hoặc tên sân bay). Mặc định ${defaultLocation}. Nguồn: wttr.in.`,
|
|
97
|
+
parameters: Parameters,
|
|
98
|
+
success: Success,
|
|
99
|
+
execute: async (input) => {
|
|
100
|
+
const loc = (input.location ?? defaultLocation).trim()
|
|
101
|
+
const lang = input.lang ?? defaultLang
|
|
102
|
+
const url = `https://wttr.in/${encodeURIComponent(loc)}?format=j1&lang=${encodeURIComponent(lang)}`
|
|
103
|
+
const controller = new AbortController()
|
|
104
|
+
const timer = setTimeout(() => controller.abort(), timeout)
|
|
105
|
+
const data = await fetchJson<WttrResponse>(url, {
|
|
106
|
+
headers: { "user-agent": ua, accept: "application/json" },
|
|
107
|
+
signal: controller.signal,
|
|
108
|
+
}).finally(() => clearTimeout(timer))
|
|
109
|
+
const cur = data.current_condition?.[0]
|
|
110
|
+
if (!cur) throw new Error(`wttr.in returned no current_condition for "${loc}"`)
|
|
111
|
+
const area = data.nearest_area?.[0]
|
|
112
|
+
const condition = (lang === "vi" ? firstValue(cur.lang_vi) : undefined) ?? firstValue(cur.weatherDesc) ?? "N/A"
|
|
113
|
+
const visibility = num(cur.visibilityKm ?? cur.visibility, NaN)
|
|
114
|
+
const pressure = num(cur.pressure, NaN)
|
|
115
|
+
const uv = num(cur.uvIndex, NaN)
|
|
116
|
+
return {
|
|
117
|
+
location: firstValue(area?.areaName) ?? loc,
|
|
118
|
+
region: firstValue(area?.region),
|
|
119
|
+
country: firstValue(area?.country),
|
|
120
|
+
observed_at: cur.localObsDateTime ?? cur.observation_time ?? new Date().toISOString(),
|
|
121
|
+
temperature_c: num(cur.temp_C),
|
|
122
|
+
feels_like_c: num(cur.FeelsLikeC),
|
|
123
|
+
humidity_percent: num(cur.humidity),
|
|
124
|
+
wind_kmh: num(cur.windspeedKmph),
|
|
125
|
+
wind_direction: cur.winddir16Point ?? "",
|
|
126
|
+
condition,
|
|
127
|
+
uv_index: Number.isFinite(uv) ? uv : undefined,
|
|
128
|
+
visibility_km: Number.isFinite(visibility) ? visibility : undefined,
|
|
129
|
+
pressure_mb: Number.isFinite(pressure) ? pressure : undefined,
|
|
130
|
+
source: "wttr.in" as const,
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
})
|
|
134
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `perplexity_search` — answer a question via Perplexity Sonar API.
|
|
3
|
+
*
|
|
4
|
+
* Unlike `web_search` (which returns raw `{title,url,snippet}` results for the
|
|
5
|
+
* LLM to synthesize), Perplexity's Sonar models return a **synthesized
|
|
6
|
+
* answer + citations** in one shot. That:
|
|
7
|
+
*
|
|
8
|
+
* • Saves output tokens on the main model (Perplexity does the summary).
|
|
9
|
+
* • Cuts hallucination risk because citations are grounded in retrieved
|
|
10
|
+
* pages.
|
|
11
|
+
* • Costs more per call but is cheaper than running web_search + a long
|
|
12
|
+
* follow-up turn.
|
|
13
|
+
*
|
|
14
|
+
* The Sonar API is **OpenAI Chat Completions-compatible**:
|
|
15
|
+
* `POST https://api.perplexity.ai/chat/completions` with the standard
|
|
16
|
+
* `{ model, messages }` body. We hit it with `postJson` and pull out the
|
|
17
|
+
* `choices[0].message.content` plus the top-level `citations` array.
|
|
18
|
+
*
|
|
19
|
+
* Docs: https://docs.perplexity.ai/docs/sdk/overview
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { defineTool } from "@tinyweb-agent-framework/agent"
|
|
23
|
+
import { Schema } from "effect"
|
|
24
|
+
import { postJson } from "../shared/http"
|
|
25
|
+
|
|
26
|
+
export type PerplexityModel = "sonar" | "sonar-pro" | "sonar-reasoning" | "sonar-reasoning-pro"
|
|
27
|
+
|
|
28
|
+
export type PerplexitySearchConfig = {
|
|
29
|
+
readonly apiKey: string
|
|
30
|
+
/** Default Sonar variant. Cheaper-and-good = "sonar"; deepest = "sonar-reasoning-pro". */
|
|
31
|
+
readonly model?: PerplexityModel
|
|
32
|
+
/** Optional system prompt prepended on every call. Keeps the answer style on-brand. */
|
|
33
|
+
readonly systemPrompt?: string
|
|
34
|
+
/** Override the base URL if you proxy through your own gateway. */
|
|
35
|
+
readonly baseURL?: string
|
|
36
|
+
readonly timeoutMs?: number
|
|
37
|
+
/** Generation params. Defaults are sensible for grounded short answers. */
|
|
38
|
+
readonly temperature?: number
|
|
39
|
+
readonly maxTokens?: number
|
|
40
|
+
readonly name?: string
|
|
41
|
+
readonly description?: string
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const Parameters = Schema.Struct({
|
|
45
|
+
query: Schema.String,
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
const Citation = Schema.Struct({
|
|
49
|
+
url: Schema.String,
|
|
50
|
+
title: Schema.optional(Schema.String),
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
const Success = Schema.Struct({
|
|
54
|
+
query: Schema.String,
|
|
55
|
+
answer: Schema.String,
|
|
56
|
+
citations: Schema.Array(Citation),
|
|
57
|
+
model: Schema.String,
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
// Sonar response shape — OpenAI-compatible plus top-level extras.
|
|
61
|
+
type SonarMessage = { role: string; content: string }
|
|
62
|
+
type SonarChoice = { message: SonarMessage; finish_reason?: string }
|
|
63
|
+
type SonarSearchResult = { url?: string; title?: string }
|
|
64
|
+
type SonarResponse = {
|
|
65
|
+
model?: string
|
|
66
|
+
choices: SonarChoice[]
|
|
67
|
+
// Older revisions returned `citations: string[]`. Newer ones return
|
|
68
|
+
// `search_results: [{ url, title, ... }]`. Support both.
|
|
69
|
+
citations?: string[]
|
|
70
|
+
search_results?: SonarSearchResult[]
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const normaliseCitations = (data: SonarResponse): { url: string; title?: string }[] => {
|
|
74
|
+
if (data.search_results && data.search_results.length > 0) {
|
|
75
|
+
return data.search_results
|
|
76
|
+
.filter((r): r is SonarSearchResult & { url: string } => typeof r.url === "string" && r.url.length > 0)
|
|
77
|
+
.map((r) => (r.title ? { url: r.url, title: r.title } : { url: r.url }))
|
|
78
|
+
}
|
|
79
|
+
if (data.citations && data.citations.length > 0) {
|
|
80
|
+
return data.citations.filter((u) => typeof u === "string").map((u) => ({ url: u }))
|
|
81
|
+
}
|
|
82
|
+
return []
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export const perplexitySearch = (config: PerplexitySearchConfig) => {
|
|
86
|
+
if (!config.apiKey) throw new Error("perplexitySearch: apiKey is required")
|
|
87
|
+
const model = config.model ?? "sonar"
|
|
88
|
+
const baseURL = config.baseURL ?? "https://api.perplexity.ai"
|
|
89
|
+
const timeout = config.timeoutMs ?? 30000
|
|
90
|
+
const temperature = config.temperature ?? 0.2
|
|
91
|
+
const maxTokens = config.maxTokens ?? 800
|
|
92
|
+
const sys =
|
|
93
|
+
config.systemPrompt ??
|
|
94
|
+
"Answer the user's question accurately and concisely. Cite sources by URL. Use the user's language."
|
|
95
|
+
return defineTool({
|
|
96
|
+
name: config.name ?? "perplexity_search",
|
|
97
|
+
description:
|
|
98
|
+
config.description ??
|
|
99
|
+
"Hỏi-đáp web với Perplexity Sonar: nhận về câu trả lời đã tổng hợp + citation. Dùng khi cần thông tin tươi/đa nguồn.",
|
|
100
|
+
parameters: Parameters,
|
|
101
|
+
success: Success,
|
|
102
|
+
execute: async (input) => {
|
|
103
|
+
const url = `${baseURL.replace(/\/+$/, "")}/chat/completions`
|
|
104
|
+
const controller = new AbortController()
|
|
105
|
+
const timer = setTimeout(() => controller.abort(), timeout)
|
|
106
|
+
const body = {
|
|
107
|
+
model,
|
|
108
|
+
messages: [
|
|
109
|
+
{ role: "system", content: sys },
|
|
110
|
+
{ role: "user", content: input.query },
|
|
111
|
+
],
|
|
112
|
+
temperature,
|
|
113
|
+
max_tokens: maxTokens,
|
|
114
|
+
}
|
|
115
|
+
const data = await postJson<SonarResponse>(url, body, {
|
|
116
|
+
headers: { authorization: `Bearer ${config.apiKey}` },
|
|
117
|
+
signal: controller.signal,
|
|
118
|
+
}).finally(() => clearTimeout(timer))
|
|
119
|
+
const answer = data.choices?.[0]?.message?.content ?? ""
|
|
120
|
+
if (!answer) throw new Error("perplexitySearch: empty answer from Sonar API")
|
|
121
|
+
return {
|
|
122
|
+
query: input.query,
|
|
123
|
+
answer,
|
|
124
|
+
citations: normaliseCitations(data),
|
|
125
|
+
model: data.model ?? model,
|
|
126
|
+
}
|
|
127
|
+
},
|
|
128
|
+
})
|
|
129
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared HTML scraping helpers.
|
|
3
|
+
*
|
|
4
|
+
* Centralises cheerio import so tools don't each pull it directly. Adds:
|
|
5
|
+
* • `loadHtml(html)` — typed wrapper returning a `cheerio.Cheerio` root.
|
|
6
|
+
* • `firstMatchText(root, selectors)` — try a list of selectors in order;
|
|
7
|
+
* return the first non-empty .text() found. Useful for resilient scrapers
|
|
8
|
+
* where the upstream site has multiple legacy layouts.
|
|
9
|
+
* • `collectText(root, selector)` — collect trimmed text for every match.
|
|
10
|
+
* • `parseVndNumber(s)` — parse `"125.500.000"` (Vietnamese thousand sep)
|
|
11
|
+
* and `"125,500.50"` into a number.
|
|
12
|
+
*
|
|
13
|
+
* Cheerio is loaded eagerly (top-level import). Bun handles its ESM build
|
|
14
|
+
* transparently. We re-export the `Cheerio` and `CheerioAPI` types so call
|
|
15
|
+
* sites don't have to take a direct dep on cheerio.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { load, type CheerioAPI, type Cheerio } from "cheerio"
|
|
19
|
+
|
|
20
|
+
export type HtmlRoot = CheerioAPI
|
|
21
|
+
|
|
22
|
+
export const loadHtml = (html: string): HtmlRoot => load(html)
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Try each selector in order; return the trimmed `.text()` of the first match
|
|
26
|
+
* with non-empty content. Returns `undefined` if nothing matches.
|
|
27
|
+
*/
|
|
28
|
+
export const firstMatchText = ($: HtmlRoot, selectors: readonly string[]): string | undefined => {
|
|
29
|
+
for (const sel of selectors) {
|
|
30
|
+
const el = $(sel).first()
|
|
31
|
+
if (el.length === 0) continue
|
|
32
|
+
const txt = el.text().trim()
|
|
33
|
+
if (txt) return txt
|
|
34
|
+
}
|
|
35
|
+
return undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Collect `.text()` (trimmed, non-empty) for every match of the selector.
|
|
40
|
+
*/
|
|
41
|
+
export const collectText = ($: HtmlRoot, selector: string): string[] => {
|
|
42
|
+
const out: string[] = []
|
|
43
|
+
// Cheerio's `each` types the second arg as `AnyNode` from domhandler. We
|
|
44
|
+
// don't want a direct domhandler dep, so we let TS infer via `.toArray()`
|
|
45
|
+
// which returns the node array typed by cheerio itself.
|
|
46
|
+
for (const node of $(selector).toArray()) {
|
|
47
|
+
const txt = $(node).text().trim()
|
|
48
|
+
if (txt) out.push(txt)
|
|
49
|
+
}
|
|
50
|
+
return out
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Parse a Vietnamese-style number like "125.500.000" → 125500000, or
|
|
55
|
+
* "1,234.56" → 1234.56. Heuristic: if there's both `.` and `,`, assume the
|
|
56
|
+
* last separator is the decimal mark. If only `.` is present and groups are
|
|
57
|
+
* exactly 3 digits, treat them as thousands.
|
|
58
|
+
*/
|
|
59
|
+
export const parseVndNumber = (s: string): number => {
|
|
60
|
+
const cleaned = s.replace(/[^\d.,-]/g, "").trim()
|
|
61
|
+
if (!cleaned) return NaN
|
|
62
|
+
const hasDot = cleaned.includes(".")
|
|
63
|
+
const hasComma = cleaned.includes(",")
|
|
64
|
+
if (hasDot && hasComma) {
|
|
65
|
+
const lastDot = cleaned.lastIndexOf(".")
|
|
66
|
+
const lastComma = cleaned.lastIndexOf(",")
|
|
67
|
+
const decimalIdx = Math.max(lastDot, lastComma)
|
|
68
|
+
const intPart = cleaned.slice(0, decimalIdx).replace(/[.,]/g, "")
|
|
69
|
+
const decPart = cleaned.slice(decimalIdx + 1)
|
|
70
|
+
return Number(`${intPart}.${decPart}`)
|
|
71
|
+
}
|
|
72
|
+
if (hasDot) {
|
|
73
|
+
const parts = cleaned.split(".")
|
|
74
|
+
const allGroupsThree = parts.slice(1).every((p) => p.length === 3)
|
|
75
|
+
if (allGroupsThree) return Number(parts.join(""))
|
|
76
|
+
return Number(cleaned)
|
|
77
|
+
}
|
|
78
|
+
if (hasComma) {
|
|
79
|
+
const parts = cleaned.split(",")
|
|
80
|
+
const allGroupsThree = parts.slice(1).every((p) => p.length === 3)
|
|
81
|
+
if (allGroupsThree) return Number(parts.join(""))
|
|
82
|
+
return Number(cleaned.replace(",", "."))
|
|
83
|
+
}
|
|
84
|
+
return Number(cleaned)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export type { Cheerio, CheerioAPI }
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export class HttpToolError extends Error {
|
|
2
|
+
readonly _tag = "HttpToolError"
|
|
3
|
+
constructor(message: string, readonly status?: number, readonly body?: string) {
|
|
4
|
+
super(message)
|
|
5
|
+
this.name = "HttpToolError"
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const ensureOk = async (res: Response, label: string): Promise<Response> => {
|
|
10
|
+
if (res.ok) return res
|
|
11
|
+
const body = await res.text().catch(() => "")
|
|
12
|
+
throw new HttpToolError(`${label} ${res.status}: ${body.slice(0, 500)}`, res.status, body)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const fetchJson = async <T = unknown>(url: string, init?: RequestInit): Promise<T> => {
|
|
16
|
+
const res = await fetch(url, init)
|
|
17
|
+
await ensureOk(res, `GET ${url}`)
|
|
18
|
+
return (await res.json()) as T
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const postJson = async <T = unknown>(url: string, body: unknown, init?: RequestInit): Promise<T> => {
|
|
22
|
+
const headers = new Headers(init?.headers)
|
|
23
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json")
|
|
24
|
+
const res = await fetch(url, { method: "POST", body: JSON.stringify(body), ...init, headers })
|
|
25
|
+
await ensureOk(res, `POST ${url}`)
|
|
26
|
+
return (await res.json()) as T
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const fetchText = async (url: string, init?: RequestInit): Promise<string> => {
|
|
30
|
+
const res = await fetch(url, init)
|
|
31
|
+
await ensureOk(res, `GET ${url}`)
|
|
32
|
+
return res.text()
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const fetchBytes = async (url: string, init?: RequestInit): Promise<Uint8Array> => {
|
|
36
|
+
const res = await fetch(url, init)
|
|
37
|
+
await ensureOk(res, `GET ${url}`)
|
|
38
|
+
const buf = await res.arrayBuffer()
|
|
39
|
+
return new Uint8Array(buf)
|
|
40
|
+
}
|