AutoGPT icon indicating copy to clipboard operation
AutoGPT copied to clipboard

Command google returned: Error: 'list' object has no attribute 'encode'

Open codygao2020 opened this issue 1 year ago • 3 comments

Duplicates

  • [X] I have searched the existing issues

Steps to reproduce 🕹

After pulling the latest code, I can't use google to get information, and I get an error every time

NEXT ACTION: COMMAND = google ARGUMENTS = {'input': 'What are the latest news or developments in the Russo-Ukrainian war from reliable sources other than AP News?'} Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for ... Input:y -=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-= SYSTEM: Command google returned: Error: 'list' object has no attribute 'encode'

Current behavior 😯

SYSTEM: Command google returned: Error: 'list' object has no attribute 'encode'

Expected behavior 🤔

Get a list of google search results

Your prompt 📝

# Paste your prompt here

codygao2020 avatar Apr 15 '23 17:04 codygao2020

same.

mflanagan1041 avatar Apr 15 '23 17:04 mflanagan1041

+1

normen avatar Apr 15 '23 17:04 normen

I asked gtp-4 about it and pasted the code of the google_search.py. It actually managed to fix it lol. Here's what to paste (replace everything in the file):

`"""Google search command for Autogpt.""" import json from typing import List, Union

from duckduckgo_search import ddg

from autogpt.config import Config

CFG = Config()

def google_search(query: str, num_results: int = 8) -> str: """Return the results of a google search

Args:
    query (str): The search query.
    num_results (int): The number of results to return.

Returns:
    str: The results of the search.
"""
search_results = []
if not query:
    return json.dumps(search_results)

results = ddg(query, max_results=num_results)
if not results:
    return json.dumps(search_results)

for j in results:
    search_results.append(j)

return json.dumps(search_results, ensure_ascii=False, indent=4)

def google_official_search(query: str, num_results: int = 8) -> str: """Return the results of a google search using the official Google API

Args:
    query (str): The search query.
    num_results (int): The number of results to return.

Returns:
    str: The results of the search.
"""

from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

try:
    # Get the Google API key and Custom Search Engine ID from the config file
    api_key = CFG.google_api_key
    custom_search_engine_id = CFG.custom_search_engine_id

    # Initialize the Custom Search API service
    service = build("customsearch", "v1", developerKey=api_key)

    # Send the search query and retrieve the results
    result = (
        service.cse()
        .list(q=query, cx=custom_search_engine_id, num=num_results)
        .execute()
    )

    # Extract the search result items from the response
    search_results = result.get("items", [])

    # Create a list of only the URLs from the search results
    search_results_links = [item["link"] for item in search_results]

except HttpError as e:
    # Handle errors in the API call
    error_details = json.loads(e.content.decode())

    # Check if the error is related to an invalid or missing API key
    if error_details.get("error", {}).get(
        "code"
    ) == 403 and "invalid API key" in error_details.get("error", {}).get(
        "message", ""
    ):
        return "Error: The provided Google API key is invalid or missing."
    else:
        return f"Error: {e}"

# Join the list of search result URLs into a single string
result_string = "\n".join(search_results_links)

# Return the string of search result URLs
return result_string`

JOechoech avatar Apr 15 '23 19:04 JOechoech

def google_search(query: str, num_results: int = 8) -> str:

IndentationError: expected an indented block after function definition on line 11

MBrekhof avatar Apr 15 '23 22:04 MBrekhof

Fixing the formatting from @JOechoech 's comment, here's the correct spacing:

autogpt/commands/google_search.py:

"""Google search command for Autogpt."""
import json
from typing import List, Union

from duckduckgo_search import ddg

from autogpt.config import Config

CFG = Config()

def google_search(query: str, num_results: int = 8) -> str:
    """Return the results of a google search

    Args:
        query (str): The search query.
        num_results (int): The number of results to return.

    Returns:
        str: The results of the search.
    """
    search_results = []
    if not query:
        return json.dumps(search_results)

    results = ddg(query, max_results=num_results)
    if not results:
        return json.dumps(search_results)

    for j in results:
        search_results.append(j)

    return json.dumps(search_results, ensure_ascii=False, indent=4)

