Важно отметить, что я использую langgraph.prebuilt.create_react_agent для создания агент. Я знаю, что существует множество других способов создания агента, но, просмотрев код langgraph.prebuilt, я не вижу причин, по которым он не будет работать.
В конце у меня также есть список того, что я пробовал, и при необходимости могу предоставить подробную информацию.
Версии библиотек:
Код: Выделить всё
langchain-core==0.3.10
langchain-ollama==0.2.0
langgraph==0.2.39
langgraph-checkpoint==2.0.2
Код: Выделить всё
import os
import asyncio
import json
import uuid
from dotenv import load_dotenv
from langchain_core.messages import HumanMessage
from langchain_ollama import ChatOllama
from langchain_core.tools import tool
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent
load_dotenv("../.env")
thing_list = [
{"name": "Thing0", "location": "paris"},
{"name": "Thing1", "location": "london"},
{"name": "Thing2", "location": "berlin"},
{"name": "Thing3", "location": "paris"},
]
@tool
def get_thing_location(symbol: str) -> str:
"""
Retrieves the location of the thing.
Args:
symbol (str): The symbol of the thing to find.
Returns:
str: the location value.
"""
thing = next((item for item in thing_list if item["name"] == symbol), None)
return thing["location"] if thing else None
@tool
def find_things_by_location(location: str) -> list:
"""
Retrieves a list of things based on their location.
Args:
location (str): The location to look for things.
Returns:
list: list of things at the location.
"""
return [thing for thing in thing_list if thing["location"] == location]
modelName=os.getenv("LLM_MODEL", "llama3.2:3b")
ollamaUrl=os.getenv("OLLAMA_URL")
model = ChatOllama(model=modelName, base_url=ollamaUrl)
memory = MemorySaver()
threadId = "thing-agent"
config = {"configurable": {"thread_id": threadId}}
agent = create_react_agent(
model=model,
tools=[find_things_by_location, get_thing_location],
checkpointer=memory,
)
thingLoc = get_thing_location('Thing0');
print(f"Location of Thing0: {thingLoc}")
otherThings = find_things_by_location(thingLoc)
print(f"Things in same location: {otherThings}")
msgs = [
HumanMessage(content="""
What is the location of Thing0?
What other things are in the same location?
"""),
]
from color_outputs import print_event
async def run():
async for event in (agent.astream_events(
{"messages": msgs},
version="v2", config=config)):
print_event(event)
asyncio.run(run())
Код: Выделить всё
Location of Thing0: paris
Things in same location: [{'name': 'Thing0', 'location': 'paris'}, {'name': 'Thing3', 'location': 'paris'}]
agent on_chain_start (['graph:step:1'])
Starting agent: agent with input messages:
Human:
What is the location of Thing0?
What other things are in the same location?
-------------
--------------------
get_thing_location on_tool_start (['seq:step:1'])
Starting tool: get_thing_location with inputs: {'symbol': 'Thing0'}
--------------------
find_things_by_location on_tool_start (['seq:step:1'])
Starting tool: find_things_by_location with inputs: {'location': 'get_thing_location', 'symbol': 'Thing0'}
--------------------
find_things_by_location on_tool_end (['seq:step:1'])
Done tool: find_things_by_location
Tool output was: content=[] name='find_things_by_location' tool_call_id='8f012dd4-6082-4bd1-bbaa-e82eba61eca0'
--------------------
get_thing_location on_tool_end (['seq:step:1'])
Done tool: get_thing_location
Tool output was: content='paris' name='get_thing_location' tool_call_id='7fc27e00-29be-48b1-ab7a-d640cee96212'
--------------------
agent on_chain_start (['graph:step:3'])
Starting agent: agent with input messages:
Human:
What is the location of Thing0?
What other things are in the same location?
-------------
AI:
-------------
Tool: get_thing_location: paris
-------------
Tool: find_things_by_location: []
-------------
--------------------
Process finished with exit code 0
Что я пробовал:
- Различные модели:
llama3.1:70b - mistral-large:123b
- мистраль-немо:12b
- llama3.2:3b
Добавление модификатора состояния с подсказкой, описывающей цикл «Думай-Действуй-Наблюдай-Повторяй».
[*]Сделай эту подсказку более или менее подробной или явно включая ограничения на то, когда и какой инструмент использовать.
Подробнее здесь: https://stackoverflow.com/questions/791 ... ple-cycles
Мобильная версия