Код: Выделить всё
from langchain_openai import ChatOpenAI
from langchain_core.messages import SystemMessage, HumanMessage
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
# Model initialization
model = ChatOpenAI(
model="gpt-4.1",
temperature=0.3
)
# State definition
class AssistanceState(TypedDict):
messages: Annotated[list, add_messages]
user_profile: Dict
chat_id: str
# ... other fields
# Node function where I want to use web_search_preview
def conversation(state: AssistanceState) -> AssistanceState:
user_profile = state.get("user_profile", {})
system_content = f"""
Eres un asistente culinario experto...
{user_profile}
"""
messages = [SystemMessage(content=system_content)] + state["messages"]
config = {"configurable": {"thread_id": state["chat_id"]}}
# This is where I want to add web_search_preview tool
response = model.invoke(messages, config=config)
return {"messages": [response]}
< /code>
Что я попробовал < /h2>
Я попытался связать инструмент с моделью, как это: < /p>
# Attempt 1: Binding tools before invoke
model.bind_tools(tools=[{"type": "web_search_preview"}])
response = model.invoke(messages, config=config, tools=[{"type": "web_search_preview"}])
# Attempt 2: Passing tools directly in invoke
response = model.invoke(messages, config=config, tools=[{"type": "web_search_preview"}])
# Attempt 3: Using the OpenAI client directly (this works)
def search_web_openai(query: str) -> str:
response = client.responses.create(
model="gpt-4.1",
tools=[{"type": "web_search_preview"}],
input=query
)
# ... process response
Инструмент web_search_preview работает отлично, когда я использую клиент Openai напрямую, но когда я пытаюсь интегрировать его в свой рабочий пофон с использованием модели. />
[*] Как я могу правильно добавить инструмент web_search_preview к модели Langchain в узле Langgraph?
есть ли конкретный способ настроить модель, чтобы использовать этот инструмент в контексте состояния? Чтобы инструмент для работы с методом вызова Лэнгхейна? /> Python: 3.9+< /li>
< /ul>
ожидаемое поведение < /h2>
Я хочу, чтобы модель была способна использовать инструмент Web_search_preview < /code> при ответе на запросы пользователей в рамках моего LANGGRAP Будьте очень ценят!
Подробнее здесь: https://stackoverflow.com/questions/796 ... ain-invoke