Without web search¶
In [1]:
from dotenv import load_dotenv
load_dotenv()
Out[1]:
True
In [2]:
import os
from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
from langchain.messages import HumanMessage, AIMessage
from langchain.tools import tool
from typing import Dict, Any
from tavily import TavilyClient
from pprint import pprint
DEEPSEEK_MODEL = "deepseek-chat"
DEEPSEEK_BASE_URL = "https://api.deepseek.com"
def deepseek_model(model: str = DEEPSEEK_MODEL, max_tokens=1000, **kwargs):
return init_chat_model(
model=model,
# DeepSeek uses LangChain's OpenAI-compatible transport.
model_provider="openai",
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url=DEEPSEEK_BASE_URL,
max_tokens=max_tokens,
**kwargs,
)
In [3]:
agent = create_agent(
model=deepseek_model()
)
In [6]:
question = {
"role":"user",
"content":"Who is the principal of Birralee Primary School?"
}
user_input = {"messages": question}
from tavily import TavilyClient
tavily_client = TavilyClient()
@tool ("web_search", description = "Search web")
def web_search(query: str) -> Dict[str, any]:
return tavily_client.search(query, search_depth="basic")
agent = create_agent(
deepseek_model(),
tools=[web_search]
)
response = agent.invoke(user_input)
print(response)
{'messages': [HumanMessage(content='Who is the principal of Birralee Primary School?', additional_kwargs={}, response_metadata={}, id='886a4412-a243-4afd-9a4c-87f37bfd1b16'), AIMessage(content='', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 48, 'prompt_tokens': 279, 'total_tokens': 327, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}, 'prompt_cache_hit_tokens': 0, 'prompt_cache_miss_tokens': 279}, 'model_provider': 'openai', 'model_name': 'deepseek-v4-flash', 'system_fingerprint': 'fp_8b330d02d0_prod0820_fp8_kvcache_20260402', 'id': 'c2332e8c-5dd1-4363-853c-e72fb8642644', 'finish_reason': 'tool_calls', 'logprobs': None}, id='lc_run--019e2111-61d4-7f50-ad10-1d4b8e22f3b1-0', tool_calls=[{'name': 'web_search', 'args': {'query': 'Birralee Primary School principal'}, 'id': 'call_00_Gp7P4qNVtD3XXooA9KNY6239', 'type': 'tool_call'}], invalid_tool_calls=[], usage_metadata={'input_tokens': 279, 'output_tokens': 48, 'total_tokens': 327, 'input_token_details': {'cache_read': 0}, 'output_token_details': {}}), ToolMessage(content='{"query": "Birralee Primary School principal", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://www.instagram.com/reel/DNZQvV2TZLm/", "title": "A beautiful, sunny morning at Birralee Primary School! So good to ...", "content": "Big thanks to Principal Ashley Ryan and School Council member Sherry Wang for showing us around campus, witness all the hard work in action and", "score": 0.8588255, "raw_content": null}, {"url": "https://www.birralee.vic.edu.au/ourschool.php?id=16", "title": "Birralee Primary School - Our School", "content": "As the principal of Birralee PS, I am excited to share the values and vision that guide us in providing a high-quality education for every child. Integrity, empathy, and a sense of responsibility are core values that we instil in all of our students. These values are publicly reinforced at each Monday morning assembly when we all recite the school declaration: *At Birralee we learn to live and work together:* *To show **care and kindness**,* *To behave with **integrity**,* *To be **respectful** and r**esponsible**,* *And strive to achieve our goals.* Our dedicated teachers and support staff are at the heart of our success.", "score": 0.8473754, "raw_content": null}, {"url": "https://www.heraldsun.com.au/leader/east/birralee-primary-school-principal-and-parents-warn-of-serious-safety-risk-to-children/news-story/043f8a690cda715dbfc2a45ae805c772", "title": "Birralee Primary School principal and parents warn of serious safety ...", "content": "Parents have been left jostling for position at drop-off and pick-up times, with principal Ashley Ryan warning the problem will only get worse", "score": 0.8430832, "raw_content": null}, {"url": "https://www.birralee.vic.edu.au/ourschool.php?id=48", "title": "Volunteer and Child Safe Policies - Birralee Primary School", "content": "If you have any suggestions, comments or questions in relation to our child safe policies and practices, please contact Ashley Ryan (Principal) or Jacqueline", "score": 0.8235701, "raw_content": null}, {"url": "https://www.easthartford.org/news/what_s_new/e_h_p_s_announces_new_o__brien_e_s_principal", "title": "EHPS Announces New O\'Brien Elementary School Principal", "content": "East Hartford Public Schools is proud to announce the new principal of Robert J. O\'Brien Elementary School, Diane Leja. She began her role on August 22, 2024.", "score": 0.068046756, "raw_content": null}], "response_time": 0.92, "request_id": "8caaac32-68a4-4f90-ab9d-887bad40402e"}', name='web_search', id='92c47474-176e-4467-9113-4b4b4e6e8c83', tool_call_id='call_00_Gp7P4qNVtD3XXooA9KNY6239'), AIMessage(content='The principal of Birralee Primary School is **Ashley Ryan**.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 14, 'prompt_tokens': 1027, 'total_tokens': 1041, 'completion_tokens_details': None, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 256}, 'prompt_cache_hit_tokens': 256, 'prompt_cache_miss_tokens': 771}, 'model_provider': 'openai', 'model_name': 'deepseek-v4-flash', 'system_fingerprint': 'fp_8b330d02d0_prod0820_fp8_kvcache_20260402', 'id': '64b2a944-504c-451c-b999-ae8eae3c61b4', 'finish_reason': 'stop', 'logprobs': None}, id='lc_run--019e2111-6dc1-7fe1-a423-4be4316f1abe-0', tool_calls=[], invalid_tool_calls=[], usage_metadata={'input_tokens': 1027, 'output_tokens': 14, 'total_tokens': 1041, 'input_token_details': {'cache_read': 256}, 'output_token_details': {}})]}
In [7]:
print(response['messages'][-1].content)
The principal of Birralee Primary School is **Ashley Ryan**.
Add web search tool¶
In [ ]:
web_results=web_search.invoke("Who is the current mayor of San Francisco?")
In [ ]:
agent = create_agent(
model=deepseek_model(),
tools=[web_search]
)
question = HumanMessage(content="Who is the current mayor of San Francisco?")
response = agent.invoke(
{"messages": [question]}
)
In [ ]:
for msg in response["messages"]:
pprint(msg)
print()
In [ ]:
import json
content = response['messages'][2].content
data = json.loads(content) # string -> dict
pprint(data)
In [ ]:
print(response['messages'][-1].content)
In [ ]: