Dappier
Dappier 將任何 LLM 或您的 Agentic AI 連接到來自可信任來源的即時、權利已清除的專有資料,使您的 AI 成為任何領域的專家。我們的專業模型包括即時網路搜尋、新聞、體育、金融股市資料、加密貨幣資料以及來自優質發行商的獨家內容。在我們的市場中探索各種資料模型:marketplace.dappier.com。
Dappier 提供豐富、即時可用且與上下文相關的資料字串,並針對與 LangChain 的無縫整合進行了最佳化。無論您是建構對話式 AI、推薦引擎還是智慧搜尋,Dappier 與 LLM 無關的 RAG 模型都可確保您的 AI 能夠存取經過驗證的最新資料,而無需建構和管理您自己的檢索管線的複雜性。
Dappier 工具
這將幫助您開始使用 Dappier 工具。如需所有 DappierRetriever 功能和配置的詳細文件,請前往 API 參考文件。
總覽
DappierRealTimeSearchTool 和 DappierAIRecommendationTool 使 AI 應用程式能夠利用即時資料和 AI 驅動的洞察力。前者提供對新聞、天氣、旅遊和金融市場最新資訊的存取,而後者透過來自新聞、金融和體育等不同領域的事實性優質內容來增強應用程式的功能,所有這些都由 Dappier 的預先訓練 RAG 模型和自然語言 API 提供支援。
設定
此工具位於 langchain-dappier
套件中。
%pip install -qU langchain-dappier
憑證
我們還需要設定我們的 Dappier API 憑證,這可以在 Dappier 網站上產生。
import getpass
import os
if not os.environ.get("DAPPIER_API_KEY"):
os.environ["DAPPIER_API_KEY"] = getpass.getpass("Dappier API key:\n")
如果您想從個別查詢取得自動追蹤,您也可以透過取消註解下方內容來設定您的 LangSmith API 金鑰
# os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
# os.environ["LANGSMITH_TRACING"] = "true"
DappierRealTimeSearchTool
存取即時 Google 搜尋結果,包括最新新聞、天氣、旅遊和優惠,以及來自 polygon.io 的最新金融新聞、股價和交易,所有這些都由 AI 洞察力提供支援,讓您隨時掌握資訊。
實例化
-
ai_model_id: str 要用於查詢的 AI 模型 ID。AI 模型 ID 始終以字首「am_」開頭。
預設為「am_01j06ytn18ejftedz6dyhz2b15」。
有多個 AI 模型 ID 可用,可在以下網址找到:https://marketplace.dappier.com/marketplace
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
# args_schema=..., # overwrite default args_schema: BaseModel
)
調用
使用 args 直接調用
DappierRealTimeSearchTool
採用單一「query」引數,該引數應為自然語言查詢
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! 🎉🏆🎾"
使用 ToolCall 調用
我們也可以使用模型產生的 ToolCall 來調用此工具,在這種情況下將傳回 ToolMessage
# This is usually generated by a model, but we'll create a tool call directly for demo purposes.
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)
# The content is a JSON string of results
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! ⚽️🏆
鏈結
我們可以透過先將我們的工具繫結到工具調用模型,然後調用它,在鏈中使用我們的工具
pip install -qU "langchain[openai]"
import getpass
import os
if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")
from langchain.chat_models import init_chat_model
llm = init_chat_model("gpt-4o-mini", model_provider="openai")
import datetime
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}."),
("human", "{user_input}"),
("placeholder", "{messages}"),
]
)
# specifying tool_choice will force the model to call this tool.
llm_with_tools = llm.bind_tools([tool])
llm_chain = prompt | llm_with_tools
@chain
def tool_chain(user_input: str, config: RunnableConfig):
input_ = {"user_input": user_input}
ai_msg = llm_chain.invoke(input_, config=config)
tool_msgs = tool.batch(ai_msg.tool_calls, config=config)
return llm_chain.invoke({**input_, "messages": [ai_msg, *tool_msgs]}, config=config)
tool_chain.invoke("who won the last womens 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}})
DappierAIRecommendationTool
使用 Dappier 的預先訓練 RAG 模型和自然語言 API,增強您的 AI 應用程式功能,從新聞、金融、體育、天氣等垂直領域的優質內容提供者提供事實性且最新的回應。
實例化
-
data_model_id: str
用於建議的資料模型 ID。資料模型 ID 始終以字首「dm_」開頭。預設為「dm_01j0pb465keqmatq9k83dthx34」。
有多個資料模型 ID 可用,可在 Dappier 市場找到。 -
similarity_top_k: int
要根據相似性檢索的頂部文件數量。預設為「9」。 -
ref: Optional[str] 應顯示 AI 建議的網站網域。預設為「None」。
-
num_articles_ref: int 從指定的參考網域 ("ref") 傳回的最小文章數量。剩餘的文章將來自 RAG 模型中的其他網站。預設為「0」。
-
search_algorithm: Literal["most_recent", "semantic", "most_recent_semantic", "trending"] 用於檢索文章的搜尋演算法。預設為「most_recent」。
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",
# name="...", # overwrite default tool name
# description="...", # overwrite default tool description
# args_schema=..., # overwrite default args_schema: BaseModel
)
調用
使用 args 直接調用
DappierAIRecommendationTool
採用單一「query」引數,該引數應為自然語言查詢
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'}]
使用 ToolCall 調用
我們也可以使用模型產生的 ToolCall 來調用此工具,在這種情況下將傳回 ToolMessage
# This is usually generated by a model, but we'll create a tool call directly for demo purposes.
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)
# The content is a JSON string of results
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
API 參考文件
如需所有 DappierRealTimeSearchTool 功能和配置的詳細文件,請前往 API 參考文件