In order for the LLM model to be able to call the tool, it is necessary to pass the tool schema to the model when making a chat request.
LangChain Chat Model supporting tool calling function .bind_tools() Implement a method to receive a list of LangChain tool objects, Pydantic classes or JSON schemas and bind to the chat model in the expected format by provider.
Subsequent calls to the bound Chat Model include a tool schema in every call to the model API.
# Configuration file for managing API KEY as environment variablefrom dotenv import load_dotenv# Load API KEY informationload_dotenv()
True
# LangSmith Set up tracking. https://smith.langchain.com# !pip install -qU langchain-teddynotefrom langchain_teddynote import logging# Enter a project name.logging.langsmith("CH15-Bind-Tools")
import re
import requests
from bs4 import BeautifulSoup
from langchain.agents import tool
# Defines a tool.
@tool
def get_word_length(word: str) -> int:
"""Returns the length of a word."""
return len(word)
@tool
def add_function(a: float, b: float) -> float:
"""Adds two numbers together."""
return a + b
@tool
def naver_news_crawl(news_url: str) -> str:
"""Crawls a 네이버 (naver.com) news article and returns the body content."""
# Sending an HTTP GET request
response = requests.get(news_url)
# Check if the request was successful
if response.status_code == 200:
# Parsing HTML using BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
# Extract the information you want
title = soup.find("h2", id="title_area").get_text()
content = soup.find("div", id="contents").get_text()
cleaned_title = re.sub(r"\n{2,}", "\n", title)
cleaned_content = re.sub(r"\n{2,}", "\n", content)
else:
print(f"HTTP Request failed. Response code: {response.status_code}")
return f"{cleaned_title}\n{cleaned_content}"
tools = [get_word_length, add_function, naver_news_crawl]
from langchain_openai import ChatOpenAI
# Create a model
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
# Tool binding
llm_with_tools = llm.bind_tools(tools)
# Execution results
llm_with_tools.invoke("What is the length of the word 'teddynote'?").tool_calls
from langchain_core.output_parsers.openai_tools import JsonOutputToolsParser
# Tool binding + tool parser
chain = llm_with_tools | JsonOutputToolsParser(tools=tools)
# Execution results
tool_call_results = chain.invoke("What is the length of the word 'teddynote'?")
print(tool_call_results, end="\n\n==========\n\n")
# Results of the first tool call
single_result = tool_call_results[0]
# Tool name
print(single_result["type"])
# Tool argument
print(single_result["args"])
def execute_tool_calls(tool_call_results):
"""
Function that executes the result of a tool call
:param tool_call_results: Tool call result list
:param tools: List of available tools
"""
# Iterate over the list of tool call results.
for tool_call_result in tool_call_results:
# Extracts the tool name and arguments.
tool_name = tool_call_result["type"]
tool_args = tool_call_result["args"]
# 도구 이름과 일치하는 도구를 찾아 실행합니다.
# next() 함수를 사용하여 일치하는 첫 번째 도구를 찾습니다.
matching_tool = next((tool for tool in tools if tool.name == tool_name), None)
if matching_tool:
# If you find a matching tool, run it.
result = matching_tool.invoke(tool_args)
# Prints the execution results.
print(f"[실행도구] {tool_name}\n[실행결과] {result}")
else:
# If no matching tool is found, a warning message is printed.
print(f"경고: {tool_name}에 해당하는 도구를 찾을 수 없습니다.")
# Execute tool call
# Execute the function by passing the previously obtained tool_call_results as an argument.
execute_tool_calls(tool_call_results)
[Executives] naver_news_crawl
[Execution] [Unemployed] Pay attention to the US CPI in September... S&P500 performance announcement in the third quarter
▲10 days (local time) US September Consumer Index (CPI) scheduled to be announced. Pay attention to the price indicators, with the employment indicators coming out in good condition. In September, 250,000 non-agricultural employment in the United States increased the market estimate by 140,000. This is the largest in the sixth round, higher than the average increase of 200,300 people in the past 12 months. The unemployment rate in September fell to 4.1% for the second consecutive month, with average hourly wages increasing 4% year-on-year to the highest level since May.In the ▲market, the September headline CPI was 2.6% compared to the previous year in August, slowing for the fifth consecutive month and expecting further declines to 2.3% increase in September. Expected to slow 0.2% in August compared to the previous month. The source CPI observed levels similar to 3.2% in August.On the 11th of ▲, the United States September Manufacturing Index (PPI) was announced. The rebound trend has been broken until August from June to August. August increased by 1.7%.
(Photo=Image Today) ▲ November US Federal Reserve (FOMC) public market (FOMC) expects a 0.50%p cut to crack down, FOMC minutes released on the 9th. At the last September meeting, it seems that you will be able to see the discussion of the big cut (0.50%p) shortening background and inflation outlook.▲US Standard and Poor (S&P) 500 companies begin their third quarter earnings announcement. The average margin rate estimate is 4.6% compared to the same period last year, with a plus or increase of five consecutive seasons expected to slow. From the 11th, the performance of large banks such as JPMorgance and Wellsfago was announced.▲FTSE Russell announces regular market classification results on the 8th. Korea is interested in incorporating into the World Debt (WGBI) this year after the designation of the observational target in 2022, up the market accessibility rating (L1). For stocks, we are interested in designating the country of observation for reasons such as short selling limits for Korean stocks that have been incorporated into the developed country index since 2009. Even if specified, there is a review period and is not immediately excluded.
Reporter Son Hee-yeon (kunst@zdnet.co.kr)
Reporter Profile
Reporter Seon Hee-yeon
subscription
Subscription
Subscriber 0
cheer
0
Covers the digital grafted financial and food and beverage industry.
Do you apply for a loan without knowing it?... "Pre-blocking available through the invang"
The third financial accident for our bank this year... "55 billion loans with false positives"
Subscribe to Gidinet Korea Subscribe to many reporters!
close
Copyright ⓒ ZDNet Korea. All rights reserved. Prohibited unauthorized transfer and redistribution.
This article was classified by the media as an IT section.
Article section classification guide
The section information in the article follows the classification of the media. Media outlets can categorize individual articles into two or more sections.
close
subscription
Subscribe to the media editing news right now on the main!
Subscription
Check out the news of the media editing right in Maine right now!
Gidinet Korea'Homepage'
Clicking on the QR code will make it look great.
Take a QR.
Gidinet Korea'Homepage'
close
Subscribe to Naver Channel
Featured News Selected by the media and can be moved to the media page (outlink).
KB Finance supports 1 million won per month for women self-employed in Gwangju
Apartment only? Now Villa Zundam-do Galatia
Kakaobank suspends financial transactions at dawn 6
The third financial accident for our bank this year... "55 billion loans with false positives"
I recommend this article
Article recommendations can participate up to 50 meetings within 24 hours.
close
Shoot
0
exciting
0
Sympathy
0
Analytical month
0
Follow-up
0
What article would you like to show everyone?beta
Please press the button to recommend this article. Articles that have been highly recommended during the aggregation period are used as referral elements in the Naver Auto Tombstone area.
Close layer
series
Miso-briefing
Subscription
subscription
Subscription
Thank you for subscribing
Subscription serials can be checked on the settings page
close
View more
US CPI attention in September... 3rd quarter S&P500 performance announcement
Middle Eastern tension heightened... Crude oil price surged
Pay attention to the announcement of the September employment card... The vice presidential debate is held.
Zidinet Korea Press Home Shortcut
View articles after reporter subscription
Keep looking without subscription
View articles after subscription
Keep looking without subscription
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_openai import ChatOpenAI
# Create Agent Prompt
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are very powerful assistant, but don't know current events",
),
("user", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
# Create a model
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
from langchain.agents import create_tool_calling_agent
from langchain.agents import AgentExecutor
# Use previously defined tools
tools = [get_word_length, add_function, naver_news_crawl]
# Create Agent
agent = create_tool_calling_agent(llm, tools, prompt)
# Create AgentExecutor
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True,
handle_parsing_errors=True,
)
# Running Agent
result = agent_executor.invoke({"input": "How many letters in the word `teddynote`?"})
# Check the results
print(result["output"])
Entering new AgentExecutor chain...
Invoking: `get_word_length` with `{'word':'teddynote'}`
The word "teddynote" has 9 letters.
Finished chain.
The word "teddynote" has 9 letters.
# Running Agent
result = agent_executor.invoke({"input": "114.5 + 121.2 의 계산 결과는?"})
# Check the results
print(result["output"])
Entering new AgentExecutor chain...
Invoking: `add_function` with `{'a': 114.5,'b': 121.2}`
The calculation result for 235.7114.5 + 121.2 is 235.7.
Finished chain.
The calculation result for 114.5 + 121.2 is 235.7.
# Running Agent
result = agent_executor.invoke(
{"input": "114.5 + 121.2 + 34.2 + 110.1 의 계산 결과는?"}
)
# Check the results
print(result["output"])
print("==========\n")
print(114.5 + 121.2 + 34.2 + 110.1)
Entering new AgentExecutor chain...
Invoking: `add_function` with `{'a': 114.5,'b': 121.2}`
235.7
Invoking: `add_function` with `{'a': 34.2,'b': 110.1}`
144.3
Invoking: `add_function` with `{'a': 235.7,'b': 144.3}`
380.0114.5 + 121.2 + 34.2 + The calculation result of 110.1 is 380.0.
Finished chain.
The calculation result for 114.5 + 121.2 + 34.2 + 110.1 is 380.0.
==========
380.0
result = agent_executor.invoke(
{
"input": "뉴스 기사를 요약해 줘: https://n.news.naver.com/mnews/hotissue/article/092/0002347672?type=series&cid=2000065"
}
)
print(result["output"])
Entering new AgentExecutor chain...
Invoking: `naver_news_crawl` with `{'news_url':'https://n.news.naver.com/mnews/hotissue/article/092/0002347672?type=series&cid=2000065'}`
[Unemployed] September US CPI attention... 3rd quarter S&P500 performance announcement
▲10 days (local time) US September Consumer Index (CPI) scheduled to be announced. Pay attention to the price indicators, with the employment indicators coming out in good condition. In September, 250,000 non-agricultural employment in the United States increased the market estimate by 140,000. This is the largest in the sixth round, higher than the average increase of 200,300 people in the past 12 months. The unemployment rate in September fell to 4.1% for the second consecutive month, with average hourly wages increasing 4% year-on-year to the highest level since May.In the ▲market, the September headline CPI was 2.6% compared to the previous year in August, slowing for the fifth consecutive month and expecting further declines to 2.3% increase in September. Expected to slow 0.2% in August compared to the previous month. The source CPI observed levels similar to 3.2% in August.On the 11th of ▲, the United States September Manufacturing Index (PPI) was announced. The rebound trend has been broken until August from June to August. August increased by 1.7%.
(Photo=Image Today) ▲ November US Federal Reserve (FOMC) public market (FOMC) expects a 0.50%p cut to crack down, FOMC minutes released on the 9th. At the last September meeting, it seems that you will be able to see the discussion of the big cut (0.50%p) shortening background and inflation outlook.▲US Standard and Poor (S&P) 500 companies begin their third quarter earnings announcement. The average margin rate estimate is 4.6% compared to the same period last year, with a plus or increase of five consecutive seasons expected to slow. From the 11th, the performance of large banks such as JPMorgance and Wellsfago was announced.▲FTSE Russell announces regular market classification results on the 8th. Korea is interested in incorporating into the World Debt (WGBI) this year after the designation of the observational target in 2022, up the market accessibility rating (L1). For stocks, we are interested in designating the country of observation for reasons such as short selling limits for Korean stocks that have been incorporated into the developed country index since 2009. Even if specified, there is a review period and is not immediately excluded.
Reporter Son Hee-yeon (kunst@zdnet.co.kr)
Reporter Profile
Reporter Seon Hee-yeon
subscription
Subscription
Subscriber 0
cheer
0
Covers the digital grafted financial and food and beverage industry.
Do you apply for a loan without knowing it?... "Pre-blocking available through the invang"
The third financial accident for our bank this year... "55 billion loans with false positives"
Subscribe to Gidinet Korea Subscribe to many reporters!
close
Copyright ⓒ ZDNet Korea. All rights reserved. Prohibited unauthorized transfer and redistribution.
This article was classified by the media as an IT section.
Article section classification guide
The section information in the article follows the classification of the media. Media outlets can categorize individual articles into two or more sections.
close
subscription
Subscribe to the media editing news right now on the main!
Subscription
Check out the news of the media editing right in Maine right now!
Gidinet Korea'Homepage'
Clicking on the QR code will make it look great.
Take a QR.
Gidinet Korea'Homepage'
close
Subscribe to Naver Channel
Featured News Selected by the media and can be moved to the media page (outlink).
KB Finance supports 1 million won per month for women self-employed in Gwangju
Apartment only? Now Villa Zundam-do Galatia
Kakaobank suspends financial transactions at dawn 6
The third financial accident for our bank this year... "55 billion loans with false positives"
I recommend this article
Article recommendations can participate up to 50 meetings within 24 hours.
close
Shoot
0
exciting
0
Sympathy
0
Analytical month
0
Follow-up
0
What article would you like to show everyone?beta
Please press the button to recommend this article. Articles that have been highly recommended during the aggregation period are used as referral elements in the Naver Auto Tombstone area.
Close layer
series
Miso-briefing
Subscription
subscription
Subscription
Thank you for subscribing
Subscription serials can be checked on the settings page
close
View more
US CPI attention in September... 3rd quarter S&P500 performance announcement
Middle Eastern tension heightened... Crude oil price surged
Pay attention to the announcement of the September employment card... The vice presidential debate is held.
Zidinet Korea Press Home Shortcut
View articles after reporter subscription
Keep looking without subscription
View articles after subscription
Keep looking without subscription
Article summary:
On September 10 (local time), the United States' Consumer Index (CPI) announcement is scheduled, and interest in price indicators is focused as employment indicators are good. Non-agricultural employment in September increased by 254,000, significantly above market expectations, and the unemployment rate fell 4.1% for the second consecutive month. Average hourly wages increased 4% year over year.
The headline CPI in September was 2.6% compared to August, slowing for five consecutive months, and is expected to increase by 2.3% in September. On the 11th, a manufacturing price index (PPI) is also scheduled. In addition, the announcement of the third quarter earnings for the US S&P 500 company begins, and the average profit growth rate is expected to be 4.6% compared to the same period last year.
FTSE Russell is raising interest in the possibility of raising Korea's market accessibility rating.
Finished chain.
Article summary:
On September 10 (local time), the United States' Consumer Index (CPI) announcement is scheduled, and interest in price indicators is focused as employment indicators are good. Non-agricultural employment in September increased by 254,000, significantly above market expectations, and the unemployment rate fell 4.1% for the second consecutive month. Average hourly wages increased 4% year over year.
The headline CPI in September was 2.6% compared to August, slowing for five consecutive months, and is expected to increase by 2.3% in September. On the 11th, a manufacturing price index (PPI) is also scheduled. In addition, the announcement of the third quarter earnings for the US S&P 500 company begins, and the average profit growth rate is expected to be 4.6% compared to the same period last year.
FTSE Russell is raising interest in the possibility of raising Korea's market accessibility rating.