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

feat: Linkup intergrate #1368

Merged
merged 8 commits into from
Dec 29, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
76 changes: 75 additions & 1 deletion camel/toolkits/search_toolkit.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
import os
import xml.etree.ElementTree as ET
from typing import Any, Dict, List, Optional, TypeAlias, Union
from typing import Any, Dict, List, Literal, Optional, Type, TypeAlias, Union

import requests
from pydantic import BaseModel

from camel.toolkits.base import BaseToolkit
from camel.toolkits.function_tool import FunctionTool
Expand Down Expand Up @@ -63,6 +64,78 @@ def search_wiki(self, entity: str) -> str:

return result

@dependencies_required("linkup")
@api_keys_required("LINKUP_API_KEY")
def search_linkup(
self,
query: str,
depth: Literal["standard", "deep"] = "standard",
output_type: Literal[
"searchResults", "sourcedAnswer", "structured"
] = "searchResults",
structured_output_schema: Union[Type[BaseModel], str, None] = None,
) -> Dict[str, Any]:
r"""Search for a query in the Linkup API and return results in various
formats.

Args:
query (str): The search query.
depth (Literal["standard", "deep"]): The depth of the search.
"standard" for a straightforward search, "deep" for a more
comprehensive search.
output_type (Literal["searchResults", "sourcedAnswer",
"structured"]): The type of output:
- "searchResults" for raw search results,
- "sourcedAnswer" for an answer with supporting sources,
- "structured" for output based on a provided schema.
structured_output_schema (Union[Type[BaseModel], str, None]): If
`output_type` is "structured",specify the schema of the
output. Can be a Pydantic BaseModel or a JSON schema string.

Returns:
Dict[str, Any]: A dictionary representing the search result. The
structure depends on the `output_type`. If an error occurs,
returns an error message.
"""
try:
from linkup import LinkupClient

# Initialize the Linkup client with the API key
LINKUP_API_KEY = os.getenv("LINKUP_API_KEY")
client = LinkupClient(api_key=LINKUP_API_KEY)

# Perform the search using the specified output_type
response = client.search(
query=query,
depth=depth,
output_type=output_type,
structured_output_schema=structured_output_schema,
)

if output_type == "searchResults":
results = [
item.__dict__
for item in response.__dict__.get('results', [])
]
return {"results": results}

elif output_type == "sourcedAnswer":
answer = response.__dict__.get('answer', '')
sources = [
item.__dict__
for item in response.__dict__.get('sources', [])
]
return {"answer": answer, "sources": sources}

elif output_type == "structured" and structured_output_schema:
return response.__dict__

else:
return {"error": f"Invalid output_type: {output_type}"}

except Exception as e:
return {"error": f"An unexpected error occurred: {e!s}"}

