■ RunnableLambda 클래스를 사용해 도구 내에서 실행 가능 항목 호출시 실행 가능 항목에 콜백을 전파하는 방법을 보여준다.
▶ 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 |
import asyncio from langchain_core.tools import tool from langchain_core.runnables import RunnableLambda async def main(): def reverseWord(word : str): return word[::-1] runnableLambda = RunnableLambda(reverseWord) @tool def reverseWordTool(word : str, callbacks): """A tool that correctly propagates callbacks.""" return runnableLambda.invoke(word, {"callbacks" : callbacks}) async for eventDictionary in reverseWordTool.astream_events("hello", version = "v2"): print(eventDictionary) asyncio.run(main()) """ {'event': 'on_tool_start', 'data': {'input': 'hello'}, 'name': 'bad_tool', 'tags': [], 'run_id': 'dd955c59-750b-4f92-832e-b786b3991788', 'metadata': {}, 'parent_ids': []} {'event': 'on_chain_start', 'data': {'input': 'hello'}, 'name': 'reverseWord', 'tags': [], 'run_id': '43a72990-24e9-4b09-9130-b18c57b54cbc', 'metadata': {}, 'parent_ids': ['dd955c59-750b-4f92-832e-b786b3991788']} {'event': 'on_chain_end', 'data': {'output': 'olleh', 'input': 'hello'}, 'run_id': '43a72990-24e9-4b09-9130-b18c57b54cbc', 'name': 'reverseWord', 'tags': [], 'metadata': {}, 'parent_ids': ['dd955c59-750b-4f92-832e-b786b3991788']} {'event': 'on_tool_end', 'data': {'output': 'olleh'}, 'run_id': 'dd955c59-750b-4f92-832e-b786b3991788', 'name': 'bad_tool', 'tags': [], 'metadata': {}, 'parent_ids': []} {'event': 'on_tool_start', 'data': {'input': 'hello'}, 'name': 'correct_tool', 'tags': [], 'run_id': 'c9001a82-3304-4db0-b447-aa5812e8bbfc', 'metadata': {}, 'parent_ids': []} {'event': 'on_chain_start', 'data': {'input': 'hello'}, 'name': 'reverseWord', 'tags': [], 'run_id': '4076da43-cac8-4938-a7ea-a9221f06225a', 'metadata': {}, 'parent_ids': ['c9001a82-3304-4db0-b447-aa5812e8bbfc']} {'event': 'on_chain_end', 'data': {'output': 'olleh', 'input': 'hello'}, 'run_id': '4076da43-cac8-4938-a7ea-a9221f06225a', 'name': 'reverseWord', 'tags': [], 'metadata': {}, 'parent_ids': ['c9001a82-3304-4db0-b447-aa5812e8bbfc']} {'event': 'on_tool_end', 'data': {'output': 'olleh'}, 'run_id': 'c9001a82-3304-4db0-b447-aa5812e8bbfc', 'name': 'correct_tool', 'tags': [], 'metadata': {}, 'parent_ids': []} """ |
▶ 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 |
aiohttp==3.9.5 aiosignal==1.3.1 annotated-types==0.7.0 async-timeout==4.0.3 attrs==23.2.0 certifi==2024.6.2 charset-normalizer==3.3.2 frozenlist==1.4.1 greenlet==3.0.3 idna==3.7 jsonpatch==1.33 jsonpointer==3.0.0 langchain==0.2.5 langchain-core==0.2.8 langchain-text-splitters==0.2.1 langsmith==0.1.79 multidict==6.0.5 numpy==1.26.4 orjson==3.10.5 packaging==24.1 pydantic==2.7.4 pydantic_core==2.18.4 PyYAML==6.0.1 requests==2.32.3 SQLAlchemy==2.0.30 tenacity==8.4.1 typing_extensions==4.12.2 urllib3==2.2.2 yarl==1.9.4 |
※ pip install langchain 명령을 실행했다.