Skip to main content

隐喻搜索 (Metaphor Search)

隐喻搜索是一个完全为LLMs设计的搜索引擎。您可以搜索并获取任何页面的内容。

本笔记本介绍了如何使用隐喻搜索。

首先,您需要设置正确的API密钥和环境变量。在这里获取每月1000次免费搜索。

然后将您的API密钥输入为环境变量。

import os

os.environ["METAPHOR_API_KEY"] = "..."

使用他们的SDK (Using their SDK)

这是使用Metaphor API的较新且更受支持的方式 - 通过他们的SDK

# !pip install metaphor-python
from metaphor_python import Metaphor

client = Metaphor(api_key=os.environ["METAPHOR_API_KEY"])
from langchain.agents import tool
from typing import List
@tool
def search(query: str):
"""使用查询调用搜索引擎。"""
return client.search(query, use_autoprompt=True, num_results=5)

@tool
def get_contents(ids: List[str]):
"""获取网页的内容。

传入的ids应该是从`search`中获取的id列表。
"""
return client.get_contents(ids)

@tool
def find_similar(url: str):
"""获取与给定URL相似的搜索结果。

传入的url应该是从`search`返回的URL。
"""
return client.find_similar(url, num_results=5)
tools = [search, get_contents, find_similar]

在代理中使用

from langchain.chat_models import ChatOpenAI
llm = ChatOpenAI(temperature=0)
from langchain.agents import OpenAIFunctionsAgent
from langchain.schema import SystemMessage
system_message = SystemMessage(content="You are a web researcher who uses search engines to look up information.")
prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message)
agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt)
from langchain.agents import AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.run("Find the hottest AI agent startups and what they do")
    

> 进入新的AgentExecutor链...

调用: `search` with `{'query': 'hottest AI agent startups'}`


SearchResponse(results=[Result(title='A Search Engine for Machine Intelligence', url='https://bellow.ai/', id='bdYc6hvHww_JvLv9k8NhPA', score=0.19460266828536987, published_date='2023-01-01', author=None, extract=None), Result(title='Adept: Useful General Intelligence', url='https://www.adept.ai/', id='aNBppxBZvQRZMov6sFVj9g', score=0.19103890657424927, published_date='2000-01-01', author=None, extract=None), Result(title='HiOperator | Generative AI-Enhanced Customer Service', url='https://www.hioperator.com/', id='jieb6sB53mId3EDo0z-SDw', score=0.18549954891204834, published_date='2000-01-01', author=None, extract=None), Result(title='Home - Stylo', url='https://www.askstylo.com/', id='kUiCuCjJYMD4N0NXdCtqlQ', score=0.1837376356124878, published_date='2000-01-01', author=None, extract=None), Result(title='DirectAI', url='https://directai.io/?utm_source=twitter&utm_medium=raw_message&utm_campaign=first_launch', id='45iSS8KnJ9tL1ilPg3dL9A', score=0.1835256814956665, published_date='2023-01-01', author=None, extract=None), Result(title='Sidekick AI | Customer Service Automated', url='https://www.sidekickai.co/', id='nCoPMUtqWQqhUvsdTjJT6A', score=0.18215584754943848, published_date='2020-01-01', author=None, extract=None), Result(title='Hebbia - Search, Reinvented', url='https://www.hebbia.ai/', id='Zy0YaekZdd4rurPQKkys7A', score=0.1799020767211914, published_date='2023-01-01', author=None, extract=None), Result(title='AI.XYZ', url='https://www.ai.xyz/', id='A5c1ePEvsaQeml2Kui_-vA', score=0.1797989457845688, published_date='2023-01-01', author=None, extract=None), Result(title='Halist AI', url='https://halist.ai/', id='-lKPLSb4N4dgMZlTgoDvJg', score=0.17975398898124695, published_date='2023-03-01', author=None, extract=None), Result(title='Clone your best expert', url='https://airin.ai/', id='_XIjx1YLPfI4cKePIEc_bQ', score=0.17957791686058044, published_date='2016-02-12', author=None, extract=None)], api=<metaphor_python.api.Metaphor object at 0x104192140>)
调用: `get_contents` with `{'ids': ['bdYc6hvHww_JvLv9k8NhPA', 'aNBppxBZvQRZMov6sFVj9g', 'jieb6sB53mId3EDo0z-SDw', 'kUiCuCjJYMD4N0NXdCtqlQ', '45iSS8KnJ9tL1ilPg3dL9A', 'nCoPMUtqWQqhUvsdTjJT6A', 'Zy0YaekZdd4rurPQKkys7A', 'A5c1ePEvsaQeml2Kui_-vA', '-lKPLSb4N4dgMZlTgoDvJg', '_XIjx1YLPfI4cKePIEc_bQ']}`


