Skip to content
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

Using google search result to improve answer #285

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@
"react-markdown": "^8.0.4",
"rehype-highlight": "^6.0.0",
"swr": "^2.0.0",
"turndown": "^7.1.1",
"uuid": "^9.0.0"
},
"devDependencies": {
"@types/fs-extra": "^9.0.13",
"@types/lodash-es": "^4.17.6",
"@types/turndown": "^5.0.1",
"@types/uuid": "^9.0.0",
"@types/webextension-polyfill": "^0.9.2",
"@typescript-eslint/eslint-plugin": "^5.47.0",
Expand Down
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const userConfigWithDefaultValue = {
triggerMode: TriggerMode.Always,
theme: Theme.Auto,
language: Language.Auto,
googleSearch: true,
}

export type UserConfig = typeof userConfigWithDefaultValue
Expand Down
16 changes: 11 additions & 5 deletions src/content-script/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { detectSystemColorScheme } from '../utils'
import ChatGPTContainer from './ChatGPTContainer'
import { config, SearchEngine } from './search-engine-configs'
import './styles.scss'
import { getPossibleElementByQuerySelector } from './utils'
import { getGoogleSearchResult, getPossibleElementByQuerySelector } from './utils'

async function mount(question: string, siteConfig: SearchEngine) {
const container = document.createElement('div')
Expand Down Expand Up @@ -50,11 +50,17 @@ async function run() {
if (searchInput && searchInput.value) {
console.debug('Mount ChatGPT on', siteName)
const userConfig = await getUserConfig()
const searchValueWithLanguageOption =
let question = searchInput.value

if (userConfig.googleSearch) {
question = (await getGoogleSearchResult(question)) + `\n\nQuestion:\n """${question}"""`
}

question =
userConfig.language === Language.Auto
? searchInput.value
: `${searchInput.value}(in ${userConfig.language})`
mount(searchValueWithLanguageOption, siteConfig)
? question
: `Answer the question in ${userConfig.language}:\n\n ${question}`
mount(question, siteConfig)
}
}

Expand Down
29 changes: 29 additions & 0 deletions src/content-script/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import TurndownService from 'turndown'
import Browser from 'webextension-polyfill'

export function getPossibleElementByQuerySelector<T extends Element>(
Expand Down Expand Up @@ -32,3 +33,31 @@ export async function shouldShowRatingTip() {
await Browser.storage.local.set({ ratingTipShowTimes: ratingTipShowTimes + 1 })
return ratingTipShowTimes >= 2
}

export async function getGoogleSearchResult(question: string) {
let searchWithGoogle = ''
const googleUrl = `https://www.google.com/search?q=${question}`

try {
const response = await fetch(googleUrl)
const html = await response.text()
const parser = new DOMParser()
const doc = parser.parseFromString(html, 'text/html')
const resultDivs = doc.querySelectorAll('div.kvH3mc.BToiNc.UK95Uc')
const turndownService = new TurndownService()
const results = Array.from(resultDivs).map((resultDiv) =>
turndownService.turndown(resultDiv.innerHTML),
)
console.log(results)
searchWithGoogle = `
Use your knowledge and Web search to answer the question.

Web search results:
${results.join('\n')}
`
} catch (error) {
console.log(error)
}

return searchWithGoogle
}
19 changes: 19 additions & 0 deletions src/options/App.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { CssBaseline, GeistProvider, Radio, Select, Text, Toggle, useToasts } from '@geist-ui/core'
import { ToggleEvent } from '@geist-ui/core/esm/toggle'
import { capitalize } from 'lodash-es'
import { useCallback, useEffect, useMemo, useState } from 'preact/hooks'
import '../base.css'
Expand Down Expand Up @@ -52,6 +53,15 @@ function OptionsPage(props: { theme: Theme; onThemeChange: (theme: Theme) => voi
[setToast],
)

const onGoogleSearchChange = useCallback(
(event: ToggleEvent) => {
const googleSearch = event.target.checked
updateUserConfig({ googleSearch })
setToast({ text: 'Changes saved', type: 'success' })
},
[setToast],
)

return (
<div className="container mx-auto">
<nav className="flex flex-row justify-between items-center mt-5 px-2">
Expand Down Expand Up @@ -130,6 +140,15 @@ function OptionsPage(props: { theme: Theme; onThemeChange: (theme: Theme) => voi
</Select.Option>
))}
</Select>
<Text h3 className="mt-8">
Allow Google Results for ChatGPT
</Text>
<div className="flex flex-row items-center gap-4">
<Toggle initialChecked onChange={onGoogleSearchChange} />
<Text b margin={0}>
Allow ChatGPT to access some Google search data and have more up-to-date answers.
</Text>
</div>
<Text h3 className="mt-5 mb-0">
AI Provider
</Text>
Expand Down