1.3 MiB
1.3 MiB
In [1]:
import wikipedia
def get_article(search_term):
results = wikipedia.search(search_term)
first_result = results[0]
page = wikipedia.page(first_result, auto_suggest=False)
return page.contentIn [2]:
article = get_article("Superman")
print(article[:500]) # article is very long, so let's just print a previewSuperman is a superhero who appears in American comic books published by DC Comics. The character was created by writer Jerry Siegel and artist Joe Shuster, and debuted in the comic book Action Comics #1 (cover-dated June 1938 and published April 18, 1938). Superman has been adapted to several other media including radio serials, novels, films, television shows, theater, and video games. Superman was born Kal-El, on the fictional planet Krypton. As a baby, his parents Jor-El and Lara sent him to
In [3]:
article = get_article("Zendaya")
print(article[:500]) # article is very long, so let's just print a previewZendaya Maree Stoermer Coleman ( zən-DAY-ə; born September 1, 1996) is an American actress and singer. Her accolades include two Primetime Emmy Awards and a Golden Globe Award. In 2022, Time named her one of the 100 most influential people in the world. Born and raised in Oakland, California, Zendaya began her career as a child model and backup dancer. She made her television debut as Rocky Blue in the Disney Channel sitcom Shake It Up (2010–2013) and starred as the titular character in the cha
In [4]:
article_search_tool = {
"toolSpec": {
"name": "get_article",
"description": "A tool to retrieve an up to date Wikipedia article.",
"inputSchema": {
"json": {
"type": "object",
"properties": {
"search_term": {
"type": "string",
"description": "The search term to find a wikipedia article by title"
},
},
"required": ["search_term"]
}
}
}
}In [5]:
import boto3
bedrock_client = boto3.client(service_name='bedrock-runtime', region_name="us-west-2")
model_id = "anthropic.claude-3-5-sonnet-20241022-v2:0"
messages = [{"role": "user", "content": [{"text": "who won the 2024 Masters Tournament?"}]}]
inference_config={"maxTokens":400}
tool_config = {"tools":[article_search_tool]}
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
inferenceConfig=inference_config,
toolConfig=tool_config,
)In [6]:
response["output"]["message"]["content"][-1]["toolUse"]Out [6]:
{'toolUseId': 'tooluse_7A-RfkEeRc2PCofwjVGHXw',
'name': 'get_article',
'input': {'search_term': '2024 Masters Tournament'}}In [7]:
messages.append(response["output"]["message"])In [8]:
messagesOut [8]:
[{'role': 'user',
'content': [{'text': 'who won the 2024 Masters Tournament?'}]},
{'role': 'assistant',
'content': [{'text': 'Let me search for information about the 2024 Masters Tournament.'},
{'toolUse': {'toolUseId': 'tooluse_7A-RfkEeRc2PCofwjVGHXw',
'name': 'get_article',
'input': {'search_term': '2024 Masters Tournament'}}}]}]In [9]:
last_block = response["output"]["message"]["content"][-1]
# This is a simple, but brittle way of getting the tool use information
# We're simply taking the last block from Claude's response.
tool_use = last_block['toolUse']
tool_name = tool_use['name']
tool_input = tool_use['input']
print("Tool name: ", tool_name)
print("Tool input", tool_input)Tool name: get_article
Tool input {'search_term': '2024 Masters Tournament'}
In [10]:
if tool_name == "get_article":
search_term = tool_input["search_term"]
wiki_result = get_article(search_term)
print(f"Searching Wikipedia for {search_term}")
print("WIKIPEDIA PAGE CONTENT:")
print(wiki_result[:500]) #just printing a small bit of the article because it's so longSearching Wikipedia for 2024 Masters Tournament WIKIPEDIA PAGE CONTENT: The 2024 Masters Tournament was the 88th edition of the Masters Tournament and the first of the men's four major golf championships held in 2024. The tournament was played from April 11–14 at Augusta National Golf Club in Augusta, Georgia, United States. Scottie Scheffler won his second Masters and major, four strokes ahead of runner-up Ludvig Åberg, who was playing in his first major. Scheffler became the fourth-youngest two-time winner of the tournament and the second player, after Tiger Woods
In [11]:
{
"role": "user",
"content": [
{
"toolResult": {
"toolUseId": "toolu_01A09q90qw90lq917835lq9",
"content": [{
"text": "The result of actually calling the tool goes here"
}]
}
}
]
}Out [11]:
{'role': 'user',
'content': [{'toolResult': {'toolUseId': 'toolu_01A09q90qw90lq917835lq9',
'content': [{'text': 'The result of actually calling the tool goes here'}]}}]}In [12]:
tool_response = {
"role": "user",
"content": [
{
"toolResult": {
"toolUseId": tool_use['toolUseId'],
"content": [
{
"text": wiki_result
}
]
}
}
]
}In [13]:
# Notice the long wikipedia article content!
tool_response['content'][0]Out [13]:
{'toolResult': {'toolUseId': 'tooluse_7A-RfkEeRc2PCofwjVGHXw',
'content': [{'text': "The 2024 Masters Tournament was the 88th edition of the Masters Tournament and the first of the men's four major golf championships held in 2024. The tournament was played from April 11–14 at Augusta National Golf Club in Augusta, Georgia, United States. Scottie Scheffler won his second Masters and major, four strokes ahead of runner-up Ludvig Åberg, who was playing in his first major. Scheffler became the fourth-youngest two-time winner of the tournament and the second player, after Tiger Woods in 2001, to win both the Masters and The Players Championship in the same calendar year. \n\n\n== Course ==\n\nThe only change to the course for the 2024 tournament was the lengthening of the second hole by ten yards.\n\n\n== Field ==\nParticipation in the Masters Tournament is by invitation only, and the tournament has the smallest field of the major championships. There are a number of criteria by which invitations are awarded, including all past winners, recent major champions, leading finishers in the previous year's majors, leading players on the PGA Tour in the previous season, winners of full-point tournaments on the PGA Tour during the previous 12 months, leading players in the Official World Golf Ranking, and some leading amateurs.\n\n\n=== Criteria ===\nThere were three changes to invitee criteria between the 2023 and 2024 tournaments. The first was to add the current NCAA Division I Men's Individual Champion a spot in the field, provided that he remains an amateur at the time of the tournament. In addition, Augusta National clarified that players who qualify for the Tour Championship must remain eligible to play in that event in order to qualify for the Masters. Also, with the PGA Tour returning to a calendar-year season schedule, Augusta National noted that winners of fall PGA Tour events would continue to qualify for the Masters.\nThe below list details the qualification criteria for the 2024 Masters Tournament and the players who have qualified under them; any additional criteria under which players qualified are indicated in parentheses.\n1. All past winners of the Masters Tournament\n\nPast winners who did not play: Tommy Aaron, Ángel Cabrera, Charles Coody, Ben Crenshaw, Nick Faldo, Raymond Floyd, Trevor Immelman, Bernhard Langer, Sandy Lyle, Larry Mize, Jack Nicklaus, Mark O'Meara, Gary Player, Craig Stadler, Tom Watson, Ian Woosnam, Fuzzy Zoeller\n2. Recent winners of the U.S. Open (2019–2023)\n\n3. Recent winners of The Open Championship (2019–2023)\n\n4. Recent winners of the PGA Championship (2019–2023)\n\n5. Recent winners of The Players Championship (2022–2024)\n6. The winner of the gold medal at the Olympic Games\n7. The winner and runner-up in the 2023 U.S. Amateur\n\nNeal Shipley (a)\n8. The winner of the 2023 Amateur Championship\n\nChristo Lamprecht (a)\n9. The winner of the 2023 Asia-Pacific Amateur Championship\n\nJasper Stubbs (a)\n10. The winner of the 2024 Latin America Amateur Championship\n\nSantiago de la Fuente (a)\n11. The winner of the 2023 U.S. Mid-Amateur Golf Championship\n\nStewart Hagestad (a)\n12. The winner of the 2023 NCAA Division I men's golf individual championship\n\nFred Biondi forfeited his invitation by turning professional.\n13. The leading 12 players, and those tying for 12th place, from the 2023 Masters Tournament\n\n14. The leading four players, and those tying for fourth place, in the 2023 U.S. Open\n\nRory McIlroy (17,18,19,20)\n15. The leading four players, and those tying for fourth place, in the 2023 Open Championship\n\n16. The leading four players, and those tying for fourth place, in the 2023 PGA Championship\n\n17. Winners of tournaments on the PGA Tour between the 2023 Masters Tournament and the 2024 Masters Tournament\n\n18. All players who qualified for and are eligible for the 2023 Tour Championship\n\n19. The leading 50 players on the Official World Golf Ranking as of December 31, 2023\n\n20. The leading 50 players on the Official World Golf Ranking as of April 1, 2024\n\nAn Byeong-hun\n21. Special invitations\n\n\n== Par-3 contest ==\nWednesday, April 10\nRickie Fowler won the par-3 contest with a score of 22 (−5). There were five holes-in-one recorded, by Sepp Straka, Luke List, Gary Woodland, Viktor Hovland, and Lucas Glover.\n\n\n== Round summaries ==\n\n\n=== First round ===\nThursday, April 11, 2024Friday, April 12, 2024\nInclement weather delayed the start of the tournament until 10:30 am Eastern time. As a result, 27 players did not complete the first round on Thursday.\nThe 8th hole, a par 5, saw a record-breaking total of 53 par-breaking scores, including 50 birdies and 3 eagles, the highest ever recorded on this hole in Masters history. \n\n\n=== Second round ===\nFriday, April 12, 2024\nBy making the cut, Tiger Woods set the record for most consecutive cuts made at the Masters, at 24. Phil Mickelson made the cut for the 28th time, surpassing Raymond Floyd and Bernhard Langer to move into solo fourth place for most cuts made at the Masters, trailing only Jack Nicklaus (37), Fred Couples (31) and Gary Player (30).\nRookie Ludvig Åberg posted the lowest score of the round, a 69, and advanced to a solo 7th place.\nBryson DeChambeau, before making a birdie on the 13th hole, moved a large directional sign that was in his line of play.\nPatrick Cantlay achieved two eagles on par 4s, marking only the fourth instance in history that a player has recorded two par-4 eagles in a single Masters Tournament, the last being Brandt Jobe in 2006.\nThe cut came at 150 (+6), with 60 players advancing to the weekend. Notables to miss the cut included 2015 champion Jordan Spieth, 2020 champion Dustin Johnson, reigning U.S. Open champion Wyndham Clark, Open champion Brian Harman, and World No. 6 Viktor Hovland. Two-time major champion Justin Thomas played his last four holes in seven-over to miss the cut by one shot.\n\n\n=== Third round ===\nSaturday, April 13, 2024\nScottie Scheffler, beginning the round in a three-way tie for the lead, chipped in for birdie on the first hole. After a double bogey on the 10th, Scheffler holed a 31-foot eagle putt on the par-five 13th, the only eagle recorded on that hole during the round. He also birdied the 15th and 18th to finish at seven under following a 71 (−1) to take a one-shot lead into the final round.\nCollin Morikawa birdied his first three holes in a three-under round of 69 and finished at six under, one shot back of Scheffler. Max Homa, tied for the lead at the start of the round, didn't make a birdie in a one-over 73 and fell two back at 5 under. Bryson DeChambeau was also atop the leaderboard to begin the round but hit his third shot in the water on the 15th and made double bogey. He holed out for birdie on the 18th to finish at three under and four shots back of Scheffler. Ludvig Åberg, making his Masters and major championship debut, was four under on his round until a bogey at the 14th. He then left his third shot on the 15th short and three-putted from just off the green for another bogey. He shot 70 (–2) and ended up at four under.\nNicolai Højgaard moved into sole possession of the lead following a run of three straight birdies from holes 8 to 10, but he then made five straight bogeys including hitting into the water on both the 13th and 15th and finished at two under.\nTiger Woods carded a 10-over-par 82 for the third round, his highest score ever in a major championship.\nNo eagles were recorded on the par-5 15th hole through the first three rounds, marking only the second time in the past 50 years that No. 15 has failed to produce an eagle by this point in the tournament. Shane Lowry scored an eagle on the par-4 14th hole, marking the first eagle on this hole since Martin Kaymer in 2016.\n\n\n=== Final round ===\nSunday, April 14, 2024\n\nWorld No. 1 Scottie Scheffler shot a four-under 68 to win his second Masters title in the last three years by four shots over runner-up Ludvig Åberg.\nScheffler began the round with a one-shot lead and birdied the third hole to go two shots ahead. He then bogeyed the fourth after hitting his tee shot over the green. Max Homa birdied the second, his first birdie in 34 holes, to get within one of the lead, while Åberg hit his approach on the seventh to four feet and made birdie to also get within one of the lead.\nScheffler bogeyed the seventh to create a three-way tie with Åberg and Collin Morikawa at six under, while Homa joined the lead with a two-putt birdie at the par-five eighth. Both Scheffler and Morikawa birdied the eighth to get to seven under, while Åberg holed a 36-foot birdie putt on the ninth to again tie. Scheffler then hit his approach on the ninth to within a foot for another birdie to get to 8 under and again in sole possession of the lead going to the second nine.\nAll three challengers then fell from contention. Morikawa hit his second shot on the ninth into a greenside bunker and couldn't advance on his third, ending up with a double bogey to fall three shots behind. He found the water on his approach at the 11th and made another double bogey. Åberg also hit into the water on the 11th for a double bogey. Homa got back within one with a close approach to the 10th, but his tee shot on the 12th flew over the green into the bushes and he was forced to take a drop. He made a double bogey on the hole to fall three shots behind.\nScheffler birdied the 10th, his third birdie in a row, to get to nine under and open a two-shot lead. Despite a bogey on the 11th, Scheffler two-putted for birdie at the par-five 13th and hit his second shot on the 14th to within four feet for another birdie to reach 10 under. He then made a nine-foot birdie putt on the par-three 16th to get to 11 under. Pars on his final two holes allowed him to close out the tournament with a four-shot victory.\nÅberg birdied the 13th and 14th to get back to seven under and finish four back of Scheffler in his Masters and major championship debut. Morikawa and Homa both finished at four under for the tournament, in a tie for third place along with Tommy Fleetwood.\n\n\n==== Scorecard ====\n\nCumulative tournament scores, relative to par\n\nSource:\n\n\n== Notes ==\n\n\n== References ==\n\n\n== External links ==\nOfficial website"}]}}In [14]:
messages.append(tool_response)In [15]:
messagesOut [15]:
[{'role': 'user',
'content': [{'text': 'who won the 2024 Masters Tournament?'}]},
{'role': 'assistant',
'content': [{'text': 'Let me search for information about the 2024 Masters Tournament.'},
{'toolUse': {'toolUseId': 'tooluse_7A-RfkEeRc2PCofwjVGHXw',
'name': 'get_article',
'input': {'search_term': '2024 Masters Tournament'}}}]},
{'role': 'user',
'content': [{'toolResult': {'toolUseId': 'tooluse_7A-RfkEeRc2PCofwjVGHXw',
'content': [{'text': "The 2024 Masters Tournament was the 88th edition of the Masters Tournament and the first of the men's four major golf championships held in 2024. The tournament was played from April 11–14 at Augusta National Golf Club in Augusta, Georgia, United States. Scottie Scheffler won his second Masters and major, four strokes ahead of runner-up Ludvig Åberg, who was playing in his first major. Scheffler became the fourth-youngest two-time winner of the tournament and the second player, after Tiger Woods in 2001, to win both the Masters and The Players Championship in the same calendar year. \n\n\n== Course ==\n\nThe only change to the course for the 2024 tournament was the lengthening of the second hole by ten yards.\n\n\n== Field ==\nParticipation in the Masters Tournament is by invitation only, and the tournament has the smallest field of the major championships. There are a number of criteria by which invitations are awarded, including all past winners, recent major champions, leading finishers in the previous year's majors, leading players on the PGA Tour in the previous season, winners of full-point tournaments on the PGA Tour during the previous 12 months, leading players in the Official World Golf Ranking, and some leading amateurs.\n\n\n=== Criteria ===\nThere were three changes to invitee criteria between the 2023 and 2024 tournaments. The first was to add the current NCAA Division I Men's Individual Champion a spot in the field, provided that he remains an amateur at the time of the tournament. In addition, Augusta National clarified that players who qualify for the Tour Championship must remain eligible to play in that event in order to qualify for the Masters. Also, with the PGA Tour returning to a calendar-year season schedule, Augusta National noted that winners of fall PGA Tour events would continue to qualify for the Masters.\nThe below list details the qualification criteria for the 2024 Masters Tournament and the players who have qualified under them; any additional criteria under which players qualified are indicated in parentheses.\n1. All past winners of the Masters Tournament\n\nPast winners who did not play: Tommy Aaron, Ángel Cabrera, Charles Coody, Ben Crenshaw, Nick Faldo, Raymond Floyd, Trevor Immelman, Bernhard Langer, Sandy Lyle, Larry Mize, Jack Nicklaus, Mark O'Meara, Gary Player, Craig Stadler, Tom Watson, Ian Woosnam, Fuzzy Zoeller\n2. Recent winners of the U.S. Open (2019–2023)\n\n3. Recent winners of The Open Championship (2019–2023)\n\n4. Recent winners of the PGA Championship (2019–2023)\n\n5. Recent winners of The Players Championship (2022–2024)\n6. The winner of the gold medal at the Olympic Games\n7. The winner and runner-up in the 2023 U.S. Amateur\n\nNeal Shipley (a)\n8. The winner of the 2023 Amateur Championship\n\nChristo Lamprecht (a)\n9. The winner of the 2023 Asia-Pacific Amateur Championship\n\nJasper Stubbs (a)\n10. The winner of the 2024 Latin America Amateur Championship\n\nSantiago de la Fuente (a)\n11. The winner of the 2023 U.S. Mid-Amateur Golf Championship\n\nStewart Hagestad (a)\n12. The winner of the 2023 NCAA Division I men's golf individual championship\n\nFred Biondi forfeited his invitation by turning professional.\n13. The leading 12 players, and those tying for 12th place, from the 2023 Masters Tournament\n\n14. The leading four players, and those tying for fourth place, in the 2023 U.S. Open\n\nRory McIlroy (17,18,19,20)\n15. The leading four players, and those tying for fourth place, in the 2023 Open Championship\n\n16. The leading four players, and those tying for fourth place, in the 2023 PGA Championship\n\n17. Winners of tournaments on the PGA Tour between the 2023 Masters Tournament and the 2024 Masters Tournament\n\n18. All players who qualified for and are eligible for the 2023 Tour Championship\n\n19. The leading 50 players on the Official World Golf Ranking as of December 31, 2023\n\n20. The leading 50 players on the Official World Golf Ranking as of April 1, 2024\n\nAn Byeong-hun\n21. Special invitations\n\n\n== Par-3 contest ==\nWednesday, April 10\nRickie Fowler won the par-3 contest with a score of 22 (−5). There were five holes-in-one recorded, by Sepp Straka, Luke List, Gary Woodland, Viktor Hovland, and Lucas Glover.\n\n\n== Round summaries ==\n\n\n=== First round ===\nThursday, April 11, 2024Friday, April 12, 2024\nInclement weather delayed the start of the tournament until 10:30 am Eastern time. As a result, 27 players did not complete the first round on Thursday.\nThe 8th hole, a par 5, saw a record-breaking total of 53 par-breaking scores, including 50 birdies and 3 eagles, the highest ever recorded on this hole in Masters history. \n\n\n=== Second round ===\nFriday, April 12, 2024\nBy making the cut, Tiger Woods set the record for most consecutive cuts made at the Masters, at 24. Phil Mickelson made the cut for the 28th time, surpassing Raymond Floyd and Bernhard Langer to move into solo fourth place for most cuts made at the Masters, trailing only Jack Nicklaus (37), Fred Couples (31) and Gary Player (30).\nRookie Ludvig Åberg posted the lowest score of the round, a 69, and advanced to a solo 7th place.\nBryson DeChambeau, before making a birdie on the 13th hole, moved a large directional sign that was in his line of play.\nPatrick Cantlay achieved two eagles on par 4s, marking only the fourth instance in history that a player has recorded two par-4 eagles in a single Masters Tournament, the last being Brandt Jobe in 2006.\nThe cut came at 150 (+6), with 60 players advancing to the weekend. Notables to miss the cut included 2015 champion Jordan Spieth, 2020 champion Dustin Johnson, reigning U.S. Open champion Wyndham Clark, Open champion Brian Harman, and World No. 6 Viktor Hovland. Two-time major champion Justin Thomas played his last four holes in seven-over to miss the cut by one shot.\n\n\n=== Third round ===\nSaturday, April 13, 2024\nScottie Scheffler, beginning the round in a three-way tie for the lead, chipped in for birdie on the first hole. After a double bogey on the 10th, Scheffler holed a 31-foot eagle putt on the par-five 13th, the only eagle recorded on that hole during the round. He also birdied the 15th and 18th to finish at seven under following a 71 (−1) to take a one-shot lead into the final round.\nCollin Morikawa birdied his first three holes in a three-under round of 69 and finished at six under, one shot back of Scheffler. Max Homa, tied for the lead at the start of the round, didn't make a birdie in a one-over 73 and fell two back at 5 under. Bryson DeChambeau was also atop the leaderboard to begin the round but hit his third shot in the water on the 15th and made double bogey. He holed out for birdie on the 18th to finish at three under and four shots back of Scheffler. Ludvig Åberg, making his Masters and major championship debut, was four under on his round until a bogey at the 14th. He then left his third shot on the 15th short and three-putted from just off the green for another bogey. He shot 70 (–2) and ended up at four under.\nNicolai Højgaard moved into sole possession of the lead following a run of three straight birdies from holes 8 to 10, but he then made five straight bogeys including hitting into the water on both the 13th and 15th and finished at two under.\nTiger Woods carded a 10-over-par 82 for the third round, his highest score ever in a major championship.\nNo eagles were recorded on the par-5 15th hole through the first three rounds, marking only the second time in the past 50 years that No. 15 has failed to produce an eagle by this point in the tournament. Shane Lowry scored an eagle on the par-4 14th hole, marking the first eagle on this hole since Martin Kaymer in 2016.\n\n\n=== Final round ===\nSunday, April 14, 2024\n\nWorld No. 1 Scottie Scheffler shot a four-under 68 to win his second Masters title in the last three years by four shots over runner-up Ludvig Åberg.\nScheffler began the round with a one-shot lead and birdied the third hole to go two shots ahead. He then bogeyed the fourth after hitting his tee shot over the green. Max Homa birdied the second, his first birdie in 34 holes, to get within one of the lead, while Åberg hit his approach on the seventh to four feet and made birdie to also get within one of the lead.\nScheffler bogeyed the seventh to create a three-way tie with Åberg and Collin Morikawa at six under, while Homa joined the lead with a two-putt birdie at the par-five eighth. Both Scheffler and Morikawa birdied the eighth to get to seven under, while Åberg holed a 36-foot birdie putt on the ninth to again tie. Scheffler then hit his approach on the ninth to within a foot for another birdie to get to 8 under and again in sole possession of the lead going to the second nine.\nAll three challengers then fell from contention. Morikawa hit his second shot on the ninth into a greenside bunker and couldn't advance on his third, ending up with a double bogey to fall three shots behind. He found the water on his approach at the 11th and made another double bogey. Åberg also hit into the water on the 11th for a double bogey. Homa got back within one with a close approach to the 10th, but his tee shot on the 12th flew over the green into the bushes and he was forced to take a drop. He made a double bogey on the hole to fall three shots behind.\nScheffler birdied the 10th, his third birdie in a row, to get to nine under and open a two-shot lead. Despite a bogey on the 11th, Scheffler two-putted for birdie at the par-five 13th and hit his second shot on the 14th to within four feet for another birdie to reach 10 under. He then made a nine-foot birdie putt on the par-three 16th to get to 11 under. Pars on his final two holes allowed him to close out the tournament with a four-shot victory.\nÅberg birdied the 13th and 14th to get back to seven under and finish four back of Scheffler in his Masters and major championship debut. Morikawa and Homa both finished at four under for the tournament, in a tie for third place along with Tommy Fleetwood.\n\n\n==== Scorecard ====\n\nCumulative tournament scores, relative to par\n\nSource:\n\n\n== Notes ==\n\n\n== References ==\n\n\n== External links ==\nOfficial website"}]}}]}]In [16]:
inference_config={"maxTokens":400}
tool_config = {"tools":[article_search_tool]}
# Send the message.
follow_up_response = bedrock_client.converse(
modelId=model_id,
messages=messages,
inferenceConfig=inference_config,
toolConfig=tool_config,
)In [17]:
follow_up_response["output"]["message"]["content"][0]["text"]Out [17]:
"Based on the Wikipedia article, Scottie Scheffler won the 2024 Masters Tournament. He shot a four-under 68 in the final round to win his second Masters title in three years, finishing four shots ahead of runner-up Ludvig Åberg. This was Scheffler's second Masters victory, and he became the fourth-youngest two-time winner of the tournament. He's also only the second player, after Tiger Woods in 2001, to win both the Masters and The Players Championship in the same calendar year."
In [18]:
def answer_question(question):
messages = [{"role": "user", "content": [{"text":question}]}]
inference_config={"maxTokens":1000}
tool_config = {"tools":[article_search_tool]}
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
inferenceConfig=inference_config,
toolConfig=tool_config,
)
if(response['stopReason'] == "tool_use"):
last_block = response["output"]["message"]["content"][-1]
# This is a simple, but brittle way of getting the tool use information
# We're simply taking the last block from Claude's response.
tool_use = last_block['toolUse']
tool_name = tool_use["name"]
tool_input = tool_use["input"]
messages.append(response["output"]["message"])
#Add Claude's tool use call to messages:
if tool_name == "get_article":
search_term = tool_input["search_term"]
print(f"Claude wants to get an article for {search_term}")
wiki_result = get_article(search_term) #get wikipedia article content
#construct our tool_result message
tool_response = {
"role": "user",
"content": [
{
"toolResult": {
"toolUseId": tool_use['toolUseId'],
"content": [
{
"text": wiki_result
}
]
}
}
]
}
messages.append(tool_response)
#respond back to Claude
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
inferenceConfig=inference_config,
toolConfig=tool_config,
)
print("Claude's final answer:")
print(response["output"]["message"]["content"][0]["text"])
else:
print("Claude did not call our tool")
print(response["output"]["message"]["content"][0]["text"])In [19]:
answer_question("Who won the 2024 F1 Australian Grand Prix")Claude wants to get an article for 2024 Australian Grand Prix Claude's final answer: Based on the article, Carlos Sainz Jr. of Ferrari won the 2024 Australian Grand Prix, which was held on March 24, 2024, at the Albert Park Circuit in Melbourne. It was a remarkable victory for Sainz, who had undergone an appendectomy just two weeks prior and missed the Saudi Arabian Grand Prix. Ferrari achieved a 1-2 finish, with Charles Leclerc taking second place. Lando Norris of McLaren finished third. Notable events from the race included: 1. Max Verstappen, who started from pole position, retired on lap 4 due to brake failure, ending his streak of nine consecutive wins 2. This was Ferrari's first 1-2 finish since the 2022 Bahrain Grand Prix 3. The event set a new attendance record at the circuit with 452,055 spectators, making it the most attended sporting event ever in Melbourne
In [20]:
answer_question("Who stars in the movie Challengers?")Claude wants to get an article for Challengers (film) Claude's final answer: Based on the information from the Wikipedia article, the main stars of "Challengers" (2024) are: 1. Zendaya as Tashi Duncan 2. Josh O'Connor as Patrick Zweig 3. Mike Faist as Art Donaldson The film is directed by Luca Guadagnino and follows a love triangle between these three characters in the world of professional tennis. Zendaya plays an injured tennis star-turned-coach, Josh O'Connor plays her ex-boyfriend who is a low-circuit tennis player, and Mike Faist plays her tennis champion husband.
In [21]:
#Let's try an example that Claude should NOT need our tool to answer:
answer_question("Who wrote the book 'Life of Pi'")Claude wants to get an article for Life of Pi Claude's final answer: Based on the Wikipedia article, Life of Pi was written by Yann Martel. The novel was published in 2001 and went on to win several prestigious awards including the Man Booker Prize in 2002. Martel is a Canadian author, and the book became a major success, selling more than ten million copies worldwide. Interestingly, before being accepted by Knopf Canada, the book was rejected by at least five London publishing houses.
In [22]:
system_prompt = """
You will be asked a question by the user.
If answering the question requires data you were not trained on, you can use the get_article tool to get the contents of a recent wikipedia article about the topic.
If you can answer the question without needing to get more information, please do so.
Only call the tool when needed.
"""In [23]:
def answer_question(question):
messages = [{"role": "user", "content": [{"text":question}]}]
inference_config={"maxTokens":1000}
tool_config = {"tools":[article_search_tool]}
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
system=[{"text":system_prompt}],
inferenceConfig=inference_config,
toolConfig=tool_config,
)
if(response['stopReason'] == "tool_use"):
last_block = response["output"]["message"]["content"][-1]
# This is a simple, but brittle way of getting the tool use information
# We're simply taking the last block from Claude's response.
tool_use = last_block['toolUse']
tool_name = tool_use["name"]
tool_input = tool_use["input"]
messages.append(response["output"]["message"])
#Add Claude's tool use call to messages:
if tool_name == "get_article":
search_term = tool_input["search_term"]
print(f"Claude wants to get an article for {search_term}")
wiki_result = get_article(search_term) #get wikipedia article content
#construct our tool_result message
tool_response = {
"role": "user",
"content": [
{
"toolResult": {
"toolUseId": tool_use['toolUseId'],
"content": [
{
"text": wiki_result
}
]
}
}
]
}
messages.append(tool_response)
#respond back to Claude
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
inferenceConfig=inference_config,
toolConfig=tool_config,
)
print("Claude's final answer:")
print(response["output"]["message"]["content"][0]["text"])
else:
print("Claude did not call our tool")
print(response["output"]["message"]["content"][0]["text"])In [24]:
answer_question("Who wrote the book 'Life of Pi'")Claude wants to get an article for Life of Pi Claude's final answer: Based on the Wikipedia article, Life of Pi was written by Yann Martel. The novel was published in 2001 and went on to win several prestigious awards including the Man Booker Prize in 2002. Martel is a Canadian author, and the book became a major success, selling more than ten million copies worldwide.
In [25]:
answer_question("Who wrote the score for the movie Challengers?")Claude wants to get an article for Challengers (film) Claude's final answer: Based on the article, the film score for "Challengers" was composed by Trent Reznor and Atticus Ross. They had previously worked with director Luca Guadagnino on the 2022 film "Bones and All." Guadagnino approached them to score Challengers by sending them an email that simply read, "Do you want to be on my next film? It's going to be super sexy." The score was later also released in a remixed version in collaboration with Boys Noize.
In [26]:
prompt = f"""
Answer the following question <question>Who wrote the movie Poor Things?</question>
When you can answer the question, keep your answer as short as possible and enclose it in <answer> tags
"""In [27]:
def answer_question(question):
system_prompt = """
You will be asked a question by the user.
If answering the question requires data you were not trained on, you can use the get_article tool to get the contents of a recent wikipedia article about the topic.
If you can answer the question without needing to get more information, please do so.
Only call the tool when needed.
"""
prompt = f"""
Answer the following question <question>{question}</question>
When you can answer the question, keep your answer as short as possible and enclose it in <answer> tags
"""
messages = [{"role": "user", "content": [{"text":prompt}]}]
inference_config={"maxTokens":1000}
tool_config = {"tools":[article_search_tool]}
# Send the message.
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
system=[{"text":system_prompt}],
inferenceConfig=inference_config,
toolConfig=tool_config,
)
if(response['stopReason'] == "tool_use"):
last_block = response["output"]["message"]["content"][-1]
# This is a simple, but brittle way of getting the tool use information
# We're simply taking the last block from Claude's response.
tool_use = last_block['toolUse']
tool_name = tool_use["name"]
tool_input = tool_use["input"]
messages.append(response["output"]["message"])
#Add Claude's tool use call to messages:
if tool_name == "get_article":
search_term = tool_input["search_term"]
print(f"Claude wants to get an article for {search_term}")
wiki_result = get_article(search_term) #get wikipedia article content
#construct our tool_result message
tool_response = {
"role": "user",
"content": [
{
"toolResult": {
"toolUseId": tool_use['toolUseId'],
"content": [
{
"text": wiki_result
}
]
}
}
]
}
messages.append(tool_response)
#respond back to Claude
response = bedrock_client.converse(
modelId=model_id,
messages=messages,
inferenceConfig=inference_config,
toolConfig=tool_config,
)
print("Claude's final answer:")
print(response["output"]["message"]["content"][0]["text"])
else:
print("Claude did not call our tool")
print(response["output"]["message"]["content"][0]["text"])In [28]:
answer_question("Who wrote the score for the movie Challengers?")Claude wants to get an article for Challengers (film) Claude's final answer: <answer>Trent Reznor and Atticus Ross composed the score for Challengers</answer>
In [29]:
answer_question("How many legs does an octopus have?")Claude did not call our tool This is a basic fact I can answer without needing to look up additional information. <answer>An octopus has 8 legs, also called arms or tentacles.</answer>