GetContentsResponse(contents=[DocumentContent(id='bdYc6hvHww_JvLv9k8NhPA', url='https://bellow.ai/', title='A Search Engine for Machine Intelligence', extract="<div><div><h2>More Opinions</h2><p>Get responses from multiple AIs</p><p>Don't rely on a single source of truth, explore the full space of machine intelligence and get highly tailored results.</p></div></div>"), DocumentContent(id='aNBppxBZvQRZMov6sFVj9g', url='https://www.adept.ai/', title='Adept: Useful General Intelligence', extract='<div><div><p>Useful <br />General <br />Intelligence</p></div>'), DocumentContent(id='jieb6sB53mId3EDo0z-SDw', url='https://www.hioperator.com/', title='HiOperator | Generative AI-Enhanced Customer Service', extract="<div><div><div><div><div><h2>Generative AI-Enhanced Customer Support Automation</h2><p>Flexible, Scalable Customer Support</p></div><div><p></p></div></div><p></p></div><div><div><p>Why HiOperator?</p><h2>Truly scalable customer service</h2><p>A digital-first customer service provider that changes all the rules of what's possible. Scalable. 100% US-Based. Effortless. HiOperator is the digital payoff.</p></div><p></p></div><div><div><p>Next-Gen Customer Service</p><h2>Scaling with HiOperator's Superagents</h2><p>HiOperator is only possible in the digital era. Our revolutionary software connects with your systems to empower our agents to learn quickly and deliver incredible accuracy. </p></div><div><div><p></p><div><h3>Train Us Once</h3><p>We handle all of the recruiting, hiring, and training moving forward. Never have to deal with another classroom retraining or head count headaches.</p></div></div><div><div><h3>Send Us Tickets</h3><p>We pull tickets automatically from your preferred CRM vendor into our custom system. You have full control over <strong>how</strong> and <strong>when</strong> we get tickets.</p></div><p></p></div><div><p></p><div><h3>Pay per resolution</h3><p>We charge for each conversation we solve. No onboarding fees. No hourly rates. Pay for what you use.</p></div></div></div></div><div><p>Customer Experience</p><h2>Insights &amp;Â\xa0News</h2></div><div><div><h2>Let's transform your customer service.</h2><p>We can onboard in a matter of days and we offer highly flexible contracts. Whether you need a large team to handle your support or some overflow assistance, getting started is easy.</p></div><p>We can onboard in a matter of days and we offer highly flexible contracts. Whether you need a large team to handle your support or some overflow assistance, getting started is easy.</p></div></div>"), DocumentContent(id='kUiCuCjJYMD4N0NXdCtqlQ', url='https://www.askstylo.com/', title='Home - Stylo', extract='<div><div><header><div><p></p><h2>Stop angry customers from breaking support</h2><p></p></div></header><div><p></p><h2><em> </em><strong><em>â\x80\x9cWe solve 99 tickets perfectly </em>ð\x9f\x98\x87<em> but the 1 we miss lands in the CEOâ\x80\x99s inbox </em>ð\x9f\x98«<em>â\x80\x9d<br /></em></strong></h2><p></p><div><p><strong>â\x80\x8d</strong>That 1 costly ticket breaks your process, metrics, and the will of your team. Angry customers make support teams less effective, which makes customers angrier in return.<strong><br />â\x80\x8d</strong><br />Stylo is AI that tells you where to most effectively spend your time to improve the customer experience. This leads to happier customers, employees, and reduces churn.</p><p>â\x80\x8d<strong>No setup, no learning curve, just plug it in and go.</strong></p></div></div><div><div><p></p><div><p>â\x80\x9cIâ\x80\x99m able to better manage the team because I can pinpoint gaps in the teamâ\x80\x99s knowledge or training, and find room for process improvements.â\x80\x9d</p><p></p></div></div></div></div>'), DocumentContent(id='45iSS8KnJ9tL1ilPg3dL9A', url='https://directai.io/?utm_source=twitter&utm_medium=raw_message&utm_campaign=first_launch', title='DirectAI', extract="<div><div><div><h2>Vision models without training data.<br /></h2><p>Build and deploy powerful computer vision models with plain language.<br />No code or training required.</p></div><div><h2>Fundamentally different.</h2><p>We use large language models and zero-shot learning to instantly build models that fit your description.</p><br /></div><div><div><p></p><h2>We're removing the last major barrier to creating custom models - <br />training data.</h2><p></p></div><div><table><colgroup></colgroup><thead><tr><th><p>Deploy and iterate in seconds with DirectAI</p></th></tr></thead><tbody><tr><td>• Don't spend time assembling training data.</td></tr><tr><td>• Don't pay a third party to label your data.</td></tr><tr><td>• Don't pay to train your model.</td></tr><tr><td>• Don't spend months finetuning your model's behavior.</td></tr></tbody></table></div></div><div><h2>Venture-backed.<p>Based in NYC.</p><p>We're changing how people use AI in the real world.</p><p>Come talk to us on .</p></h2></div></div></div>"), DocumentContent(id='nCoPMUtqWQqhUvsdTjJT6A', url='https://www.sidekickai.co/', title='Sidekick AI | Customer Service Automated', extract='<div><div><div><div><div><div><div><p>Hi, I am an AI named Jenny, working at Pizza Planet. How can I help you today?</p></div><div><p>How much are large pizzas with 1 topping?</p></div><div><p>For most toppings, a large with one topping would be $10.99.</p></div><div><p>Ok, can I order a large with pepperoni</p></div><div><p>Sure! Takeout or delivery?</p></div><div><p>Alright, order placed. See you at 5 pm!</p></div></div><div><p></p></div></div><p></p></div><div><p>Meet Sidekick</p><div><p>\n Sidekick is an AI agent built to hold natural and dynamic conversations with your customers and talk just like a human.</p><p>Built on the world\'s most advanced AI models, Sidekick pushes the state of the art in natural conversation and converses seamlessly with your customers.\n </p></div><p>Try it out ➜</p><p>Try it out ↓</p></div><div><p>An AI agent designed for <strong>service-led growth.</strong></p><div><div><p></p><p>Personal</p><p>Every customer is different, and has unique needs. Our agents are built to provide personalized service depending on the customer\'s needs.</p></div><div><p></p><p>Fast</p><p>Unlike humans, our Sidekicks respond near-instantly, any time of the day. Your customers won\'t wait for service ever again.</p></div><div><p></p><p>Effective</p><p>Customers love great service, and Sidekick delivers. Grow revenue by solving issues in minutes instead of hours, and providing personalized support to each customer.</p></div></div></div><div><p>Integrating with <strong>your tools.</strong></p></div><div><p><strong>Wherever </strong>your customers are.</p><p>\n Sidekick takes an omnichannel approach to customer service, aggregating all customer interactions across all platforms in one area. Currently most social media platforms are supported, along with website embeddings and API integration.\n </p><div><div><div><p>On the web.</p><div><p>Sidekick makes adding a live chat to your website as simple as copy and pasting a single line of code.</p><p>Chat bubbles discretely sit in the bottom right corner and provide a smooth conversation experience, with AI and human agents alike.</p></div></div><p></p><p></p></div><div><div><p>On Facebook.</p><div><p>Sidekick integrates with your Facebook pages to make live customer service one click away.</p><p>Customers can reach your agent and get service without ever leaving Messenger.</p></div></div><p></p><p></p></div><div><div><p>On Instagram.</p><div><p>E-Commerce on Instagram is especially demanding for customer service.</p><p>Sidekick integrates easily with Instagram accounts to put a live agent one click away.</p></div></div><p></p><p></p></div><div><div><p>On Twitter.</p><div><p>Customers are spending more time on Twitter, which means businesses should provide customer service right on the platform.</p><p>Sidekick integrates easily with Twitter accounts to put a live agent one click away.</p></div></div><p></p><p></p></div><div><div><p>Anywhere you want.</p><div><p>Our API provides programmatic access to your Sidekick agent to integrate into your own app.</p><p>We\'ve built simple abstractions over the chat interface to make it easy to work with our API.</p></div></div><div><div><p>Endpoints</p><div><p>POST</p><p>https://www.api.sidekickai.co/converse</p></div></div><div><p>Sample Request</p><div><pre>{\n "access_token": "KjZUZBWAOKwgLWAlVFyL",\n "conversation_id": "23874",\n "body": "How much is a large 2 topping?"\n}</pre></div></div><div><p>Sample Response</p><div><pre>{\n "response": "A large'), DocumentContent(id='Zy0YaekZdd4rurPQKkys7A', url='https://www.hebbia.ai/', title='Hebbia - Search, Reinvented', extract="<div><div><h2>Direct to the point <br />with cutting-edge AI.</h2><p>Stop relying on archaic software, traditional Q&amp;A emails, or waiting for deal partners. Get answers on your own time with accuracy that you can't replicate with humans. <br />â\x80\x8d<br /></p><p>HebbiaÂ\xa0retrieves <strong>every</strong> answer, even insights humans overlook. <br /></p></div>"), DocumentContent(id='A5c1ePEvsaQeml2Kui_-vA', url='https://www.ai.xyz/', title='AI.XYZ', extract='<div><div>\n \n \n<article>\n \n \n \n \n \n<div><div>\n<p><h2><strong>Go be human</strong></h2></p>\n</div><div><p>\n</p><h4>Let your AI deal with the rest</h4>\n<p></p></div><div><p>Design your own AI with AI.XYZ</p></div><div>\n \n \n \n <p></p>\n \n </div></div>\n \n \n \n \n<div><p>\n</p><h3><strong>The digital world was designed to make us more productive but now navigating it all has become its own job.</strong></h3>\n<p></p></div>\n \n \n \n \n<section>\n <div>\n \n \n \n \n \n \n \n \n <p></p>\n \n \n </div>\n <div><div><p>\n</p><h2><strong>Take life a little easier</strong></h2>\n<p></p></div><div>\n \n \n \n <p></p>\n \n </div><div><p>\n</p><h2><strong>Tackles info<br />overload</strong></h2>\n<p></p></div><div><p>\n</p><h4>“Like ChatGPT, but way more proactive and useful because it’s designed by me, for only me”</h4>\n<p></p></div><div>\n \n \n \n <p></p>\n \n </div><div><p>\n</p><h2><strong>Never sits<br />around</strong></h2>\n<p></p></div><div><p>\n</p><h4>“Even if I’m not interacting with it, my AI looks for ways to simplify my day, surprising me with useful ideas”</h4>\n<p></p></div><div>\n \n \n \n <p></p>\n \n </div><div><p>\n</p><h2><strong>Supports and<br />inspires</strong></h2>\n<p></p></div><div><p>\n</p><h4>“It takes things off my plate, but also cheers me on throughout the day — helping me navigate it all”</h4>\n<p></p></div></div>\n \n \n</section>\n \n \n \n \n<div><div><p>\n</p><h2><strong>Create your AI in 3 simple steps:</strong></h2>\n<p></p></div><div>\n<p><strong>STEP ONE</strong></p><h2><strong>Pick a face and voice</strong></h2><h4>Choose from our library of characters or add your own unique face and voice.</h4>\n</div><div>\n \n \n \n <p></p>\n \n </div><div>\n<p><strong>STEP TWO</strong></p><h2><strong>Create your AI’s persona and memory</strong></h2><h4>Decide who your AI is, its purpose and what it will help you with. Paste information that you want your AI to know.</h4>\n</div><div>\n \n \n \n <p></p>\n \n </div><div>\n<p><strong>STEP THREE</strong></p><h2><strong>Get started</strong></h2><h4>Ask your AI to help you with ideas and support throughout your day. Eventually it will be able to proactively support you.</h4>\n</div><div>\n \n \n \n <p></p>\n \n </div></div>\n \n \n \n \n<section>\n <div>\n \n \n \n \n \n \n \n \n <p></p>\n \n \n </div>\n <div><p>\n</p><h2><strong>Start training your AI to do things for you</strong></h2>\n<p></p></div>\n \n \n</section>\n \n</article>\n \n \n \n \n \n </div></div'), DocumentContent(id='-lKPLSb4N4dgMZlTgoDvJg', url='https://halist.ai/', title='Halist AI', extract='<div><div>\n<p><a href="/app/">Start for free</a></p><p>\nPowered by OpenAI GPT-3 and GPT-4.\n</p>\n<h2>ChatGPT. Lightning-fast and private. Everywhere.</h2>\n<h2>Optimized access to the AI on mobile.</h2>\n<p></p><p>\nTo install Halist on <b>iPhone</b>, open the web app in Safari and tap the "Share" icon. Then, tap "Add to Home Screen" and follow the prompts.\nTo install on <b>Android</b>, open the website in Chrome and tap the three dots in the top right corner. Then, tap "Add to Home screen" and follow the prompts.\n</p>\n</div></div>'), DocumentContent(id='_XIjx1YLPfI4cKePIEc_bQ', url='https://airin.ai/', title='Clone your best expert', extract='<div><section><section><div><p> Airin clones how your top expert solves problems in as little as 2 hours. Airin creates an AI companion for the rest of your team by focusing on the patterns in your expert’s questions and hypotheses, not their answers. <a href="/how-it-works">Learn how it works </a></p></div></section><section><div><p> Your customers, agents, sales teams, and consultants can independently solve a wider-range of complex problems with an AI companion. This eliminates the need to maintain large teams of specialized experts. </p></div></section><section><div><p> Airin automates remote coaching for new hires and dramatically reduces time to productivity. New employees partner with your AI companion and meet productivity standards in half the time. </p></div></section></section>')])以下是一些最热门的AI代理初创公司及其所做的事情:

