■ StructuredTool 클래스의 invoke 메소드에서 AIMessage 객체의 tool_calls 속성 값을 사용해 ToolMessage 객체를 구하는 방법을 보여준다.
※ OPENAI_API_KEY 환경 변수 값은 .env 파일에 정의한다.
▶ 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 |
import random from dotenv import load_dotenv from langchain_core.tools import tool from typing import Tuple from typing import List from langchain_openai import ChatOpenAI load_dotenv() @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 chatOpenAI = ChatOpenAI(model = "gpt-4o-mini") runnableBindable = chatOpenAI.bind_tools([generateRandomIntegerValues]) responseAIMessage = runnableBindable.invoke("generate 6 positive ints less than 25") responseToolMessage = generateRandomIntegerValues.invoke(responseAIMessage.tool_calls[0]) print(responseToolMessage) """ content='Successfully generated array of 6 random ints in [1, 24].' name='generateRandomIntegerValues' tool_call_id='call_OgLpy9rZDTvCukX9RLIcEuGT' artifact=[2, 21, 13, 1, 24, 8] """ |
▶ 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 |
annotated-types==0.7.0 anyio==4.6.0 certifi==2024.8.30 charset-normalizer==3.3.2 distro==1.9.0 exceptiongroup==1.2.2 h11==0.14.0 httpcore==1.0.5 httpx==0.27.2 idna==3.10 jiter==0.5.0 jsonpatch==1.33 jsonpointer==3.0.0 langchain-core==0.3.6 langchain-openai==0.2.1 langsmith==0.1.129 openai==1.50.2 orjson==3.10.7 packaging==24.1 pydantic==2.9.2 pydantic_core==2.23.4 python-dotenv==1.0.1 PyYAML==6.0.2 regex==2024.9.11 requests==2.32.3 sniffio==1.3.1 tenacity==8.5.0 tiktoken==0.7.0 tqdm==4.66.5 typing_extensions==4.12.2 urllib3==2.2.3 |
※ pip install langchain-openai 명령을 실행했다.