@vipinsights/gemini-web-search-grounding 0.0.0-stage → 1.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/README.md CHANGED
@@ -1,3 +1,63 @@
1
- # Temporary Holding Version
1
+ # gemini-web-search-grounding
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+ ## Install
15
+
16
+ Requires Pi 1.5.0 or newer. Do not load it alongside `pi-web-search`; both register `web_search`.
17
+
18
+ ```bash
19
+ pi install npm:@vipinsights/gemini-web-search-grounding
20
+ ```
21
+
22
+ ## Replace the previous web search tool
23
+
24
+ 1. List installed packages and find the old one (e.g. `pi-web-search`):
25
+
26
+ ```bash
27
+ pi list
28
+ ```
29
+
30
+ 2. Remove it:
31
+
32
+ ```bash
33
+ pi remove npm:pi-web-search
34
+ ```
35
+
36
+ 3. Install this one:
37
+
38
+ ```bash
39
+ pi install npm:@vipinsights/gemini-web-search-grounding
40
+ ```
41
+
42
+ 4. Set `GEMINI_API_KEY`, restart Pi, and select a Gemini model.
43
+ 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.
44
+
45
+ ## Publish to npm
46
+
47
+ 1. Log in (once): `npm login`
48
+ 2. Confirm `name` and `version` in `package.json`; the name must be unused on npm.
49
+ 3. Run checks: `npm test && npm run typecheck`
50
+ 4. Preview the tarball: `npm pack --dry-run` (only `src` and `README.md` should ship)
51
+ 5. Publish: `npm publish --access public`
52
+ 6. Verify: `pi install npm:@vipinsights/gemini-web-search-grounding`
53
+ 7. For later releases: `npm version patch|minor|major`, then `npm publish --access public`
54
+
55
+ The `pi-package` keyword in `package.json` makes it discoverable as a Pi package.
56
+
57
+
58
+ ## Test
59
+
60
+ ```bash
61
+ npm test
62
+ npm run typecheck
63
+ ```
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@vipinsights/gemini-web-search-grounding",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.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 ADDED
@@ -0,0 +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
+ }
@@ -0,0 +1,95 @@
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
+
5
+ const TIMEOUT_MS = 60_000;
6
+
7
+ export const WebSearchSchema = Type.Object({
8
+ query: Type.String({ minLength: 1, description: "The search query or question to answer" }),
9
+ });
10
+ export type WebSearchInput = Static<typeof WebSearchSchema>;
11
+
12
+ type GeminiResponse = {
13
+ candidates?: Array<{
14
+ content?: { parts?: Array<{ text?: string; thought?: boolean }> };
15
+ finishReason?: string;
16
+ groundingMetadata?: {
17
+ webSearchQueries?: string[];
18
+ groundingChunks?: Array<{ web?: { uri?: string; title?: string } }>;
19
+ };
20
+ }>;
21
+ promptFeedback?: { blockReason?: string };
22
+ error?: { message?: string };
23
+ };
24
+
25
+ // Failures throw: pi reports a thrown error as a failed tool call (isError).
26
+ export async function webSearch(
27
+ params: WebSearchInput,
28
+ signal: AbortSignal | undefined,
29
+ ctx: ExtensionContext,
30
+ ): Promise<AgentToolResult<any>> {
31
+ const model = ctx.model;
32
+ if (model?.api !== "google-generative-ai") {
33
+ const current = model ? `${model.id} (${model.provider}/${model.api})` : "none";
34
+ throw new Error(`web_search requires a Gemini model (google-generative-ai). Current model: ${current}.`);
35
+ }
36
+
37
+ // Same env var pi uses for its own Gemini calls (GEMINI_API_KEY).
38
+ 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).`);
40
+
41
+ const baseUrl = (model.baseUrl ?? "").replace(/\/+$/, "");
42
+ const modelId = encodeURIComponent(model.id.replace(/^models\//, ""));
43
+ const timeout = AbortSignal.timeout(TIMEOUT_MS);
44
+ const res = await fetch(`${baseUrl}/models/${modelId}:generateContent`, {
45
+ method: "POST",
46
+ headers: { "Content-Type": "application/json", "x-goog-api-key": apiKey },
47
+ body: JSON.stringify({
48
+ contents: [{ role: "user", parts: [{ text: params.query }] }],
49
+ // The only tool enabled. No url_context.
50
+ tools: [{ google_search: {} }],
51
+ }),
52
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
53
+ });
54
+
55
+ const data = (await res.json().catch(() => ({}))) as GeminiResponse;
56
+ if (!res.ok) {
57
+ throw new Error(`web_search: Gemini ${res.status} ${data.error?.message ?? res.statusText}`);
58
+ }
59
+ if (data.promptFeedback?.blockReason) {
60
+ throw new Error(`web_search: blocked by Gemini (${data.promptFeedback.blockReason})`);
61
+ }
62
+
63
+ const candidate = data.candidates?.[0];
64
+ if (candidate?.finishReason && !["STOP", "MAX_TOKENS"].includes(candidate.finishReason)) {
65
+ throw new Error(`web_search: generation stopped by Gemini (${candidate.finishReason})`);
66
+ }
67
+
68
+ const answer = (candidate?.content?.parts ?? [])
69
+ .filter((part) => !part.thought)
70
+ .map((part) => part.text ?? "")
71
+ .join("")
72
+ .trim();
73
+ if (!answer) {
74
+ throw new Error(`web_search: empty response (finishReason: ${candidate?.finishReason ?? "unknown"})`);
75
+ }
76
+
77
+ const metadata = candidate?.groundingMetadata;
78
+ const seen = new Set<string>();
79
+ const sources: Array<{ title: string; url: string }> = [];
80
+ for (const chunk of metadata?.groundingChunks ?? []) {
81
+ const url = chunk.web?.uri;
82
+ if (!url || seen.has(url)) continue;
83
+ seen.add(url);
84
+ sources.push({ title: chunk.web?.title || url, url });
85
+ }
86
+
87
+ const sourceText = sources.length
88
+ ? "\n\nSources:\n" + sources.map((s, i) => `${i + 1}. ${s.title}: ${s.url}`).join("\n")
89
+ : "\n\n(No grounding sources returned.)";
90
+
91
+ return {
92
+ content: [{ type: "text", text: answer + sourceText }],
93
+ details: { modelId: model.id, queries: metadata?.webSearchQueries ?? [], sources },
94
+ };
95
+ }