■ StructuredTool 클래스의 tool_call_schema 변수를 사용해 ModelMetadata 객체를 구하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
from langchain_core.tools import tool from typing import List from typing_extensions import Annotated from langchain_core.tools import InjectedToolArg userDictionary = {} @tool(parse_docstring = True) def updateFavoritePets(petList : List[str], userID : Annotated[str, InjectedToolArg]) -> None: """Add the list of favorite pets. Args: petList : List of favorite pets to set. userID : User's ID. """ userDictionary[userID] = petList modelClass = updateFavoritePets.tool_call_schema toolCallSchemaDictionary = modelClass.schema() print(toolCallSchemaDictionary) """ { 'description' : 'Add the list of favorite pets.', 'properties' : { 'petList' : { 'description' : 'List of favorite pets to set.', 'items' : {'type' : 'string'}, 'title' : 'Petlist', 'type' : 'array' } }, 'required' : ['petList'], 'title' : 'updateFavoritePets', 'type' : 'object' } """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.5.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.2 langchain-text-splitters==0.3.0 langsmith==0.1.124 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip install langchain 명령을
더 읽기
■ ChatOpenAI 클래스의 bind_tools 메소드를 사용해 도구 출력을 채팅 모델에 전달하는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다. ▶
더 읽기
■ ModelMetaclass 클래스의 schema 메소드를 사용해 스키마 딕셔너리를 구하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
from langchain_core.tools import tool from typing import List from typing_extensions import Annotated from langchain_core.tools import InjectedToolArg userDictionary = {} @tool(parse_docstring = True) def updateFavoritePets(petList : List[str], userID : Annotated[str, InjectedToolArg]) -> None: """Add the list of favorite pets. Args: petList : List of favorite pets to set. userID : User's ID. """ userDictionary[userID] = petList modelMetaclass = updateFavoritePets.get_input_schema() inputSchemaDictionary = modelMetaclass.schema() print(inputSchemaDictionary) """ { 'description' : 'Add the list of favorite pets.', 'properties' : { 'petList' : { 'description' : 'List of favorite pets to set.', 'items' : {'type': 'string'}, 'title' : 'Petlist', 'type' : 'array' }, 'userID' : { 'description' : "User's ID.", 'title' : 'Userid', 'type' : 'string' } }, 'required' : ['petList', 'userID'], 'title' : 'updateFavoritePets', 'type' : 'object' } """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.5.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.2 langchain-text-splitters==0.3.0 langsmith==0.1.124 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip install langchain 명령을
더 읽기
■ StructuredTool 클래스의 get_input_schema 메소드를 사용해 ModelMetaclass 객체를 구하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
from langchain_core.tools import tool from typing import List from typing_extensions import Annotated from langchain_core.tools import InjectedToolArg userDictionary = {} @tool(parse_docstring = True) def updateFavoritePets(petList : List[str], userID : Annotated[str, InjectedToolArg]) -> None: """Add the list of favorite pets. Args: petList : List of favorite pets to set. userID : User's ID. """ userDictionary[userID] = petList modelMetaclass = updateFavoritePets.get_input_schema() |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.5.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.2 langchain-text-splitters==0.3.0 langsmith==0.1.124 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip install langchain 명령을
더 읽기
■ PydanticToolsParser 클래스의 생성자에서 tools 인자를 사용해 도구 호출 정보를 반환하는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다. ▶
더 읽기
■ ChatOpenAI 클래스dml bind_tools 메소드를 사용해 도구 호출 메시지를 반환하는 방법을 보여준다. ※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다. ▶ main.py
더 읽기
■ WikipediaQueryRun 클래스의 생성자에서 description 인자를 사용해 도구 설명을 재정의하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
from pydantic import BaseModel from pydantic import Field from langchain_community.utilities import WikipediaAPIWrapper from langchain_community.tools import WikipediaQueryRun class WIKIModel(BaseModel): """Inputs to the wikipedia tool.""" query : str = Field(description = "query to look up in Wikipedia, should be 3 or less words") wikipediaAPIWrapper = WikipediaAPIWrapper(top_k_results = 1, doc_content_chars_max = 100) wikipediaQueryRun = WikipediaQueryRun( name = "wiki-tool", description = "look up things in wikipedia", args_schema = WIKIModel, api_wrapper = wikipediaAPIWrapper, return_direct = True, ) print(wikipediaQueryRun.run("langchain")) print() print(f"Name : {wikipediaQueryRun.name }") print(f"Description : {wikipediaQueryRun.description }") print(f"args schema : {wikipediaQueryRun.args }") print(f"returns directly? : {wikipediaQueryRun.return_direct}") """ Page: LangChain Summary: LangChain is a framework designed to simplify the creation of applications Name : wiki-tool Description : look up things in wikipedia args schema : {'query': {'description': 'query to look up in Wikipedia, should be 3 or less words', 'title': 'Query', 'type': 'string'}} returns directly? : True """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 beautifulsoup4==4.12.3 certifi==2024.8.30 charset-normalizer==3.3.2 dataclasses-json==0.6.7 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-community==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 marshmallow==3.22.0 multidict==6.1.0 mypy-extensions==1.0.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic-settings==2.5.2 pydantic_core==2.23.4 python-dotenv==1.0.1 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 soupsieve==2.6 SQLAlchemy==2.0.35 tenacity==8.5.0 typing-inspect==0.9.0 typing_extensions==4.12.2 urllib3==2.2.3 wikipedia==1.4.0 yarl==1.11.1 |
※ pip install langchain-community
더 읽기
■ WikipediaQueryRun 클래스에서 name/description/args/return_direct 변수를 사용하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
from langchain_community.utilities import WikipediaAPIWrapper from langchain_community.tools import WikipediaQueryRun wikipediaAPIWrapper = WikipediaAPIWrapper(top_k_results = 1, doc_content_chars_max = 100) wikipediaQueryRun = WikipediaQueryRun(api_wrapper = wikipediaAPIWrapper) resultString = wikipediaQueryRun.invoke({"query" : "langchain"}) print(resultString) print() print(f"Name : {wikipediaQueryRun.name }") print(f"Description : {wikipediaQueryRun.description }") print(f"args schema : {wikipediaQueryRun.args }") print(f"returns directly? : {wikipediaQueryRun.return_direct}") """ Page: LangChain Summary: LangChain is a framework designed to simplify the creation of applications Name : wikipedia Description : A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query. args schema : {'query': {'description': 'query to look up on wikipedia', 'title': 'Query', 'type': 'string'}} returns directly? : False """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 beautifulsoup4==4.12.3 certifi==2024.8.30 charset-normalizer==3.3.2 dataclasses-json==0.6.7 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-community==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 marshmallow==3.22.0 multidict==6.1.0 mypy-extensions==1.0.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic-settings==2.5.2 pydantic_core==2.23.4 python-dotenv==1.0.1 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 soupsieve==2.6 SQLAlchemy==2.0.35 tenacity==8.5.0 typing-inspect==0.9.0 typing_extensions==4.12.2 urllib3==2.2.3 wikipedia==1.4.0 yarl==1.11.1 |
※ pip install langchain-community wikipedia 명령을 실행했다.
■ WikipediaQueryRun 클래스의 invoke 메소드를 사용해 질의하는 방법을 보여준다. ▶ main.py
|
from langchain_community.utilities import WikipediaAPIWrapper from langchain_community.tools import WikipediaQueryRun wikipediaAPIWrapper = WikipediaAPIWrapper(top_k_results = 1, doc_content_chars_max = 100) wikipediaQueryRun = WikipediaQueryRun(api_wrapper = wikipediaAPIWrapper) resultString = wikipediaQueryRun.invoke({"query" : "langchain"}) print(resultString) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 beautifulsoup4==4.12.3 certifi==2024.8.30 charset-normalizer==3.3.2 dataclasses-json==0.6.7 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-community==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 marshmallow==3.22.0 multidict==6.1.0 mypy-extensions==1.0.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic-settings==2.5.2 pydantic_core==2.23.4 python-dotenv==1.0.1 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 soupsieve==2.6 SQLAlchemy==2.0.35 tenacity==8.5.0 typing-inspect==0.9.0 typing_extensions==4.12.2 urllib3==2.2.3 wikipedia==1.4.0 yarl==1.11.1 |
※ pip install langchain-community wikipedia 명령을 실행했다.
■ WikipediaQueryRun 클래스의 생성자에서 api_wrapper 인자를 사용해 WikipediaQueryRun 객체를 만드는 방법을 보여준다. ▶ main.py
|
from langchain_community.utilities import WikipediaAPIWrapper from langchain_community.tools import WikipediaQueryRun wikipediaAPIWrapper = WikipediaAPIWrapper(top_k_results = 1, doc_content_chars_max = 100) wikipediaQueryRun = WikipediaQueryRun(api_wrapper = wikipediaAPIWrapper) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 beautifulsoup4==4.12.3 certifi==2024.8.30 charset-normalizer==3.3.2 dataclasses-json==0.6.7 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-community==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 marshmallow==3.22.0 multidict==6.1.0 mypy-extensions==1.0.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic-settings==2.5.2 pydantic_core==2.23.4 python-dotenv==1.0.1 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 soupsieve==2.6 SQLAlchemy==2.0.35 tenacity==8.5.0 typing-inspect==0.9.0 typing_extensions==4.12.2 urllib3==2.2.3 wikipedia==1.4.0 yarl==1.11.1 |
※ pip install langchain-community
더 읽기
■ WikipediaAPIWrapper 클래스의 생성자에서 top_k_results/doc_content_chars_max 인자를 사용해 WikipediaAPIWrapper 객체를 만드는 방법을 보여준다. ▶ main.py
|
from langchain_community.utilities import WikipediaAPIWrapper wikipediaAPIWrapper = WikipediaAPIWrapper(top_k_results = 1, doc_content_chars_max = 100) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 beautifulsoup4==4.12.3 certifi==2024.8.30 charset-normalizer==3.3.2 dataclasses-json==0.6.7 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-community==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 marshmallow==3.22.0 multidict==6.1.0 mypy-extensions==1.0.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic-settings==2.5.2 pydantic_core==2.23.4 python-dotenv==1.0.1 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 soupsieve==2.6 SQLAlchemy==2.0.35 tenacity==8.5.0 typing-inspect==0.9.0 typing_extensions==4.12.2 urllib3==2.2.3 wikipedia==1.4.0 yarl==1.11.1 |
※ pip install langchain-community
더 읽기
■ BaseTool 클래스의 invoke 메소드에서 ToolCall 사용해 도구에서 생성된 컨텐츠와 아티펙트가 모두 포함된 ToolMessage 객체를 반환하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
import random from langchain_core.tools import BaseTool from typing import Tuple from typing import List class GenerateRandomValueTool(BaseTool): name : str = "GenerateRandomValueTool" description : str = "Generate size random floats in the range [min, max]." response_format : str = "content_and_artifact" decimalPointCount : int = 2 def _run(self, min : float, max : float, size : int) -> Tuple[str, List[float]]: rangeValue = max - min randomValueList = [round(min + (rangeValue * random.random()), ndigits = self.decimalPointCount) for _ in range(size)] content = f"Generated {size} floats in [{min}, {max}], rounded to {self.decimalPointCount} decimals." return content, randomValueList generateRandomValueTool = GenerateRandomValueTool(decimalPointCount = 4) resultToolMessage = generateRandomValueTool.invoke( { "name" : "generate_random_floats", "args" : {"min" : 0.1, "max" : 3.3333, "size" : 3}, "id" : "123", "type" : "tool_call" } ) print(resultToolMessage) |
▶
더 읽기
■ StructuredTool 클래스의 invoke 메소드에서 ToolCall 사용해 도구에서 생성된 콘텐츠와 아티팩트가 모두 포함된 ToolMessage 객체를 반환하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
import random from langchain_core.tools import tool from typing import Tuple from typing import List @tool(response_format = "content_and_artifact") def generateRandomInteger(min : int, max : int, size : int) -> Tuple[str, List[int]]: """Generate size random ints in the range [min, max].""" rangeList = [random.randint(min, max) for _ in range(size)] content = f"Successfully generated array of {size} random ints in [{min}, {max}]." return content, rangeList resultToolMessage = generateRandomInteger.invoke( { "name" : "generateRandomInteger", "args" : {"min" : 0, "max" : 9, "size" : 10}, "id" : "123", # required "type" : "tool_call" # required } ) print(resultToolMessage) |
▶
더 읽기
■ @tool 데코레이터에서 response_format 인자를 사용해 컨텐트를 반환하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
import random from langchain_core.tools import tool from typing import Tuple from typing import List @tool(response_format = "content_and_artifact") def generateRandomIntegerValues(minimumValue : int, maximumValue : int, count : int) -> Tuple[str, List[int]]: """Generate size random ints in the range [minimumValue, maximumValue].""" array = [random.randint(minimumValue, maximumValue) for _ in range(count)] content = f"Successfully generated array of {count} random ints in [{minimumValue}, {maximumValue}]." return content, array responseString = generateRandomIntegerValues.invoke({"minimumValue" : 0, "maximumValue" : 9, "count" : 10}) print(responseString) """ Successfully generated array of 10 random ints in [0, 9]. """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip install langchain 명령을 실행했다.
■ StructuredTool 클래스의 from_function 정적 메소드에서 handle_tool_error 인자를 사용해 도구 오류를 처리하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
from langchain_core.tools import ToolException from langchain_core.tools import StructuredTool def getWeather(city : str) -> int: """Get weather for the given city.""" raise ToolException(f"Error : There is no city by the name of {city}.") def _handleError(toolException : ToolException) -> str: return f"The following errors occurred during tool execution : `{toolException.args[0]}`" getWeatherTool = StructuredTool.from_function( func = getWeather, handle_tool_error = _handleError, ) resultString = getWeatherTool.invoke({"city" : "foobar"}) print(resultString) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip
더 읽기
■ StructuredTool 클래스의 from_function 정적 메소드에서 handle_tool_error 인자를 사용해 도구 오류를 처리하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
from langchain_core.tools import ToolException from langchain_core.tools import StructuredTool def getWeather(city : str) -> int: """Get weather for the given city.""" raise ToolException(f"Error : There is no city by the name of {city}.") getWeatherTool = StructuredTool.from_function( func = getWeather, handle_tool_error = "There is no such city, but it's probably above 0K there!" ) resultString = getWeatherTool.invoke({"city" : "foobar"}) print(resultString) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip
더 읽기
■ StructuredTool 클래스의 from_function 정적 메소드에서 handle_tool_error 인자를 사용해 도구 오류를 처리하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
from langchain_core.tools import ToolException from langchain_core.tools import StructuredTool def getWeather(city : str) -> int: """Get weather for the given city.""" raise ToolException(f"Error : There is no city by the name of {city}.") getWeatherTool = StructuredTool.from_function( func = getWeather, handle_tool_error = True, ) resultString = getWeatherTool.invoke({"city" : "foobar"}) print(resultString) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip
더 읽기
■ StructuredTool 클래스의 from_function 정적 메소드에서 func/coroutine 인자를 사용해 도구 함수를 동기/비동기 호출하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
import asyncio from langchain_core.tools import StructuredTool def multiply(a : int, b : int) -> int: """Multiply two numbers.""" return a * b async def multiplyAsync(a : int, b : int) -> int: """Multiply two numbers.""" return a * b calculatorTool = StructuredTool.from_function(func = multiply, coroutine = multiplyAsync) async def main(): print(calculatorTool.invoke({"a" : 2, "b" : 3})) print(await calculatorTool.ainvoke({"a": 2, "b": 5})) asyncio.run(main()) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※
더 읽기
■ StructuredTool 클래스의 from_function 정적 메소드에서 func 인자를 사용해 도구 함수를 동기/비동기 호출하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
import asyncio from langchain_core.tools import StructuredTool def multiply(a : int, b : int) -> int: """Multiply two numbers.""" return a * b calculatorTool = StructuredTool.from_function(func = multiply) async def main(): print(calculatorTool.invoke({"a" : 2, "b" : 3})) print(await calculatorTool.ainvoke({"a" : 2, "b" : 5})) asyncio.run(main()) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※
더 읽기
■ BaseTool 클래스를 사용해 도구를 만드는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
import asyncio from pydantic import BaseModel from pydantic import Field from langchain_core.tools import BaseTool from typing import Type from typing import Optional from langchain_core.callbacks import CallbackManagerForToolRun from langchain_core.callbacks import AsyncCallbackManagerForToolRun class CalculatorModel(BaseModel): a : int = Field(description = "first number") b : int = Field(description = "second number") class CalculatorTool(BaseTool): name : str = Field(default = "Calculator" ) description : str = Field(default = "유용한 수학 계산을 수행합니다.") args_schema : Type[BaseModel] = CalculatorModel return_direct : bool = True def _run(self, a : int, b : int, run_manager : Optional[CallbackManagerForToolRun] = None) -> str: """Use the tool.""" return a * b async def _arun(self, a : int, b : int, run_manager : Optional[AsyncCallbackManagerForToolRun] = None) -> str: """Use the tool asynchronously.""" # 계산이 저렴하다면, 아래에 표시된 것처럼 동기화 구현에 위임하면 된다. # 동기화 계산이 비싸다면, _arun 메서드 전체를 삭제해야 한다. # LangChain은 자동으로 더 나은 구현을 제공하여 다른 비동기 코드를 차단하지 않도록 스레드에서 작업을 시작한다. return self._run(a, b, run_manager = run_manager.get_sync()) async def main(): calculatorTool = CalculatorTool() print(calculatorTool.name ) print(calculatorTool.description ) print(calculatorTool.args ) print(calculatorTool.return_direct) print(calculatorTool.invoke({"a" : 2, "b" : 3})) print(await calculatorTool.ainvoke({"a" : 2, "b" : 3})) asyncio.run(main()) """ Calculator 유용한 수학 계산을 수행합니다. {'a': {'description': 'first number', 'title': 'A', 'type': 'integer'}, 'b': {'description': 'second number', 'title': 'B', 'type': 'integer'}} True 6 6 """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip install langchain 명령을 실행했다.
■ BaseTool 클래스를 사용해 도구를 만드는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
from langchain.tools import BaseTool from pydantic import Field class CalculatorTool(BaseTool): name : str = Field(default = "Calculator" ) description : str = Field(default = "유용한 수학 계산을 수행합니다.") def _run(self, query : str) -> str: """주어진 수학 표현식을 계산합니다.""" try: result = eval(query) return f"계산 결과 : {result}" except: return "올바른 수학 표현식이 아닙니다. 다시 시도해주세요." async def _arun(self, query : str) -> str: """비동기 실행을 위한 메서드입니다.""" return self._run(query) calculatorTool = CalculatorTool() result = calculatorTool.run("2 + 2") print(result) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip install langchain 명령을 실행했다.
■ GenericFakeChatModel 클래스의 생성자에서 messages 인자를 사용해 GenericFakeChatModel 객체를 만드는 방법을 보여준다. ▶ 예제 코드 (PY)
|
from langchain_core.language_models import GenericFakeChatModel genericFakeChatModel = GenericFakeChatModel(messages = iter(["hello matey"])) |
※ pip install langchain 명령을
더 읽기
■ RunnableSequence 클래스의 as_tool 메소드를 사용해 도구를 만드는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
from langchain_core.prompts import ChatPromptTemplate from langchain_core.language_models import GenericFakeChatModel from langchain_core.output_parsers import StrOutputParser chatPromptTemplate = ChatPromptTemplate.from_messages([("human", "Hello. Please respond in the style of {answer_style}.")]) genericFakeChatModel = GenericFakeChatModel(messages = iter(["hello matey"])) runnableSequence = chatPromptTemplate | genericFakeChatModel | StrOutputParser() structuredTool = runnableSequence.as_tool(name = "Style responder", description = "Description of when to use tool.") print(structuredTool.args) """ {'answer_style': {'title': 'Answer Style', 'type': 'string'}} """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip install langchain 명령을 실행했다.
■ StructuredTool 클래스의 from_function 정적 메소드에서 args_schema 인자를 사용해 BaseModel 객체를 설정하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
from pydantic import BaseModel from pydantic import Field from langchain_core.tools import StructuredTool class CalculatorModel(BaseModel): a : int = Field(description = "first number" ) b : int = Field(description = "second number") def multiply(a : int, b : int) -> int: """Multiply two numbers.""" return a * b calculatorTool = StructuredTool.from_function( func = multiply, name = "Calculator", description = "multiply numbers", args_schema = CalculatorModel, return_direct = True, ) print(calculatorTool.invoke({"a" : 2, "b" : 3})) print(calculatorTool.name ) print(calculatorTool.description) print(calculatorTool.args ) """ 6 Calculator multiply numbers {'a': {'description': 'first number', 'title': 'A', 'type': 'integer'}, 'b': {'description': 'second number', 'title': 'B', 'type': 'integer'}} """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip
더 읽기
■ StructuredTool 클래스의 from_function 정적 메소드에서 func/coroutine 인자를 사용해 동기/비동기 함수를 설정하는 방법을 보여준다. ▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
import asyncio from langchain_core.tools import StructuredTool def multiply(a : int, b : int) -> int: """Multiply two numbers.""" return a * b async def multiplyAsync(a: int, b: int) -> int: """Multiply two numbers.""" return a * b async def main(): calculatorTool = StructuredTool.from_function(func = multiply, coroutine = multiplyAsync) print(calculatorTool.invoke({"a" : 2, "b" : 3})) print(await calculatorTool.ainvoke({"a" : 2, "b" : 5})) asyncio.run(main()) |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
aiohappyeyeballs==2.4.0 aiohttp==3.10.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 attrs==24.2.0 certifi==2024.8.30 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.1.0 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.3.0 langchain-core==0.3.1 langchain-text-splitters==0.3.0 langsmith==0.1.122 multidict==6.1.0 numpy==1.26.4 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 PyYAML==6.0.2 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.35 tenacity==8.5.0 typing_extensions==4.12.2 urllib3==2.2.3 yarl==1.11.1 |
※ pip
더 읽기