-
Notifications
You must be signed in to change notification settings - Fork 3.7k
feat: add grounding with google search #1084
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sedanah-m
wants to merge
7
commits into
master
Choose a base branch
from
feat/grounding-with-google-search
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
6456259
feat: add grounding with google search
sedanah-m 2e0af1e
fix: bug where extracting the uri, verifying its presence, and using …
sedanah-m 88fb638
fix: a few things:
sedanah-m 78d5c9d
fix: there was a bug where the google search suggestions wouldn't cli…
sedanah-m cf98ae9
add doc in comment
sedanah-m 4f68811
fix:
sedanah-m 0c896ec
add grounding with google search feature script to package.json
sedanah-m File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
140 changes: 140 additions & 0 deletions
140
ai/ai-samples/src/features/grounding-with-google-search/index.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| import { useState, useRef, useEffect } from 'react'; | ||
| import { generateGroundedContent, GroundedResult } from './service'; | ||
|
|
||
| /** | ||
| * Encapsulates the Google Search suggestions HTML/CSS within a Shadow DOM | ||
| * as documented in Firebase's SearchEntrypoint reference: | ||
| * container.attachShadow({ mode: 'open' }).innerHTML = renderedContent; | ||
| * (https://firebase.google.com/docs/reference/js/ai.searchentrypoint) | ||
| */ | ||
| function SearchSuggestionsWidget({ renderedContent }: { renderedContent: string }) { | ||
| const containerRef = useRef<HTMLDivElement>(null); | ||
|
|
||
| useEffect(() => { | ||
| if (!containerRef.current) return; | ||
| const shadowRoot = | ||
| containerRef.current.shadowRoot || | ||
| containerRef.current.attachShadow({ mode: 'open' }); | ||
| shadowRoot.innerHTML = renderedContent; | ||
| }, [renderedContent]); | ||
|
|
||
| return <div ref={containerRef} style={{ minHeight: '40px' }} />; | ||
| } | ||
|
|
||
| export default function GroundingWithGoogleSearchView() { | ||
| const [prompt, setPrompt] = useState('Who won the euro 2024?'); | ||
| const [result, setResult] = useState<GroundedResult | null>(null); | ||
| const [loading, setLoading] = useState(false); | ||
| const [error, setError] = useState<string | null>(null); | ||
|
|
||
| const handleGenerate = async () => { | ||
| const cleanedPrompt = prompt.trim(); | ||
|
|
||
| if (!cleanedPrompt) { | ||
| setError('Please enter a prompt.'); | ||
| return; | ||
| } | ||
|
|
||
| setLoading(true); | ||
| setError(null); | ||
| setResult(null); | ||
|
|
||
| try { | ||
| const data = await generateGroundedContent(cleanedPrompt); | ||
| setResult(data); | ||
| } catch (err: unknown) { | ||
| const message = err instanceof Error ? err.message : 'An error occurred during grounded generation.'; | ||
| setError(message); | ||
| } finally { | ||
| setLoading(false); | ||
| } | ||
| }; | ||
|
|
||
| const renderedContent = result?.groundingMetadata?.searchEntryPoint?.renderedContent; | ||
|
|
||
| const uniqueSources = Array.from( | ||
| new Map( | ||
| (result?.groundingMetadata?.groundingChunks ?? []) | ||
| .filter((chunk): chunk is { web: { uri: string; title?: string } } => Boolean(chunk.web?.uri)) | ||
| .map((chunk) => [chunk.web.uri, chunk.web]) | ||
| ).values() | ||
| ); | ||
|
|
||
| return ( | ||
| <div style={{ padding: '20px', maxWidth: '600px', margin: '0 auto' }}> | ||
| <h2>Grounding with Google Search</h2> | ||
| <p style={{ color: '#666', marginBottom: '20px' }}> | ||
| Connects Gemini to real-time Google Search to provide up-to-date answers and sources. | ||
| </p> | ||
|
|
||
| <div style={{ marginBottom: '15px' }}> | ||
| <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}> | ||
| Prompt: | ||
| </label> | ||
| <textarea | ||
| value={prompt} | ||
| onChange={(e) => setPrompt(e.target.value)} | ||
| rows={4} | ||
| style={{ width: '100%', padding: '8px', fontFamily: 'inherit' }} | ||
| /> | ||
| </div> | ||
|
|
||
| <button | ||
| onClick={handleGenerate} | ||
| disabled={loading} | ||
| style={{ | ||
| padding: '10px 20px', | ||
| cursor: loading ? 'not-allowed' : 'pointer', | ||
| backgroundColor: loading ? '#ccc' : '#007BFF', | ||
| color: '#fff', | ||
| border: 'none', | ||
| borderRadius: '4px', | ||
| }} | ||
| > | ||
| {loading ? 'Searching & Generating...' : 'Generate Grounded Content'} | ||
| </button> | ||
|
|
||
| {error && ( | ||
| <div style={{ color: '#D8000C', backgroundColor: '#FFD2D2', padding: '10px', marginTop: '15px', borderRadius: '4px' }}> | ||
| <strong>Error:</strong> {error} | ||
| </div> | ||
| )} | ||
|
|
||
| {result && ( | ||
| <div style={{ marginTop: '20px', borderTop: '1px solid #eee', paddingTop: '15px' }}> | ||
| <h3>Response:</h3> | ||
| <p style={{ whiteSpace: 'pre-wrap', lineHeight: '1.5' }}>{result.text}</p> | ||
|
|
||
| {/* REQUIRED COMPLIANCE: Display Google Search suggestions in Shadow DOM if returned */} | ||
| {renderedContent && ( | ||
| <div style={{ marginTop: '15px' }}> | ||
| <h4>Search Suggestions:</h4> | ||
| <SearchSuggestionsWidget renderedContent={renderedContent} /> | ||
| </div> | ||
| )} | ||
|
|
||
| {/* REQUIRED COMPLIANCE: Display sources */} | ||
| {uniqueSources.length > 0 && ( | ||
| <div style={{ marginTop: '15px' }}> | ||
| <h4>Sources:</h4> | ||
| <ul style={{ paddingLeft: '20px' }}> | ||
| {uniqueSources.map((source) => ( | ||
| <li key={source.uri} style={{ marginBottom: '4px' }}> | ||
| <a | ||
| href={source.uri} | ||
| target="_blank" | ||
| rel="noopener noreferrer" | ||
| style={{ color: '#007BFF' }} | ||
| > | ||
| {source.title || source.uri} | ||
| </a> | ||
| </li> | ||
| ))} | ||
| </ul> | ||
| </div> | ||
| )} | ||
| </div> | ||
| )} | ||
| </div> | ||
| ); | ||
| } |
33 changes: 33 additions & 0 deletions
33
ai/ai-samples/src/features/grounding-with-google-search/service.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| import { getAiModel } from '../../services/firebaseAIService'; | ||
| import { GroundingMetadata } from 'firebase/ai'; | ||
|
|
||
| export interface GroundedResult { | ||
| text: string; | ||
| groundingMetadata?: GroundingMetadata; | ||
| } | ||
|
|
||
| /** | ||
| * Generates grounded content using the Google Search tool. | ||
| * Connects the Gemini model to real-time web content for up-to-date answers, | ||
| * sources (groundingChunks), and compliant search suggestions (searchEntryPoint). | ||
| * @param prompt The string question or instruction sent to the model. | ||
| * @returns The text response and grounding metadata. | ||
| */ | ||
| export async function generateGroundedContent(prompt: string): Promise<GroundedResult> { | ||
| try { | ||
| const model = getAiModel('gemini-3.7-flash', { | ||
| tools: [{ googleSearch: {} }], | ||
| }); | ||
|
|
||
| const result = await model.generateContent(prompt); | ||
| const text = result.response.text(); | ||
| const groundingMetadata = result.response.candidates?.[0]?.groundingMetadata; | ||
|
|
||
| return { text, groundingMetadata }; | ||
| } catch (error: unknown) { | ||
| console.error('Error generating grounded content with Firebase AI:', error); | ||
| throw error instanceof Error | ||
| ? error | ||
| : new Error('An unknown error occurred during generation.'); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.