1. [Bellow AI](https://bellow.ai/):这家初创公司提供了一个面向机器智能的搜索引擎。它允许用户从多个AI获取响应,探索机器智能的全部领域,并获得高度定制的结果。

2. [Adept AI](https://www.adept.ai/):Adept专注于创建有用的通用智能。

3. [HiOperator](https://www.hioperator.com/):HiOperator提供生成式AI增强的客户支持自动化。它提供可扩展的、面向数字的客户服务,并使用其软件使代理能够快速学习并提供准确的结果。

4. [Stylo](https://www.askstylo.com/):Stylo使用AI来帮助管理客户支持,确定在哪里最有效地花时间来改善客户体验。

5. [DirectAI](https://directai.io/):DirectAI允许用户使用简单的语言构建和部署强大的计算机视觉模型,无需编码或训练。

6. [Sidekick AI](https://www.sidekickai.co/):Sidekick AI旨在与客户进行自然和动态的对话,根据客户的需求提供个性化服务。

7. [Hebbia](https://www.hebbia.ai/):Hebbia正在通过先进的AI重新定义搜索,检索每一个答案,甚至是人类忽视的洞察力。

8. [AI.XYZ](https://www.ai.xyz/):AI.XYZ允许用户设计自己的AI,解决信息过载问题,并在一天中提供支持和灵感。

9. [Halist AI](https://halist.ai/):Halist AI为ChatGPT提供了优化的移动访问,由OpenAI GPT-3和GPT-4提供支持。

10. [Airin](https://airin.ai/):Airin在短短2小时内克隆了您的顶级专家解决问题的方式,为您的团队创建了一个AI伴侣。它自动化了新员工的远程培训,并大大缩短了达到生产力标准的时间。

> 链条执行完毕。

使用工具包装器 (Using the tool wrapper)

这是使用Metaphor的旧方法 - 通过我们自己的内部集成。

from langchain.utilities import MetaphorSearchAPIWrapper
search = MetaphorSearchAPIWrapper()

调用API

results接受一个经过Metaphor优化的搜索查询和结果数量(最多500个)。它返回一个包含标题、URL、作者和创建日期的结果列表。

search.results("关于AI安全性的最佳博客文章绝对是这个:", 10)
    [{'title': 'AI安全性的核心观点:何时、为什么、什么以及如何',
'url': 'https://www.anthropic.com/index/core-views-on-ai-safety',
'author': None,
'published_date': '2023-03-08'},
{'title': '人工智能的灭绝风险',
'url': 'https://aisafety.wordpress.com/',
'author': None,
'published_date': '2013-10-08'},
{'title': 'AI安全性的简单图景 - LessWrong',
'url': 'https://www.lesswrong.com/posts/WhNxG4r774bK32GcH/the-simple-picture-on-ai-safety',
'author': 'Alex Flint',
'published_date': '2018-05-27'},
{'title': 'AI安全性工作的最佳时机',
'url': 'https://slatestarcodex.com/2015/05/29/no-time-like-the-present-for-ai-safety-work/',
'author': None,
'published_date': '2015-05-29'},
{'title': '关于AI安全性的解决方案呼吁 - LessWrong',
'url': 'https://www.lesswrong.com/posts/ASMX9ss3J5G3GZdok/a-plea-for-solutionism-on-ai-safety',
'author': 'Jasoncrawford',
'published_date': '2023-06-09'},
{'title': '人工智能革命:第一部分 - Wait But Why',
'url': 'https://waitbutwhy.com/2015/01/artificial-intelligence-revolution-1.html',
'author': 'Tim Urban',
'published_date': '2015-01-22'},
{'title': 'Anthropic: AI安全性的核心观点:何时、为什么、什么以及如何 - EA Forum',
'url': 'https://forum.effectivealtruism.org/posts/uGDCaPFaPkuxAowmH/anthropic-core-views-on-ai-safety-when-why-what-and-how',
'author': 'Jonmenaster',
'published_date': '2023-03-09'},
{'title': '[链接文章] Sam Altman的2015年博客文章:机器智能第1部分和第2部分 - LessWrong',
'url': 'https://www.lesswrong.com/posts/QnBZkNJNbJK9k5Xi7/linkpost-sam-altman-s-2015-blog-posts-machine-intelligence',
'author': 'Olivia Jimenez',
'published_date': '2023-04-28'},
{'title': '毁灭的证明 - LessWrong',
'url': 'https://www.lesswrong.com/posts/xBrpph9knzWdtMWeQ/the-proof-of-doom',
'author': 'Johnlawrenceaspden',
'published_date': '2022-03-09'},
{'title': 'Anthropic的AI安全性核心观点 - LessWrong',
'url': 'https://www.lesswrong.com/posts/xhKr5KtvdJRssMeJ3/anthropic-s-core-views-on-ai-safety',
'author': 'Zac Hatfield-Dodds',
'published_date': '2023-03-09'}]

添加过滤器 (Adding filters)

我们还可以为搜索添加过滤器。

include_domains: Optional[List[str]] - 包含在搜索中的域名列表。如果指定了此参数,结果将只来自这些域名。include_domains 和 exclude_domains 只能指定其中之一。

exclude_domains: Optional[List[str]] - 排除在搜索中的域名列表。如果指定了此参数,结果将只来自这些域名。include_domains 和 exclude_domains 只能指定其中之一。

start_crawl_date: Optional[str] - "Crawl date" 指的是 Metaphor 发现链接的日期,比发布日期更精确,更有用。如果指定了 start_crawl_date,结果将只包括在 start_crawl_date 之后爬取的链接。必须使用 ISO 8601 格式 (YYYY-MM-DDTHH:MM:SSZ) 指定。

end_crawl_date: Optional[str] - "Crawl date" 指的是 Metaphor 发现链接的日期,比发布日期更精确,更有用。如果指定了 end_crawl_date,结果将只包括在 end_crawl_date 之前爬取的链接。必须使用 ISO 8601 格式 (YYYY-MM-DDTHH:MM:SSZ) 指定。

start_published_date: Optional[str] - 如果指定了此参数,只返回发布日期在 start_published_date 之后的链接。必须使用 ISO 8601 格式 (YYYY-MM-DDTHH:MM:SSZ) 指定。请注意,对于某些链接,我们没有发布日期,如果指定了 start_published_date,这些链接将被排除在结果之外。

end_published_date: Optional[str] - 如果指定了此参数,只返回发布日期在 end_published_date 之前的链接。必须使用 ISO 8601 格式 (YYYY-MM-DDTHH:MM:SSZ) 指定。请注意,对于某些链接,我们没有发布日期,如果指定了 end_published_date,这些链接将被排除在结果之外。

查看完整文档 here

search.results(
"关于 AI 安全性的最佳博客文章绝对是这篇:",
10,
include_domains=["lesswrong.com"],
start_published_date="2019-01-01",
)

使用隐喻作为工具 (Use Metaphor as a tool)

隐喻可以作为一个工具,用于获取其他工具(如浏览工具)无法获取的URL。

from langchain.agents.agent_toolkits import PlayWrightBrowserToolkit
from langchain.tools.playwright.utils import (
create_async_playwright_browser, # A synchronous browser is available, though it isn't compatible with jupyter.
)

async_browser = create_async_playwright_browser()
toolkit = PlayWrightBrowserToolkit.from_browser(async_browser=async_browser)
tools = toolkit.get_tools()

tools_by_name = {tool.name: tool for tool in tools}
print(tools_by_name.keys())
navigate_tool = tools_by_name["navigate_browser"]
extract_text = tools_by_name["extract_text"]
from langchain.agents import initialize_agent, AgentType
from langchain.chat_models import ChatOpenAI
from langchain.tools import MetaphorSearchResults

llm = ChatOpenAI(model_name="gpt-4", temperature=0.7)

metaphor_tool = MetaphorSearchResults(api_wrapper=search)

agent_chain = initialize_agent(
[metaphor_tool, extract_text, navigate_tool],
llm,
agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
)

agent_chain.run(
"find me an interesting tweet about AI safety using Metaphor, then tell me the first sentence in the post. Do not finish until able to retrieve the first sentence."
)