search.ts 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. /**
  2. * The model-facing `web_search` tool: discover current information on the web.
  3. * Execution goes through `ctx.web` — this module owns only the model-facing
  4. * schema, argument validation, the result-count bound, and result formatting,
  5. * never provider selection or network access.
  6. */
  7. import type { Context } from 'cordis'
  8. import { defineTool } from '@deepseek-ai/dsh-tools'
  9. import type { GenericCallView } from '@deepseek-ai/dsh-tools'
  10. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  11. import type { WebSearchResult } from '@deepseek-ai/dsh-web'
  12. import type {} from '@deepseek-ai/dsh-system-prompt'
  13. /**
  14. * Default upper bound on returned sources (the `searchMaxResults` config).
  15. * Owned by the consumer (not the provider or model), mirroring `dsh-tool-fs`'s
  16. * `READ_LIMIT`. The model just asks a question; the product controls how much
  17. * context returns. The default `8` aligns with OpenCode's Exa default.
  18. */
  19. export const WEB_SEARCH_MAX_RESULTS = 8
  20. /**
  21. * Validate value constraints the schema DSL can't express: a non-blank
  22. * `query`. Throws a plain `Error` otherwise.
  23. *
  24. * @param args - the schema-validated `web_search` arguments.
  25. * @returns the accepted arguments, passed through unchanged.
  26. */
  27. export function parseSearchArgs(args: { query: string }): { query: string } {
  28. if (args.query.trim().length === 0) throw new Error('query must be a non-empty string')
  29. return { query: args.query }
  30. }
  31. /** Display label for a source: its title, else its hostname. */
  32. function sourceLabel(url: string, title: string | undefined): string {
  33. if (title !== undefined && title.length > 0) return title
  34. try {
  35. return new URL(url).hostname
  36. } catch {
  37. // A provider should return a valid URL, but never let a malformed one throw
  38. // out of pure formatting — fall back to the raw string.
  39. return url
  40. }
  41. }
  42. /**
  43. * Format a search result as one model-facing text block.
  44. *
  45. * @param result - the seam's search outcome.
  46. * @returns the provider answer (when any), a markdown source list with snippet
  47. * and date metadata (or `No results found.`), a refine-the-query note when
  48. * truncated, and a standing cite-your-sources instruction.
  49. */
  50. export function formatSearchOutput(result: WebSearchResult): string {
  51. const parts: string[] = []
  52. if (result.content !== undefined && result.content.length > 0) parts.push(result.content)
  53. if (result.sources.length > 0) {
  54. const lines = result.sources.map((source) => {
  55. const label = sourceLabel(source.url, source.title)
  56. const meta: string[] = []
  57. if (source.snippet !== undefined && source.snippet.length > 0) meta.push(source.snippet)
  58. if (source.publishedAt !== undefined && source.publishedAt.length > 0) meta.push(`(${source.publishedAt})`)
  59. const suffix = meta.length > 0 ? ` — ${meta.join(' ')}` : ''
  60. return `- [${label}](${source.url})${suffix}`
  61. })
  62. parts.push(`Sources:\n${lines.join('\n')}`)
  63. } else if (result.content === undefined || result.content.length === 0) {
  64. parts.push('No results found.')
  65. }
  66. if (result.truncated) parts.push(`(Showing the first ${result.sources.length} sources. Refine the query for more.)`)
  67. parts.push('Cite the relevant URLs above as markdown links in your answer.')
  68. return parts.join('\n\n')
  69. }
  70. /**
  71. * Pending-call presentation: a search card titled by the query.
  72. *
  73. * @param args - the raw tool arguments; only `query` feeds the view.
  74. * @returns the generic card view (`kind: 'search'`) shown while the call runs.
  75. */
  76. export function presentSearchCall(args: { query: string }): GenericCallView {
  77. return { card: 'generic', title: args.query, kind: 'search', rawInput: args.query }
  78. }
  79. /**
  80. * Register the `web_search` tool and its system-prompt guidance.
  81. *
  82. * @param ctx - context whose `tools` and `systemPrompt` registries receive the
  83. * registrations; both are effect-scoped and unregister on plugin dispose.
  84. * @param maxResults - the deployment's source cap, sent as every seam
  85. * request's `maxResults`.
  86. * @param timeoutMs - the cooperative tool-call budget (ms) attached as the tool's
  87. * `ToolDefinition.timeoutMs` for `@deepseek-ai/dsh-timeout-policy` to enforce.
  88. */
  89. export function applyWebSearchTool(ctx: Context, maxResults: number, timeoutMs: number): void {
  90. ctx.systemPrompt.section({
  91. name: 'tool:web_search',
  92. order: 110,
  93. text: 'Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links.',
  94. })
  95. ctx.tools.register(defineTool({
  96. name: 'web_search',
  97. description: 'Search the web for current information. Returns an optional summary answer and a list of source URLs.',
  98. parameters: {
  99. query: { type: 'string', required: true, description: 'The search query.' },
  100. },
  101. timeoutMs,
  102. // Provider reads do not mutate parent-agent state.
  103. isConcurrencySafe: () => true,
  104. async execute(args, exec): Promise<ContentBlock[]> {
  105. const input = parseSearchArgs(args)
  106. const result = await ctx.web.search(
  107. { query: input.query, maxResults },
  108. exec.signal,
  109. )
  110. return [{ type: 'text', text: formatSearchOutput(result) }]
  111. },
  112. presentCall: presentSearchCall,
  113. }))
  114. }