Ошибка проверки ввода: «1.57» не имеет типа «номер» из langchain_mcp_adapterPython

Программы на Python
Anonymous
Ошибка проверки ввода: «1.57» не имеет типа «номер» из langchain_mcp_adapter

Сообщение Anonymous »

Я получаю следующую ошибку: ❌ Произошла ошибка: Ошибка проверки ввода: «1.57» не имеет типа «число».
Насколько я понимаю, это происходит до вызова сервера MCP: адаптер LangChain MCP проверяет аргументы вызова инструмента по схеме JSON, и модель выдает «1.57» в виде строки вместо 1.57 как число, поэтому проверка не удалась.
Правильно ли это понимание? И как с этим рекомендуется бороться при использовании create_agent(model,tools) и инструментов MCP
Код:
import os
import asyncio
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain_mcp_adapters.client import MultiServerMCPClient
import logging

logging.basicConfig(level=logging.DEBUG)

logging.getLogger("langchain_mcp_adapters").setLevel(logging.DEBUG)
logging.getLogger("mcp").setLevel(logging.DEBUG)

load_dotenv()

async def main():
try:
# 1.Get tools from MCP server
mcp_server_url = os.getenv("MCP_SERVER_URL", "http://localhost:3001/mcp")
client = MultiServerMCPClient({
"nav2_mcp_server": {
"transport": "streamable_http",
"url": mcp_server_url,
}
})

print("🔧 Fetching tools from Nav2 MCP server...")
tools = await client.get_tools()

print(f"✅ Retrieved {len(tools)} tools from physical-agentic-robot-mcp server:")
for tool in tools:
# print(f" • {tool.name}: {tool.description}")
print(f" • {tool.name}: {tool.args_schema}")

# 2.Create LLM model
model = init_chat_model(model = "llama3.2:3b", model_provider="ollama")

# 3. Create agent with tools from MCP server
agent = create_agent(model, tools, system_prompt="You are the brains of the robot and need to call the correct tools with correct tool json schema arguments.")

# 4. Use the agent to get documentation
# query = "Is there any green trash can in environment, can you move there?"
query = "Navigate 1m forward, then turn 90 degrees to the right, and move another 1m forward."
print(f"👤 User: {query}\n")

response = await agent.ainvoke({"messages": [("human", query)]})
last_message = response["messages"][-1]

print(f"🤖 Agent: {last_message.content}\n")
except Exception as e:
print(f"❌ An error occurred: {e}")

finally:
print("✅ MCP client connection closed")

if __name__ == "__main__":
asyncio.run(main())

Пример инструмента сервера MCP
@mcp.tool(
name='navigate_to_pose',
description="""Navigate the robot to a specific pose (position and
orientation) in the map frame.

Example usage:
- navigate to position (2.0, 3.0) with orientation 1.57
- go to x=2 y=3 with yaw=90 degrees
- move to coordinates (2, 3) facing north
""",
tags={'navigate', 'go to', 'move to', 'navigate to pose', 'position'},
annotations={
'title': 'Navigate To Pose',
'readOnlyHint': False,
'openWorldHint': False
},
)
async def navigate_to_pose(
x: Annotated[float, 'X coordinate of target pose in map frame'],
y: Annotated[float, 'Y coordinate of target pose in map frame'],
yaw: Annotated[
float,
'Orientation in radians (0=east, π/2=north, π=west, 3π/2=south)'
] = 0.0,
ctx: Annotated[
Optional[Context],
'MCP context used for logging and progress msgs'
] = None,
) -> str:

Вернуться в «Python»