@dependencies_required("duckduckgo_search")
def search_duckduckgo(
self, query: str, source: str = "text", max_results: int = 5
Expand Down Expand Up @@ -618,6 +691,7 @@ def get_tools(self) -> List[FunctionTool]:
"""
return [
FunctionTool(self.search_wiki),
FunctionTool(self.search_linkup),
FunctionTool(self.search_google),
FunctionTool(self.search_duckduckgo),
FunctionTool(self.query_wolfram_alpha),
Expand Down
126 changes: 126 additions & 0 deletions examples/toolkits/search_toolkit.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
# limitations under the License.
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========

from pydantic import BaseModel

from camel.agents import ChatAgent
from camel.toolkits import FunctionTool, SearchToolkit

Expand Down Expand Up @@ -87,3 +89,127 @@
You can visit these links to get the most up-to-date temperature and weather
conditions in Tokyo.
'''

search_linkup_response = SearchToolkit().search_linkup(
query="Can you tell me which women were awared the Physics Nobel Prize",
depth="standard",
output_type="searchResults",
)

print(search_linkup_response)
"""
{'results': [{'type': 'text', 'name': 'Physics Nobel Prizes awarded to women |
Scientia News', 'url': 'https://www.scientianews.org/
physics-nobel-prize-winners', 'content': 'The next female Nobel Prize in
Physics award winner wouldn't be until another half-century later, with Donna
Strickland. Strickland was awarded the Prize for her work on chirped pulse
amplification and its applications. Although the research itself was published
in 1985, she didn't receive the award until 2018.'}, {'type': 'text', 'name':
'The 60 Women Who Have Won the Nobel Prize - Stacker', 'url': 'https://stacker.
com/history/60-women-who-have-won-nobel-prize', 'content': '- Award: Nobel
Prize in Physics - Year: 1963. Maria Goeppert-Mayer was born in Germany. After
she married, she migrated to America, where she worked on an American atom
bomb project during World War II. Her work uncovered important discoveries
about nuclear structure, and Goeppert-Mayer is one of only four women to win
the Nobel Prize in physics.'}, {'type': 'text', 'name': 'Nobel Prize awarded
women - NobelPrize.org', 'url': 'https://www.nobelprize.org/prizes/lists/
nobel-prize-awarded-women/', 'content': 'The Nobel Prize and the Sveriges
Riksbank Prize in Economic Sciences in Memory of Alfred Nobel have been
awarded to women 66 times between 1901 and 2024. Only one woman, Marie Curie,
has been honoured twice, with the Nobel Prize in Physics 1903 and the Nobel
Prize in Chemistry 1911. This means that 65 women in total have been awarded
the Nobel ...'}, {'type': 'text', 'name': 'Women who changed science - The
Nobel Prize', 'url': 'https://www.nobelprize.org/womenwhochangedscience/
stories', 'content': 'Nobel Prize in Physics 1903 Nobel Prize in Chemistry
1911. MARIE CURIE. Read her story. Nobel Prize in Physiology or Medicine 1988.
GERTRUDE B. ELION. Read her story. Nobel Prize in Physiology or Medicine 1988.
GERTRUDE B. ELION. Read her story. Nobel Prize in Physics 1963. MARIA GOEPPERT
MAYER. Read her story.'}, {'type': 'text', 'name': 'List of female Nobel
laureates - Wikipedia', 'url': 'https://en.wikipedia.org/wiki/
List_of_female_Nobel_laureates', 'content': "The most recent women to be
awarded a Nobel Prize were Han Kang in Literature (2024), Claudia Goldin in
Economics, Narges Mohammadi for Peace, Anne L'Huillier in Physics and Katalin
Karikó in Physiology or Medicine (2023), Annie Ernaux in Literature and
Carolyn R. Bertozzi for Chemistry (2022), Maria Ressa for Peace (2021), Louise
Glück in ..."}, {'type': 'text', 'name': 'Only 5 women have won the Nobel
Prize in physics—recent winners share ...', 'url': 'https://phys.org/news/
2024-10-women-won-nobel-prize-physics.html', 'content': 'Out of 225 people
awarded the Nobel Prize in physics, only five have been women. This is a very
small number, and certainly smaller than 50%—the percent of women in the human
population.'}, {'type': 'text', 'name': 'All These Women Won Science Nobel
Prizes - The Stemettes Zine', 'url': 'https://stemettes.org/zine/articles/
nobel-prize-women/', 'content': 'Currently, only 17% of Nobel Prize winners
are women in the Science categories. So here we are celebrating all the
amazing women who have Nobel Prizes for their Science research. ... & Physics
(1903) Marie and her husband were awarded the Nobel Prize for Physics in 1903,
for their study into the spontaneous radiation discovered by Becquerel. In ...
'}, {'type': 'text', 'name': 'These Are the 57 Women Who Have Won the Nobel
Prize', 'url': 'https://www.newsweek.com/
these-are-57-women-who-have-won-nobel-prize-1538702', 'content': 'Getty Images/
Hulton-Deutsch Collection/CORBIS Marie Curie (born Skłodowska) - Award: Nobel
Prize in Physics - Year: 1903. Marie Curie, who was the first woman to win a
Nobel Prize, coined the ...'}, {'type': 'text', 'name': 'Anne L'Huillier -
Banquet speech - NobelPrize.org', 'url': 'https://www.nobelprize.org/prizes/
physics/2023/lhuillier/speech/', 'content': 'The Nobel Prize in Physics 2023
was awarded to Pierre Agostini, Ferenc Krausz and Anne L'Huillier "for
experimental methods that generate attosecond pulses of light for the study of
electron dynamics in matter" ... 120 years ago, Marie Skłodowska Curie was the
first woman to be awarded the Nobel Prize in Physics. I am the fifth. For
more ...'}, {'type': 'text', 'name': 'Facts on the Nobel Prize in Physics -
NobelPrize.org', 'url': 'https://www.nobelprize.org/prizes/facts/
facts-on-the-nobel-prize-in-physics/', 'content': 'List of all female Nobel
Prize laureates. Multiple Nobel Prize laureates in physics. John Bardeen is
the only person who has received the Nobel Prize in Physics twice, year 1956
and 1972 . Marie Curie was awarded the Nobel Prize twice, once in physics 1903
and once in chemistry 1911.. See the list of multiple Nobel Prize laureates
within other Nobel Prize categories here'}]}
"""

search_linkup_response = SearchToolkit().search_linkup(
query="Can you tell me which women were awared the Physics Nobel Prize",
depth="standard",
output_type="sourcedAnswer",
)

print(search_linkup_response)
"""
{'answer': "The women who have been awarded the Nobel Prize in Physics are: 1.
Marie Curie - 1903 2. Maria Goeppert Mayer - 1963 3. Donna Strickland - 2018
4. Anne L'Huillier - 2023", 'sources': [{'name': 'Nobel Prize awarded women -
NobelPrize.org', 'url': 'https://www.nobelprize.org/prizes/lists/
nobel-prize-awarded-women/', 'snippet': 'The Nobel Prize and the Sveriges
Riksbank Prize in Economic Sciences in Memory of Alfred Nobel have been
awarded to women 66 times between 1901 and 2024.'}, {'name': 'Physics Nobel
Prizes awarded to women | Scientia News', 'url': 'https://www.scientianews.org/
physics-nobel-prize-winners', 'snippet': 'The next female Nobel Prize in
Physics award winner wouldn't be until another half-century later, with Donna
Strickland.'}, {'name': 'List of female Nobel laureates - Wikipedia', 'url':
'https://en.wikipedia.org/wiki/List_of_female_Nobel_laureates', 'snippet':
"The most recent women to be awarded a Nobel Prize were Han Kang in Literature
(2024), Claudia Goldin in Economics, Narges Mohammadi for Peace, Anne
L'Huillier in Physics and Katalin Karikó in Physiology or Medicine (2023)."}]}
(camel-ai-py3.10) ruihan@RuideMac-mini camel %
"""


class PersonInfo(BaseModel):
# Basic company information
name: str = "" # Company name
description: str = ""


search_linkup_response = SearchToolkit().search_linkup(
query="Can you tell me which women were awared the Physics Nobel Prize",
depth="standard",
output_type="structured",
structured_output_schema=PersonInfo,
)
print(search_linkup_response)

"""
{'name': 'Female Nobel Prize Winners in Physics', 'description': 'The women
awarded the Nobel Prize in Physics include: 1. Marie Curie (1903) 2. Maria
Goeppert-Mayer (1963) 3. Donna Strickland (2018) 4. (4th winner not mentioned
in the provided data) 5. (5th winner not mentioned in the provided data). Less
than 5 women have won the Nobel Prize in Physics out of 225 total laureates.'}
"""
Loading
Loading