Skip to main content
LangChain is a software framework that helps facilitate the integration of large language models (LLMs) into applications. As a language model integration framework, LangChain’s use-cases largely overlap with those of language models in general, including document analysis and summarization, chatbots, and code analysis. Building your AI app with LangChain? Supercharge your app with immediate access to real-time data, spanning news, entertainment, finance, stock market data, weather, and more.

Getting Started

Installation

To install the langchain-dappier package, run:
pip install langchain-dappier

Setting API Credentials

Generate an API key from the Dappier platform and set it as an environment variable:
Python
import os
import getpass

if not os.environ.get("DAPPIER_API_KEY"):
    os.environ["DAPPIER_API_KEY"] = getpass.getpass("Dappier API key:")
For LangSmith tracing, set your API key:
Python
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"

Dappier Tool

Overview

The DappierRealTimeSearchTool and DappierAIRecommendationTool empower AI applications with real-time data and AI-driven insights. The DappierRealTimeSearchTool provides access to up-to-date information across news, weather, travel, and financial markets, while the DappierAIRecommendationTool enhances applications with factual, premium content from domains like News, Finance, and Sports, powered by Dappier’s pre-trained RAG models and natural language APIs.

DappierRealTimeSearchTool

You can also check this cookbook in colab here

Watch the Video

If you prefer a visual walkthrough, check out the accompanying video below:

Features

The DappierRealTimeSearchTool provides real-time Google search results, including:
  • Latest news, weather, and travel deals
  • Up-to-date financial news, stock prices, and trades
  • AI-enhanced insights for accurate and fast information retrieval

Instantiation

Python
from langchain_dappier import DappierRealTimeSearchTool

tool = DappierRealTimeSearchTool(
    # ai_model_id="...", # Overwrite default AI model ID
    # name="...",        # Overwrite default tool name
    # description="...", # Overwrite default tool description
)

Usage

Direct Invocation

Python
tool.invoke({"query": "What happened at the last Wimbledon"})
"At the last Wimbledon in 2024, Carlos Alcaraz won the title by defeating Novak Djokovic. This victory marked Alcaraz's fourth Grand Slam title at just 21 years old! 🎉🏆🎾"

Using ToolCall

Python
model_generated_tool_call = {
    "args": {"query": "Euro 2024 host nation"},
    "id": "1",
    "name": "dappier",
    "type": "tool_call",
}
tool_msg = tool.invoke(model_generated_tool_call)
print(tool_msg.content[:400])
Euro 2024 is being hosted by Germany! 🇩🇪 The tournament runs from June 14 to July 14, 2024, featuring 24 teams competing across various cities like Berlin and Munich. It's going to be an exciting summer of football! ⚽️🏆

Chaining with LLM

Python
from langchain.chat_models import init_chat_model

llm = init_chat_model(model="gpt-4o", model_provider="openai", temperature=0)
Python
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableConfig, chain

today = datetime.datetime.today().strftime("%D")
prompt = ChatPromptTemplate([
    ("system", f"You are a helpful assistant. The date today is {today}.")
])

llm_with_tools = llm.bind_tools([tool])
llm_chain = prompt | llm_with_tools

tool_chain = chain(lambda user_input, config: llm_chain.invoke({"user_input": user_input}, config=config))

