Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/ai-sdk/src/limit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest"
import { clampSearchLimit } from "./tools"

describe("clampSearchLimit", () => {
it("keeps in-range integers", () => {
expect(clampSearchLimit(1)).toBe(1)
expect(clampSearchLimit(10)).toBe(10)
expect(clampSearchLimit(50)).toBe(50)
})

it("clamps huge and negative values into range", () => {
expect(clampSearchLimit(1e9)).toBe(50)
expect(clampSearchLimit(-5)).toBe(1)
expect(clampSearchLimit(0)).toBe(1)
})

it("floors fractional values", () => {
expect(clampSearchLimit(7.9)).toBe(7)
})

it("falls back to the default on non-numeric input", () => {
expect(clampSearchLimit(Number.NaN)).toBe(10)
expect(clampSearchLimit(undefined)).toBe(10)
expect(clampSearchLimit("12" as unknown as number)).toBe(12)
})
})
26 changes: 23 additions & 3 deletions packages/ai-sdk/src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ type AddMemoryInput = {
memory: string
}

/**
* Clamp a model-supplied result limit into the 1-50 range.
*
* The JSON schema already constrains well-behaved models, but
* prompt-injected or sloppy callers can still hand negative, fractional,
* or huge values straight into a metered API.
*/
export function clampSearchLimit(value: unknown): number {
const parsed = Number(value)
if (!Number.isFinite(parsed)) return 10
return Math.min(50, Math.max(1, Math.floor(parsed)))
}

/**
* Create Supermemory tools for AI SDK
*/
Expand All @@ -30,6 +43,10 @@ export function supermemoryTools(
) {
const client = new Supermemory({
apiKey,
// Bound tool-call latency: without a timeout a hung connection stalls
// the agent's execute() loop indefinitely.
timeout: 30_000,
maxRetries: 2,
...(config?.baseUrl ? { baseURL: config.baseUrl } : {}),
})

Expand All @@ -54,8 +71,10 @@ export function supermemoryTools(
default: true,
},
limit: {
type: "number",
description: "Maximum number of results to return",
type: "integer",
minimum: 1,
maximum: 50,
description: "Maximum number of results to return (1-50)",
default: 10,
},
},
Expand All @@ -67,10 +86,11 @@ export function supermemoryTools(
limit = 10,
}) => {
try {
const safeLimit = clampSearchLimit(limit)
const response = await client.search.execute({
q: informationToGet,
containerTags,
limit,
limit: safeLimit,
chunkThreshold: 0.6,
includeFullDocs,
})
Expand Down