@vipinsights/gemini-web-search-grounding 1.0.0 → 1.2.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/README.md CHANGED
@@ -1,61 +1,81 @@
1
- # gemini-web-search-grounding
2
-
3
- Minimal `web_search` tool for [pi](https://pi.dev) using Gemini's Grounding with Google Search. Derived from [ttttmr/pi-web-search](https://github.com/ttttmr/pi-web-search) (MIT).
4
-
5
- ## Scope
6
-
7
- - One tool: `web_search(query)`. Returns a grounded answer plus source links.
8
- - Gemini only: runs on pi's current model, and only when it uses the `google-generative-ai` API. Any other model returns an error.
9
- - Auth: the env var pi uses for Gemini (`GEMINI_API_KEY`). No `/login` credentials, no config files.
10
- - No `url_context`, no URL parameters, no URL fetching, no other vendors.
11
-
12
- ## Install
13
-
14
- Requires Pi 1.5.0 or newer. Do not load it alongside `pi-web-search`; both register `web_search`.
15
-
16
- ```bash
17
- pi install npm:gemini-web-search-grounding
18
- ```
19
-
20
- ## Replace the previous web search tool
21
-
22
- 1. List installed packages and find the old one (e.g. `pi-web-search`):
23
-
24
- ```bash
25
- pi list
26
- ```
27
-
28
- 2. Remove it:
29
-
30
- ```bash
31
- pi remove npm:pi-web-search
32
- ```
33
-
34
- 3. Install this one:
35
-
36
- ```bash
37
- pi install npm:gemini-web-search-grounding
38
- ```
39
-
40
- 4. Set `GEMINI_API_KEY`, restart Pi, and select a Gemini model.
41
- 5. If `web_search` is still registered twice, check `packages` and `extensions` in `~/.pi/agent/settings.json` (and the project's `.pi/settings.json`) for leftover `pi-web-search` entries and delete them.
42
-
43
- ## Publish to npm
44
-
45
- 1. Log in (once): `npm login`
46
- 2. Confirm `name` and `version` in `package.json`; the name must be unused on npm.
47
- 3. Run checks: `npm test && npm run typecheck`
48
- 4. Preview the tarball: `npm pack --dry-run` (only `src` and `README.md` should ship)
49
- 5. Publish: `npm publish` (add `--access public` for a scoped name like `@vtinfo/...`)
50
- 6. Verify: `pi install npm:gemini-web-search-grounding`
51
- 7. For later releases: `npm version patch|minor|major`, then `npm publish`
52
-
53
- The `pi-package` keyword in `package.json` makes it discoverable as a Pi package.
54
-
55
-
56
- ## Test
57
-
58
- ```bash
59
- npm test
60
- npm run typecheck
61
- ```
1
+ # gemini-web-search-grounding
2
+
3
+ Minimal `web_search` tool for [pi](https://pi.dev) using Gemini's Grounding with Google Search. Derived from [ttttmr/pi-web-search](https://github.com/ttttmr/pi-web-search) (MIT).
4
+
5
+ https://www.npmjs.com/package/@vipinsights/gemini-web-search-grounding
6
+
7
+ ## Scope
8
+
9
+ - One tool: `web_search(query)`. Returns a grounded answer plus source links.
10
+ - Gemini only: runs on pi's current model, and only when it uses the `google-generative-ai` API. Any other model returns an error.
11
+ - Auth: the env var pi uses for Gemini (`GEMINI_API_KEY`). No `/login` credentials, no config files.
12
+ - No `url_context`, no URL parameters, no URL fetching, no other vendors.
13
+
14
+ ## How it works
15
+
16
+ The search is Gemini's own built-in [Grounding with Google Search](https://ai.google.dev/gemini-api/docs/google-search) tool, not a separate search API.
17
+
18
+ - One `generateContent` call to pi's current Gemini model, with `tools: [{google_search: {}}]` as the only tool.
19
+ - The request holds just the query string: no system prompt, chat history, or files.
20
+ - Gemini runs the Google searches server-side and answers from the results.
21
+ - Sources come from the response's `groundingMetadata` (`webSearchQueries`, `groundingChunks`).
22
+
23
+ ## Configuration
24
+
25
+ Search calls reuse pi's current model, but with their own thinking level and timeout.
26
+
27
+ | Env var | Default | Purpose |
28
+ | --- | --- | --- |
29
+ | `WEB_SEARCH_THINKING_LEVEL` | `low` | `minimal`/`low`/`medium`/`high`; set to empty for Gemini 2.5 models, which reject it |
30
+ | `WEB_SEARCH_TIMEOUT_MS` | `15000` | Search timeout; no retries |
31
+
32
+ ## Install
33
+
34
+ Requires Pi 1.5.0 or newer. Do not load it alongside `pi-web-search`; both register `web_search`.
35
+
36
+ ```bash
37
+ pi install npm:@vipinsights/gemini-web-search-grounding
38
+ ```
39
+
40
+ ## Replace the previous web search tool
41
+
42
+ 1. List installed packages and find the old one (e.g. `pi-web-search`):
43
+
44
+ ```bash
45
+ pi list
46
+ ```
47
+
48
+ 2. Remove it:
49
+
50
+ ```bash
51
+ pi remove npm:pi-web-search
52
+ ```
53
+
54
+ 3. Install this one:
55
+
56
+ ```bash
57
+ pi install npm:@vipinsights/gemini-web-search-grounding
58
+ ```
59
+
60
+ 4. Set `GEMINI_API_KEY`, restart Pi, and select a Gemini model.
61
+ 5. If `web_search` is still registered twice, check `packages` and `extensions` in `~/.pi/agent/settings.json` (and the project's `.pi/settings.json`) for leftover `pi-web-search` entries and delete them.
62
+
63
+ ## Publish to npm
64
+
65
+ 1. Log in (once): `npm login`
66
+ 2. Confirm `name` and `version` in `package.json`; the name must be unused on npm.
67
+ 3. Run checks: `npm test && npm run typecheck`
68
+ 4. Preview the tarball: `npm pack --dry-run` (only `src` and `README.md` should ship)
69
+ 5. Publish: `npm publish --access public`
70
+ 6. Verify: `pi install npm:@vipinsights/gemini-web-search-grounding`
71
+ 7. For later releases: `npm version patch|minor|major`, then `npm publish --access public`
72
+
73
+ The `pi-package` keyword in `package.json` makes it discoverable as a Pi package.
74
+
75
+
76
+ ## Test
77
+
78
+ ```bash
79
+ npm test
80
+ npm run typecheck
81
+ ```
package/package.json CHANGED
@@ -1,43 +1,46 @@
1
- {
2
- "name": "@vipinsights/gemini-web-search-grounding",
3
- "version": "1.0.0",
4
- "description": "Minimal web_search for pi using Gemini's Grounding with Google Search. Gemini models only; no URL fetching.",
5
- "type": "module",
6
- "main": "src/index.ts",
7
- "keywords": [
8
- "pi",
9
- "pi-extension",
10
- "pi-package",
11
- "web-search",
12
- "gemini",
13
- "google",
14
- "grounding"
15
- ],
16
- "author": "vipinsights",
17
- "license": "MIT",
18
- "files": [
19
- "src",
20
- "README.md"
21
- ],
22
- "scripts": {
23
- "test": "node --test tests/*.test.mjs",
24
- "typecheck": "tsc --noEmit"
25
- },
26
- "devDependencies": {
27
- "@earendil-works/pi-ai": "^1.5.0",
28
- "@earendil-works/pi-coding-agent": "^1.5.0",
29
- "@types/node": "^25.9.1",
30
- "typebox": "^1.1.38",
31
- "typescript": "^6.0.3"
32
- },
33
- "pi": {
34
- "extensions": [
35
- "./src/index.ts"
36
- ]
37
- },
38
- "peerDependencies": {
39
- "@earendil-works/pi-ai": ">=1.5.0",
40
- "@earendil-works/pi-coding-agent": ">=1.5.0",
41
- "typebox": "*"
42
- }
43
- }
1
+ {
2
+ "name": "@vipinsights/gemini-web-search-grounding",
3
+ "version": "1.2.0",
4
+ "description": "Minimal web_search for pi using Gemini's Grounding with Google Search. Gemini models only; no URL fetching.",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "keywords": [
8
+ "pi",
9
+ "pi-extension",
10
+ "pi-package",
11
+ "web-search",
12
+ "gemini",
13
+ "google",
14
+ "grounding"
15
+ ],
16
+ "author": "vipinsights",
17
+ "license": "MIT",
18
+ "files": [
19
+ "src",
20
+ "README.md"
21
+ ],
22
+ "scripts": {
23
+ "test": "node --test tests/*.test.mjs",
24
+ "typecheck": "tsc --noEmit"
25
+ },
26
+ "engines": {
27
+ "node": ">=24.0.0"
28
+ },
29
+ "devDependencies": {
30
+ "@earendil-works/pi-ai": "^1.5.0",
31
+ "@earendil-works/pi-coding-agent": "^1.5.0",
32
+ "@types/node": "^25.9.1",
33
+ "typebox": "^1.1.38",
34
+ "typescript": "^6.0.3"
35
+ },
36
+ "pi": {
37
+ "extensions": [
38
+ "./src/index.ts"
39
+ ]
40
+ },
41
+ "peerDependencies": {
42
+ "@earendil-works/pi-ai": ">=1.5.0",
43
+ "@earendil-works/pi-coding-agent": ">=1.5.0",
44
+ "typebox": "*"
45
+ }
46
+ }
package/src/index.ts CHANGED
@@ -1,12 +1,12 @@
1
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
- import { webSearch, WebSearchSchema } from "./web_search.ts";
3
-
4
- export default function (pi: ExtensionAPI) {
5
- pi.registerTool({
6
- name: "web_search",
7
- label: "Web Search",
8
- description: "Search the web with Google Search grounding via the current Gemini model. Returns an answer with source links. Does not fetch or read specific URLs.",
9
- parameters: WebSearchSchema,
10
- execute: (_id, params, signal, _onUpdate, ctx) => webSearch(params, signal, ctx),
11
- });
12
- }
1
+ import type {ExtensionAPI} from "@earendil-works/pi-coding-agent";
2
+ import {webSearch, WebSearchSchema} from "./web_search.ts";
3
+
4
+ export default function (pi: ExtensionAPI) {
5
+ pi.registerTool({
6
+ name: "web_search",
7
+ label: "Web Search",
8
+ description: "Search the web with Google Search grounding via the current Gemini model. Returns an answer with source links. Does not fetch or read specific URLs. Use a plain natural-language question; avoid stacking exact-quoted phrases or OR operators, which tend to find nothing and time out.",
9
+ parameters: WebSearchSchema,
10
+ execute: (_id, params, signal, _onUpdate, ctx) => webSearch(params, signal, ctx),
11
+ });
12
+ }
package/src/web_search.ts CHANGED
@@ -1,11 +1,14 @@
1
- import type { AgentToolResult, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { getEnvApiKey } from "@earendil-works/pi-ai/compat";
3
- import { Type, type Static } from "typebox";
1
+ import type {AgentToolResult, ExtensionContext} from "@earendil-works/pi-coding-agent";
2
+ import {getEnvApiKey} from "@earendil-works/pi-ai/compat";
3
+ import {Type, type Static} from "typebox";
4
4
 
5
- const TIMEOUT_MS = 60_000;
5
+ // A search lookup does not need the agent's own (often high) thinking level; low keeps a grounded
6
+ // search well under the timeout.
7
+ const DEFAULT_THINKING_LEVEL = "low";
8
+ const DEFAULT_TIMEOUT_MS = 15_000;
6
9
 
7
10
  export const WebSearchSchema = Type.Object({
8
- query: Type.String({ minLength: 1, description: "The search query or question to answer" }),
11
+ query: Type.String({minLength: 1, description: "The search query or question to answer"}),
9
12
  });
10
13
  export type WebSearchInput = Static<typeof WebSearchSchema>;
11
14
 
@@ -22,6 +25,15 @@ type GeminiResponse = {
22
25
  error?: { message?: string };
23
26
  };
24
27
 
28
+ function settings() {
29
+ const timeout = Number(process.env.WEB_SEARCH_TIMEOUT_MS);
30
+ return {
31
+ // Empty string omits thinkingConfig, which Gemini 2.5 models need (they reject thinkingLevel).
32
+ thinkingLevel: process.env.WEB_SEARCH_THINKING_LEVEL ?? DEFAULT_THINKING_LEVEL,
33
+ timeoutMs: Number.isInteger(timeout) && timeout > 0 ? timeout : DEFAULT_TIMEOUT_MS,
34
+ };
35
+ }
36
+
25
37
  // Failures throw: pi reports a thrown error as a failed tool call (isError).
26
38
  export async function webSearch(
27
39
  params: WebSearchInput,
@@ -36,16 +48,22 @@ export async function webSearch(
36
48
 
37
49
  // Same env var pi uses for its own Gemini calls (GEMINI_API_KEY).
38
50
  const apiKey = getEnvApiKey(model.provider);
39
- if (!apiKey) throw new Error(`web_search: set the environment variable pi uses for provider "${model.provider}" (GEMINI_API_KEY).`);
51
+ if (!apiKey) {
52
+ throw new Error(`web_search: set the environment variable pi uses for provider "${model.provider}" (GEMINI_API_KEY).`);
53
+ }
40
54
 
41
- const timeout = AbortSignal.timeout(TIMEOUT_MS);
42
- const res = await fetch(`${model.baseUrl}/models/${encodeURIComponent(model.id)}:generateContent`, {
55
+ const {thinkingLevel, timeoutMs} = settings();
56
+ const baseUrl = (model.baseUrl ?? "").replace(/\/+$/, "");
57
+ const modelId = encodeURIComponent(model.id.replace(/^models\//, ""));
58
+ const timeout = AbortSignal.timeout(timeoutMs);
59
+ const res = await fetch(`${baseUrl}/models/${modelId}:generateContent`, {
43
60
  method: "POST",
44
- headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
61
+ headers: {"Content-Type": "application/json", "x-goog-api-key": apiKey},
45
62
  body: JSON.stringify({
46
- contents: [{ role: "user", parts: [{ text: params.query }] }],
63
+ contents: [{role: "user", parts: [{text: params.query}]}],
47
64
  // The only tool enabled. No url_context.
48
- tools: [{ google_search: {} }],
65
+ tools: [{google_search: {}}],
66
+ ...(thinkingLevel ? {generationConfig: {thinkingConfig: {thinkingLevel}}} : {}),
49
67
  }),
50
68
  signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
51
69
  });
@@ -59,6 +77,10 @@ export async function webSearch(
59
77
  }
60
78
 
61
79
  const candidate = data.candidates?.[0];
80
+ if (candidate?.finishReason && !["STOP", "MAX_TOKENS"].includes(candidate.finishReason)) {
81
+ throw new Error(`web_search: generation stopped by Gemini (${candidate.finishReason})`);
82
+ }
83
+
62
84
  const answer = (candidate?.content?.parts ?? [])
63
85
  .filter((part) => !part.thought)
64
86
  .map((part) => part.text ?? "")
@@ -73,9 +95,11 @@ export async function webSearch(
73
95
  const sources: Array<{ title: string; url: string }> = [];
74
96
  for (const chunk of metadata?.groundingChunks ?? []) {
75
97
  const url = chunk.web?.uri;
76
- if (!url || seen.has(url)) continue;
98
+ if (!url || seen.has(url)) {
99
+ continue;
100
+ }
77
101
  seen.add(url);
78
- sources.push({ title: chunk.web?.title || url, url });
102
+ sources.push({title: chunk.web?.title || url, url});
79
103
  }
80
104
 
81
105
  const sourceText = sources.length
@@ -83,7 +107,7 @@ export async function webSearch(
83
107
  : "\n\n(No grounding sources returned.)";
84
108
 
85
109
  return {
86
- content: [{ type: "text", text: answer + sourceText }],
87
- details: { modelId: model.id, queries: metadata?.webSearchQueries ?? [], sources },
110
+ content: [{type: "text", text: answer + sourceText}],
111
+ details: {modelId: model.id, queries: metadata?.webSearchQueries ?? [], sources},
88
112
  };
89
113
  }