大模型只是知道要调用工具,本身不能直接调用工具
from init_llm import deepseek_llm
from langchain.agents import create_agent
from langchain.agents.middleware import wrap_model_call, ModelRequest, ModelResponse
from langchain.chat_models import init_chat_model
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain_core.messages import HumanMessage, AIMessage, ToolMessage, function
from init_llm import deepseek_llm
@tool
def get_weather(local:str) ->str:
"""获取天气信息"""
return f"{local}天气非常好"
model_with_tool=deepseek_llm.bind_tools(get_weather)
messages=\[\]
human_message=HumanMessage(content="北京天气怎么样")
messages.append(human_message)
response=model_with_tool.invoke((messages))
messages.append(response)
if response.tool_calls:
for tool_call in response.tool_calls:
if tool_call"name"=="get_weather":
tool_result=get_weather.invoke(tool_call)
messages.append(tool_result)
print(type(tool_result))
print(tool_result)
print(model_with_tool.invoke((messages)))
print(messages)
[HumanMessage(content='北京天气怎么样', additional_kwargs={}, response_metadata={}),
AIMessage(content='好的,我来查一下北京的天气信息。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 53, 'prompt_tokens': 273, 'total_tokens': 326, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 256}, 'prompt_cache_hit_tokens': 256, 'prompt_cache_miss_tokens': 17}, 'model_provider': 'deepseek', 'model_name': 'deepseek-v4-flash', 'system_fingerprint': 'fp_8b330d02d0_prod0820_fp8_kvcache_20260402', 'id': 'e9a0aca0-1731-4f21-88e4-68c0634f1814', 'finish_reason': 'tool_calls', 'logprobs': None}, id='lc_run--019e78d0-0b95-7a51-a56f-6c93d100c1ef-0', tool_calls={'name': 'get_weather', 'args': {'local': '北京'}, 'id': 'call_00_iWUvgLsMXG29jlpAZTQZ8672', 'type': 'tool_call'}, invalid_tool_calls=\[\], usage_metadata={'input_tokens': 273, 'output_tokens': 53, 'total_tokens': 326, 'input_token_details': {'cache_read': 256}, 'output_token_details': {}}),
ToolMessage(content='北京天气非常好', name='get_weather', tool_call_id='call_00_iWUvgLsMXG29jlpAZTQZ8672')]