-
Notifications
You must be signed in to change notification settings - Fork 1.5k
[FirebaseAI] Add usage of Grounding with Google Search #1724
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
dlarocque
wants to merge
13
commits into
main
Choose a base branch
from
dl/grounding
base: main
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.
+263
−29
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
15d6f04
[FirebaseAI] Add usage of Grounding with Google Search
dlarocque ec1c964
Add xcode project changes
dlarocque d9fe94d
remove app bar, user icon, candidate extension
dlarocque 8b176d1
style
dlarocque 9f02ca3
Refactor to improve reusability!
dlarocque 2c78802
set default model
dlarocque 5be4ca3
Merge branch 'main' into dl/grounding
dlarocque c9d86e0
Temporarily use `CocoaPods-12.0.0` branch for SPM dependency
andrewheard 99c1362
Temporarily use commit SHA before Analytics 12.0 for SPM dependency
andrewheard fb77255
Refactor
dlarocque 3db183b
Update grounding PR branch to use Firebase 12 release
paulb777 118ee3c
Merge pull request #1730 from firebase/pb-grounding-12
dlarocque 58580a7
Review fixes
dlarocque 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
79 changes: 79 additions & 0 deletions
79
firebaseai/ChatExample/Views/Grounding/GoogleSearchSuggestionView.swift
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,79 @@ | ||
// Copyright 2025 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
import SwiftUI | ||
import WebKit | ||
|
||
/// A view that renders Google Search suggestions with links that allow users | ||
/// to view the search results in the device's default browser. | ||
/// This is added to the bottom of chat messages containing results grounded | ||
/// in Google Search. | ||
struct GoogleSearchSuggestionView: UIViewRepresentable { | ||
dlarocque marked this conversation as resolved.
Show resolved
Hide resolved
|
||
let htmlString: String | ||
|
||
// This Coordinator class will act as the web view's navigation delegate. | ||
class Coordinator: NSObject, WKNavigationDelegate { | ||
func webView(_ webView: WKWebView, | ||
decidePolicyFor navigationAction: WKNavigationAction, | ||
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { | ||
// Check if the navigation was triggered by a user clicking a link. | ||
if navigationAction.navigationType == .linkActivated { | ||
if let url = navigationAction.request.url { | ||
// Open the URL in the system's default browser (e.g., Safari). | ||
UIApplication.shared.open(url) | ||
} | ||
// Cancel the navigation inside our small web view. | ||
decisionHandler(.cancel) | ||
return | ||
} | ||
// For all other navigation types (like the initial HTML load), allow it. | ||
decisionHandler(.allow) | ||
} | ||
} | ||
|
||
func makeCoordinator() -> Coordinator { | ||
Coordinator() | ||
} | ||
|
||
func makeUIView(context: Context) -> WKWebView { | ||
let webView = WKWebView() | ||
webView.isOpaque = false | ||
webView.backgroundColor = .clear | ||
webView.scrollView.backgroundColor = .clear | ||
webView.scrollView.isScrollEnabled = false | ||
// Set the coordinator as the navigation delegate. | ||
webView.navigationDelegate = context.coordinator | ||
return webView | ||
} | ||
|
||
func updateUIView(_ uiView: WKWebView, context: Context) { | ||
// The renderedContent is an HTML snippet with CSS. | ||
// For it to render correctly, we wrap it in a basic HTML document structure. | ||
let fullHTML = """ | ||
<!DOCTYPE html> | ||
<html> | ||
<head> | ||
<meta name='viewport' content='width=device-width, initial-scale=1.0, user-scalable=no'> | ||
<style> | ||
body { margin: 0; padding: 0; } | ||
</style> | ||
</head> | ||
<body> | ||
\(htmlString) | ||
</body> | ||
</html> | ||
""" | ||
uiView.loadHTMLString(fullHTML, baseURL: nil) | ||
} | ||
} |
81 changes: 81 additions & 0 deletions
81
firebaseai/ChatExample/Views/Grounding/GroundedResponseView.swift
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,81 @@ | ||
// Copyright 2023 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
import FirebaseAI | ||
import SwiftUI | ||
|
||
/// A view that displays a chat message that is grounded in Google Search. | ||
struct GroundedResponseView: View { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think it might be better to enhance ResponseTextView to provide a slot for an auxiliary view. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We can do that in a follow-up PR. |
||
var message: ChatMessage | ||
var groundingMetadata: GroundingMetadata | ||
|
||
var body: some View { | ||
// We can only display a response grounded in Google Search if the searchEntrypoint is non-nil. | ||
let isCompliant = (groundingMetadata.groundingChunks.isEmpty || groundingMetadata | ||
.searchEntryPoint != nil) | ||
if isCompliant { | ||
HStack(alignment: .top, spacing: 8) { | ||
VStack(alignment: .leading, spacing: 8) { | ||
// Message text | ||
ResponseTextView(message: message) | ||
|
||
if !groundingMetadata.groundingChunks.isEmpty { | ||
Divider() | ||
// Source links | ||
ForEach(0 ..< groundingMetadata.groundingChunks.count, id: \.self) { index in | ||
if let webChunk = groundingMetadata.groundingChunks[index].web { | ||
SourceLinkView( | ||
title: webChunk.title ?? "Untitled Source", | ||
uri: webChunk.uri | ||
) | ||
} | ||
} | ||
} | ||
// Search suggestions | ||
if let searchEntryPoint = groundingMetadata.searchEntryPoint { | ||
Divider() | ||
GoogleSearchSuggestionView(htmlString: searchEntryPoint.renderedContent) | ||
.frame(height: 44) | ||
.clipShape(RoundedRectangle(cornerRadius: 22)) | ||
} | ||
} | ||
} | ||
.frame(maxWidth: .infinity, alignment: .leading) | ||
} | ||
} | ||
} | ||
|
||
/// A view for a single, clickable source link. | ||
struct SourceLinkView: View { | ||
let title: String | ||
let uri: String? | ||
|
||
var body: some View { | ||
if let uri, let url = URL(string: uri) { | ||
Link(destination: url) { | ||
HStack(spacing: 4) { | ||
Image(systemName: "link") | ||
.font(.caption) | ||
.foregroundColor(.secondary) | ||
Text(title) | ||
.font(.footnote) | ||
.underline() | ||
.lineLimit(1) | ||
.multilineTextAlignment(.leading) | ||
} | ||
} | ||
.buttonStyle(.plain) | ||
} | ||
} | ||
} |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This equality operator is only here because
GroundingMetadata
doesn't conform toEquatable
. Since it's a rather complex type, I suggest simplifying this==
implementation to only check equality of theid
attribute. This is sufficient, since each chat message is uniquely identified by itsid
attribute.Let's also call this out:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If this implementation only compares the
id
's, won't the view not update if we update aChatMessage
field liketext
(for example, in a case where we are streaming a chat message, and updating thetext
field as each chunk arrives)?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think @dlarocque is right. As another example, if the equality check doesn't include
pending
then the following won't trigger:quickstart-ios/firebaseai/ChatExample/Screens/ConversationScreen.swift
Lines 52 to 72 in 0485eec
This results in
MessageContentView
showing the bouncing dots forever:quickstart-ios/firebaseai/ChatExample/Views/MessageView.swift
Lines 42 to 44 in 0485eec
How about we add
// TODO(andrewheard): Add Equatable conformance to GroundingMetadata and remove this
instead? AlthoughGroundingMetadata
is quite a complex type, all the leaf nodes are basic types so it's quite easy to make it conform and Apple actually recommends doing so:I think it's something we should consider for our APIs going forward.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good point - I think I got too used to how this works in the new world (with the Observable macro), where this does indeed work.
So we've got three options:
==
implementationGroundingMetadata
conforms toEquatable
Since not everybody will be able to use the new Observation framework, we should probably implement (2) in the short term, which also doesn't hurt once we're able to migrate to the Observation framework.