def google_official_search(query: str, num_results: int = 8) -> str:
    """Return the results of a google search using the official Google API

    Args:
        query (str): The search query.
        num_results (int): The number of results to return.

    Returns:
        str: The results of the search.
    """

    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError

    try:
        # Get the Google API key and Custom Search Engine ID from the config file
        api_key = CFG.google_api_key
        custom_search_engine_id = CFG.custom_search_engine_id

        # Initialize the Custom Search API service
        service = build("customsearch", "v1", developerKey=api_key)

        # Send the search query and retrieve the results
        result = (
            service.cse()
            .list(q=query, cx=custom_search_engine_id, num=num_results)
            .execute()
        )

        # Extract the search result items from the response
        search_results = result.get("items", [])

        # Create a list of only the URLs from the search results
        search_results_links = [item["link"] for item in search_results]

    except HttpError as e:
        # Handle errors in the API call
        error_details = json.loads(e.content.decode())

        # Check if the error is related to an invalid or missing API key
        if error_details.get("error", {}).get(
            "code"
        ) == 403 and "invalid API key" in error_details.get("error", {}).get(
            "message", ""
        ):
            return "Error: The provided Google API key is invalid or missing."
        else:
            return f"Error: {e}"

    # Join the list of search result URLs into a single string
    result_string = "\n".join(search_results_links)

    # Return the string of search result URLs
    return result_string

polds avatar Apr 15 '23 23:04 polds

Same on any COMMAND = google

@polds fix corrects the issue

Explorergt92 avatar Apr 16 '23 00:04 Explorergt92

https://github.com/Significant-Gravitas/Auto-GPT/pull/1698

TechnoTaff avatar Apr 16 '23 00:04 TechnoTaff

@polds awesome, thank you

duffercn avatar Apr 16 '23 01:04 duffercn

@polds awesome, thank you so much

Qiaogun avatar Apr 16 '23 09:04 Qiaogun

thank you all, signed in just to thank you :D

monokid avatar Apr 16 '23 12:04 monokid

Fixing the formatting from @JOechoech 's comment, here's the correct spacing:

autogpt/commands/google_search.py:

"""Google search command for Autogpt."""
import json
from typing import List, Union

from duckduckgo_search import ddg

from autogpt.config import Config

CFG = Config()

def google_search(query: str, num_results: int = 8) -> str:
    """Return the results of a google search

    Args:
        query (str): The search query.
        num_results (int): The number of results to return.

    Returns:
        str: The results of the search.
    """
    search_results = []
    if not query:
        return json.dumps(search_results)

    results = ddg(query, max_results=num_results)
    if not results:
        return json.dumps(search_results)

    for j in results:
        search_results.append(j)

    return json.dumps(search_results, ensure_ascii=False, indent=4)

def google_official_search(query: str, num_results: int = 8) -> str:
    """Return the results of a google search using the official Google API

    Args:
        query (str): The search query.
        num_results (int): The number of results to return.

    Returns:
        str: The results of the search.
    """

    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError

    try:
        # Get the Google API key and Custom Search Engine ID from the config file
        api_key = CFG.google_api_key
        custom_search_engine_id = CFG.custom_search_engine_id

        # Initialize the Custom Search API service
        service = build("customsearch", "v1", developerKey=api_key)

        # Send the search query and retrieve the results
        result = (
            service.cse()
            .list(q=query, cx=custom_search_engine_id, num=num_results)
            .execute()
        )

        # Extract the search result items from the response
        search_results = result.get("items", [])

        # Create a list of only the URLs from the search results
        search_results_links = [item["link"] for item in search_results]

    except HttpError as e:
        # Handle errors in the API call
        error_details = json.loads(e.content.decode())

        # Check if the error is related to an invalid or missing API key
        if error_details.get("error", {}).get(
            "code"
        ) == 403 and "invalid API key" in error_details.get("error", {}).get(
            "message", ""
        ):
            return "Error: The provided Google API key is invalid or missing."
        else:
            return f"Error: {e}"

    # Join the list of search result URLs into a single string
    result_string = "\n".join(search_results_links)

    # Return the string of search result URLs
    return result_string

nice!

Mandolilele avatar Apr 16 '23 14:04 Mandolilele

This is fixed in master

normen avatar Apr 16 '23 15:04 normen

still getting google search error NEXT ACTION: COMMAND = google ARGUMENTS = {'input': 'golf industry opportunities'} Enter 'y' to authorise command, 'y -N' to run N continuous commands, 'n' to exit program, or enter feedback for ... Input:y -=-=-=-=-=-=-= COMMAND AUTHORISED BY USER -=-=-=-=-=-=-= SYSTEM: Command google returned: Error: name: customsearch version: v1

pyfoo avatar Apr 19 '23 19:04 pyfoo

still getting this same error despite updating the google_search.py file as above. Has anyone else foudn another solution that works?

Error: Command google returned: Error: 'list' object has no attribute 'encode'

addyfizzle avatar May 03 '23 19:05 addyfizzle

I have the same issue too. Updated the google_search.py with the code of @polds but the [] is still empty

PaderRiders avatar May 22 '23 13:05 PaderRiders