tool_chain.invoke("Who won the last women's singles Wimbledon?")
AIMessage(content="Barbora Krejčíková won the women's singles title at Wimbledon 2024, defeating Jasmine Paolini in the final with a score of 6–2, 2–6, 6–4. This victory marked her first Wimbledon singles title and her second major singles title overall! 🎉🏆🎾", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 69, 'prompt_tokens': 222, 'total_tokens': 291, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-2024-08-06', 'system_fingerprint': 'fp_4691090a87', 'finish_reason': 'stop', 'logprobs': None}, id='run-87a385dd-103b-4344-a3be-2d6fd1dcfdf5-0', usage_metadata={'input_tokens': 222, 'output_tokens': 69, 'total_tokens': 291, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})

Parameters

ai_model_id (str) Optional:

  • The AI model ID to use for the query.
  • AI model IDs always start with the prefix "am_".
  • Defaults to "am_01j06ytn18ejftedz6dyhz2b15".
  • Multiple AI model IDs are available, which can be found at Dappier marketplace.

DappierAIRecommendationTool

Watch the Video

If you prefer a visual walkthrough, check out the accompanying video below:

Features

The DappierAIRecommendationTool delivers AI-powered recommendations using Dappier’s pre-trained RAG models:
  • Provides factual and up-to-date responses
  • Sources premium content from News, Finance, Sports, and more

Instantiation

Python
from langchain_dappier import DappierAIRecommendationTool

tool = DappierAIRecommendationTool(
    data_model_id="dm_01j0pb465keqmatq9k83dthx34",
    similarity_top_k=3,
    ref="sportsnaut.com",
    num_articles_ref=2,
    search_algorithm="most_recent",
)

Usage

Direct Invocation

Python
tool.invoke({"query": "latest sports news"})
[
    {
        "author": "Matt Weaver",
        "image_url": "https://images.dappier.com/dm_01j0pb465keqmatq9k83dthx34/Screenshot_20250117_021643_Gallery_.jpg?width=428&height=321",
        "pubdate": "Fri, 17 Jan 2025 08:04:03 +0000",
        "source_url": "https://sportsnaut.com/chili-bowl-thursday-bell-column/",
        "summary": "The article highlights the thrilling unpredictability of the Chili Bowl Midget Nationals, focusing on the dramatic shifts in fortune for drivers like Christopher Bell, Tanner Thorson, and Karter Sarff during Thursday's events. Key moments included Sarff's unfortunate pull-off and a last-lap crash that allowed Ryan Bernal to capitalize and improve his standing, showcasing the chaotic nature of the race and the importance of strategy and luck.\n\nAs the competition intensifies leading up to Championship Saturday, Bell faces the challenge of racing from a Last Chance Race, reflecting on the excitement and difficulties of the sport. The article emphasizes the emotional highs and lows experienced by racers, with insights from Bell and Bernal on the unpredictable nature of racing. Overall, it captures the camaraderie and passion that define the Chili Bowl, illustrating how each moment contributes to the event's narrative.",
        "title": "Thursday proves why every lap of Chili Bowl is so consequential"
    },
    {
        "author": "Matt Higgins",
        "image_url": "https://images.dappier.com/dm_01j0pb465keqmatq9k83dthx34/Pete-Alonso-24524027_.jpg?width=428&height=321",
        "pubdate": "Fri, 17 Jan 2025 02:48:42 +0000",
        "source_url": "https://sportsnaut.com/new-york-mets-news-pete-alonso-rejected-last-ditch-contract-offer/",
        "summary": "The New York Mets are likely parting ways with star first baseman Pete Alonso after failing to finalize a contract agreement. Alonso rejected a last-minute three-year offer worth between $68 and $70 million, leading the Mets to redirect funds towards acquiring a top reliever. With Alonso's free-agent options dwindling, speculation arises about his potential signing with another team for the 2025 season, while the Mets plan to shift Mark Vientos to first base.\n\nIn a strategic move, the Mets are also considering a trade for Toronto Blue Jays' star first baseman Vladimir Guerrero Jr. This potential acquisition aims to enhance the Mets' competitiveness as they reshape their roster. Guerrero's impressive offensive stats make him a valuable target, and discussions are in the early stages. Fans and analysts are keenly watching the situation, as a trade involving such a prominent player could significantly impact both teams.",
        "title": "MLB insiders reveal New York Mets’ last-ditch contract offer that Pete Alonso rejected"
    },
    {
        "author": "Jim Cerny",
        "image_url": "https://images.dappier.com/dm_01j0pb465keqmatq9k83dthx34/NHL-New-York-Rangers-at-Utah-25204492_.jpg?width=428&height=321",
        "pubdate": "Fri, 17 Jan 2025 05:10:39 +0000",
        "source_url": "https://www.foreverblueshirts.com/new-york-rangers-news/stirring-5-3-comeback-win-utah-close-road-trip/",
        "summary": "The New York Rangers achieved a thrilling 5-3 comeback victory against the Utah Hockey Club, showcasing their resilience after a prior overtime loss. The Rangers scored three unanswered goals in the third period, with key contributions from Reilly Smith, Chris Kreider, and Artemi Panarin, who sealed the win with an empty-net goal. This victory marked their first win of the season when trailing after two periods and capped off a successful road trip, improving their record to 21-20-3.\n\nIgor Shesterkin's strong performance in goal, along with Arthur Kaliyev's first goal for the team, helped the Rangers overcome an early deficit. The game featured multiple lead changes, highlighting the competitive nature of both teams. As the Rangers prepare for their next game against the Columbus Blue Jackets, they aim to close the gap in the playoff race, with the Blue Jackets currently holding a five-point lead in the Eastern Conference standings.",
        "title": "Rangers score 3 times in 3rd period for stirring 5-3 comeback win against Utah to close road trip"
    }
]

Using ToolCall

Python
model_generated_tool_call = {
    "args": {"query": "top 3 news articles"},
    "id": "1",
    "name": "dappier",
    "type": "tool_call",
}
tool_msg = tool.invoke(model_generated_tool_call)
print(tool_msg.content[:400])
[{"author": "Matt Johnson", "image_url": "https://images.dappier.com/dm_01j0pb465keqmatq9k83dthx34/MLB-New-York-Mets-at-Colorado-Rockies-23948644_.jpg?width=428&height=321", "pubdate": "Fri, 17 Jan 2025 13:31:02 +0000", "source_url": "https://sportsnaut.com/new-york-mets-rumors-vladimir-guerrero-jr-news/", "summary": "The New York Mets are refocusing their strategy after failing to extend a contra

Parameters

data_model_id (str) Optional:

  • The data model ID to use for recommendations.
  • Data model IDs always start with the prefix "dm_".
  • Defaults to "dm_01j0pb465keqmatq9k83dthx34".

similarity_top_k (int) Optional:

  • The number of top documents to retrieve based on similarity.
  • Defaults to 9.

ref (str) Optional:

  • The site domain where AI recommendations should be displayed.
  • Defaults to None.

num_articles_ref (int) Optional:

  • The minimum number of articles to return from the specified reference domain (ref).
  • The remaining articles will come from other sites in the RAG model.
  • Defaults to 0.

search_algorithm (str) Optional:

  • The search algorithm to use for retrieving articles.
  • Options:
    • "most_recent" (default),
    • "semantic",
    • "most_recent_semantic",
    • "trending".

Dappier Retriever

You can also check this cookbook in colab here

Overview

The Dappier AI Recommendations Retriever is a custom retriever built using LangChain’s retriever interface. It enhances AI applications by providing real-time, AI-driven recommendations from premium content sources across industries like News, Finance, and Sports. By leveraging Dappier’s pre-trained RAG models and natural language APIs, this retriever ensures that responses are not only accurate but also contextually relevant. It takes a user query as input and returns a list of LangChain Document objects with high-quality recommendations, making it a powerful tool for AI applications requiring up-to-date, content-aware insights.

Watch the Video

If you prefer a visual walkthrough, check out the accompanying video below:

Usage

Python
from langchain_dappier import DappierRetriever

retriever = DappierRetriever(data_model_id="dm_01jagy9nqaeer9hxx8z1sk1jx6")

query = "latest news"

retriever.invoke(query)
[Document(metadata={'title': 'Man shot and killed on Wells Street near downtown Fort Wayne', 'author': 'Gregg Montgomery', 'source_url': 'https://www.wishtv.com/news/indiana-news/man-shot-dies-fort-wayne-december-25-2024/', 'image_url': 'https://images.dappier.com/dm_01jagy9nqaeer9hxx8z1sk1jx6/fort-wayne-police-department-vehicle-via-Flickr_.jpg?width=428&height=321', 'pubdata': 'Thu, 26 Dec 2024 01:00:33 +0000'}, page_content='A man was shot and killed on December 25, 2024, in Fort Wayne, Indiana, near West Fourth and Wells streets. Police arrived shortly after 6:30 p.m. following reports of gunfire and found the victim in the 1600 block of Wells Street, where he was pronounced dead. The area features a mix of businesses, including a daycare and restaurants.\n\nAs of the latest updates, police have not provided details on the safety of the area, potential suspects, or the motive for the shooting. Authorities are encouraging anyone with information to reach out to the Fort Wayne Police Department or Crime Stoppers.'),
Document(metadata={'title': 'House cat dies from bird flu in pet food, prompting recall', 'author': 'Associated Press', 'source_url': 'https://www.wishtv.com/news/business/house-cat-bird-flu-pet-food-recall/', 'image_url': 'https://images.dappier.com/dm_01jagy9nqaeer9hxx8z1sk1jx6/BACKGROUND-Northwest-Naturals-cat-food_.jpg?width=428&height=321', 'pubdata': 'Wed, 25 Dec 2024 23:12:41 +0000'}, page_content='An Oregon house cat has died after eating pet food contaminated with the H5N1 bird flu virus, prompting a nationwide recall of Northwest Naturals\' 2-pound Feline Turkey Recipe raw frozen pet food. The Oregon Department of Agriculture confirmed that the strictly indoor cat contracted the virus solely from the food, which has "best if used by" dates of May 21, 2026, and June 23, 2026. \n\nThe affected product was distributed across several states, including Arizona, California, and Florida, as well as British Columbia, Canada. Consumers are urged to dispose of the recalled food and seek refunds. This incident raises concerns about the spread of bird flu and its potential impact on domestic animals, particularly as California has declared a state of emergency due to the outbreak affecting various bird species.'),
Document(metadata={'title': '20 big cats die from bird flu at Washington sanctuary', 'author': 'Nic F. Anderson, CNN', 'source_url': 'https://www.wishtv.com/news/national/bird-flu-outbreak-wild-felid-center-2024/', 'image_url': 'https://images.dappier.com/dm_01jagy9nqaeer9hxx8z1sk1jx6/BACKGROUND-Amur-Bengal-tiger-at-Wild-Felid-Advocacy-Center-of-Washington-FB-post_.jpg?width=428&height=321', 'pubdata': 'Wed, 25 Dec 2024 23:04:34 +0000'}, page_content='The Wild Felid Advocacy Center in Washington state has experienced a devastating bird flu outbreak, resulting in the deaths of 20 big cats, over half of its population. The first death was reported around Thanksgiving, affecting various species, including cougars and a tiger mix. The sanctuary is currently under quarantine, closed to the public, and working with animal health officials to disinfect enclosures and implement prevention strategies.\n\nAs the situation unfolds, the Washington Department of Fish and Wildlife has noted an increase in bird flu cases statewide, including infections in cougars. While human infections from bird flu through contact with mammals are rare, the CDC acknowledges the potential risk. The sanctuary hopes to reopen in the new year, focusing on the recovery of the remaining animals and taking measures to prevent further outbreaks, marking an unprecedented challenge in its 20-year history.')]

Use within a chain

Like other retrievers, DappierRetriever can be incorporated into LLM applications via chains. We will need a LLM or chat model. Let’s use OpenAI as an example.
pip install -U langchain_core langchain-openai
export OPENAI_API_KEY="your-api-key"
Python
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o", temperature=0)

prompt = ChatPromptTemplate.from_template(
    """Answer the question based only on the context provided.

Context: {context}

Question: {question}"""
)


def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)


chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

chain.invoke(
    "What are the key highlights and outcomes from the latest events covered in the article?"
)
"The key highlights and outcomes from the latest events covered in the article include:\n\n1. An Israeli airstrike in Gaza killed five journalists from Al-Quds Today Television, leading to condemnation from their outlet and raising concerns about violence against media professionals in the region.\n2. The Committee to Protect Journalists reported that since October 7, 2023, at least 141 journalists have been killed in the region, marking the deadliest period for journalists since 1992, with the majority being Palestinians in Gaza.\n3. A man was shot and killed in Fort Wayne, Indiana, with police not providing details on suspects, motive, or the safety of the area.\n4. An Oregon house cat died after eating pet food contaminated with the H5N1 bird flu virus, leading to a nationwide recall of Northwest Naturals' Feline Turkey Recipe raw frozen pet food and raising concerns about the spread of bird flu among domestic animals."

Parameters

data_model_id (str) Optional:

  • The data model ID to use for recommendations.
  • Data model IDs always start with the prefix "dm_".
  • Defaults to "dm_01j0pb465keqmatq9k83dthx34".

similarity_top_k (int) Optional:

  • The number of top documents to retrieve based on similarity.
  • Defaults to 9.

ref (str) Optional:

  • The site domain where AI recommendations should be displayed.
  • Defaults to None.

num_articles_ref (int) Optional:

  • The minimum number of articles to return from the specified reference domain (ref).
  • The remaining articles will come from other sites in the RAG model.
  • Defaults to 0.

search_algorithm (str) Optional:

  • The search algorithm to use for retrieving articles.
  • Options:
    • "most_recent" (default),
    • "semantic",
    • "most_recent_semantic",
    • "trending".

Conclusion

Dappier’s tools and retrievers empower AI models with real-time search and AI-driven content recommendations, ensuring seamless and up-to-date knowledge retrieval. For further exploration, visit our marketplace.