
创建ai代理的终极指南:使用huggingface的smolagents实现创新与实践示例
- Rifx.Online
- Large Language Models , AI Applications , AI Research
- 08 Mar, 2025
smolagents
读者们好 👋 希望大家一切都好 😊
上图是由 smolagents 框架生成的,看起来很可爱吧。在本文的最后,你也会了解到如何使用 hugging face 的 smolagents 来创建图像
Agent 生态系统
什么是 Agent?
Agent 是一个利用 AI 模型与其环境交互以实现用户定义目标的系统。它结合了推理、规划和执行操作(通常通过外部工具)来完成任务。
可以将 Agent 视为有两个主要部分:
1.大脑(AI 模型)
这里发生所有的思考。AI 模型处理推理和规划。它根据情况决定采取哪些 Action。
2.身体(能力和工具)
这部分代表了 Agent 能够做的一切。
可能的操作范围取决于 Agent 所配备的功能。例如,由于人类没有翅膀,他们无法执行“飞” Action,但他们可以执行“走”、“跑”、“跳”、“抓”等 Action。
我们使用什么类型的 AI 模型用于 Agents?
在 Agents 中最常见的 AI 模型是 LLM(大型语言模型),它接受文本作为输入,并输出文本。
众所周知的例子有 OpenAI 的 GPT4、Meta 的 LLama、Google 的 Gemini 等。这些模型已经在大量的文本上进行了训练,并且能够很好地泛化。我们将在下一节中了解更多关于 LLM 的信息。
也可以使用接受其他输入作为 Agent 核心模型的模型。例如,视觉语言模型 (VLM),它类似于 LLM,但也理解图像作为输入。我们现在将重点关注 LLM,稍后将讨论其他选项。
AI 如何对其环境采取行动?
LLM 是很棒的模型,但它们只能生成文本。
但是,如果你让像 HuggingChat 或 ChatGPT 这样的知名聊天应用程序生成图像,它们可以!这是怎么可能的?
答案是 HuggingChat、ChatGPT 和类似应用程序的开发人员实现了附加功能(称为工具),LLM 可以使用这些工具来创建图像。
Credits: HuggingFace
Agent 可以执行什么类型的任务?
Agent 可以执行我们通过 Tools 实现以完成 Actions 的任何任务。
例如,如果我编写一个 Agent 来充当我在计算机上的个人助理(如 Siri),并且我要求它“向我的经理发送电子邮件,要求推迟今天的会议”,我可以给它一些代码来发送电子邮件。这将是 Agent 需要发送电子邮件时可以使用的新 Tool。我们可以用 Python 编写它:
def send_message_to(recipient, message):
"""Useful to send an e-mail message to a recipient"""
...
send_message_to("Manager", "Can we postpone today's meeting?")
LLM,正如我们将看到的,将生成代码来运行该工具,并在需要时运行,从而完成所需的任务。
Tools 的设计非常重要,并且对你的 Agent 的质量有很大影响。某些任务需要制作非常特定的 Tools,而其他任务可以使用通用工具(如“web_search”)来解决。
请注意,Actions 与 Tools 不同。例如,一个 Action 可以涉及使用多个 Tools 来完成。
允许 Agent 与其环境交互,使公司和个人能够实际使用。
示例 1:个人虚拟助手
像 Siri、Alexa 或 Google Assistant 这样的虚拟助手在代表用户使用其数字环境进行交互时充当 Agent。
它们获取用户查询、分析上下文、从数据库中检索信息,并提供响应或启动操作(如设置提醒、发送消息或控制智能设备)。
示例 2:客户服务聊天机器人
许多公司部署聊天机器人作为 Agent,它们以自然语言与客户交互。
这些 Agent 可以回答问题、指导用户完成故障排除步骤、在内部数据库中打开问题,甚至完成交易。
它们预定义的目标可能包括提高用户满意度、减少等待时间或提高销售转化率。通过直接与客户互动、从对话中学习并随着时间的推移调整其响应,它们展示了 Agent 行动中的核心原则。
示例 3: 视频游戏中的 AI 非玩家角色
由 LLM 驱动的 AI 智能体可以使非玩家角色 (NPC) 更加动态和不可预测。
它们不再遵循僵化的行为树,而是可以根据上下文做出反应,适应玩家的互动,并生成更细致的对话。 这种灵活性有助于创造出更逼真、更具吸引力的角色,这些角色会随着玩家的行动而演变。
它们是如何工作的?
智能体将首先思考,然后行动,最后观察以执行任何操作
致谢:HuggingFace
大图景:Congo 智能体
步骤 1:用户请求“给我拿杯咖啡” Congo 智能体
步骤 2:Congo 智能体思考和计划(将思考和计划选择哪些工具来完成用户请求)Congo 智能体进行推理和计划,找出他需要的步骤和工具:
- 去厨房
- 使用咖啡机
- 冲泡咖啡
- 把咖啡拿回来
步骤 3:Congo 智能体使用工具完成用户请求
什么是 LLM? 大脑(AI 模型)
正如我们已经了解了 LLM,我不想详细介绍,但我将重点介绍几件事。
LLM 是一种 AI 模型,擅长理解和生成人类语言。 它们经过大量文本数据的训练,使它们能够学习语言中的模式、结构,甚至是细微差别。 这些模型通常由数百万个参数组成。
如今,大多数 LLM 都建立在 Transformer 架构之上——一种基于“注意力”算法的深度学习架构,自 2018 年谷歌发布 BERT 以来,它引起了极大的兴趣。
Transformer 有 3 种类型:
编码器 基于编码器的 Transformer 将文本(或其他数据)作为输入,并输出该文本的密集表示(或嵌入)。
示例:来自谷歌的 BERT
- 用例:文本分类、语义搜索、命名实体识别
- 典型大小:数百万个参数
解码器 基于解码器的 Transformer 侧重于一次生成一个新标记来完成一个序列。
示例:来自 Meta 的 Llama
- 用例:文本生成、聊天机器人、代码生成
- 典型大小:数十亿(以美国标准,即 ¹⁰⁹)个参数
Seq2Seq(编码器-解码器) 序列到序列 Transformer 结合了编码器和解码器。 编码器首先将输入序列处理成上下文表示,然后解码器生成输出序列。
示例:T5、BART
- 用例:翻译、摘要、释义
- 典型大小:数百万个参数
注意力机制是关键
Transformer 架构的一个关键方面是注意力机制(Attention)。当预测下一个词时,句子中的每个词的重要性并不相同;例如在句子“法国的首都是……”中,“法国”和“首都”这两个词携带了最多的含义。
来源:HuggingFace
这种识别预测下一个 token 最相关词语的过程已被证明非常有效。
虽然 LLM 的基本原理——预测下一个 token——自 GPT-2 以来一直保持不变,但在扩展神经网络和使注意力机制适用于越来越长的序列方面取得了重大进展。
如果您与 LLM 交互过,您可能熟悉术语上下文长度(context length),它指的是 LLM 可以处理的最大 token 数,以及它拥有的最大注意力跨度(attention span)。
什么是 AI 工具?主体
工具是提供给 LLM 的一个功能。此功能应实现一个明确的目标。
以下是 AI 代理中一些常用的工具:
这些仅仅是示例,实际上您可以为任何用例创建工具!
一个好的工具应该能够补充 LLM 的能力。
例如,如果您需要执行算术运算,为您的 LLM 提供计算器工具将比依赖模型的原生功能提供更好的结果。
此外,LLM 根据其训练数据预测提示的完成情况,这意味着它们的内部知识仅包括训练之前发生的事情。因此,如果您的代理需要最新数据,您必须通过某种工具提供它。
例如,如果您直接询问 LLM(没有搜索工具)今天的天气,LLM 可能会凭空捏造随机天气。
来源:Huggingface
一个工具应包含:
- 对该功能作用的文本描述。
- 一个可调用对象(Callable)(执行操作的东西)。
- 带有类型提示的参数(Arguments)。
- (可选)带有类型提示的输出。
工具是如何工作的?
正如我们所看到的,LLM 只能接收文本输入并生成文本输出。它们无法自行调用工具。当我们谈论向代理提供工具时,我们的意思是,我们教会 LLM 关于工具的存在,并要求模型生成文本,以便在需要时调用工具。例如,如果我们提供一个工具来从互联网上查询某个地点的天气,然后询问 LLM 巴黎的天气,LLM 将识别出这个问题是使用我们教给它的“天气”工具的相关机会。LLM 将生成文本(以代码的形式)来调用该工具。代理有责任解析 LLM 的输出,识别是否需要调用工具,并代表 LLM 调用该工具。然后,来自该工具的输出将被发送回 LLM,LLM 将为其用户撰写最终回复。
来自工具调用的输出是对话中的另一种消息类型。工具调用步骤通常不会显示给用户:代理检索对话,调用工具,获取输出,将它们添加为新的对话消息,然后再次将更新后的对话发送给 LLM。从用户的角度来看,就像 LLM 使用了该工具,但实际上是我们的应用程序代码(代理)完成了它。
核心组件
代理在以下连续循环中工作:思考(Thought)→ 行动(Act)和观察(Observe)。
让我们一起分解这些动作:
- 思考:代理的 LLM 部分决定下一步应该做什么。
- 行动:代理通过使用相关参数调用工具来采取行动。
- 观察:模型反思来自工具的响应。
思考-行动-观察循环
这三个组件在连续循环中协同工作。用编程的类比来说,代理使用一个 while 循环:循环一直持续到代理的目标得到实现。
从视觉上看,它看起来像这样:
来源:HuggingFace
在许多代理框架中,规则和指南直接嵌入到系统提示中,确保每个循环都遵循定义的逻辑。
在一个简化版本中,我们的系统提示可能如下所示:
来源:HuggingFace
我们在这里看到,在系统消息中,我们定义了:
- 代理的行为。
- 我们的代理可以访问的工具,正如我们在上一节中所描述的。
- 思考-行动-观察循环,我们将其嵌入到 LLM 指令中。
让我们举一个小例子来理解这个过程,然后再深入研究该过程的每个步骤。
Congo,天气代理
我们创建了 Congo,天气代理。
用户询问 Congo:“今天印度的天气怎么样?”
Congo 的工作是使用天气 API 工具回答此查询。
循环的展开方式如下:
Thought
内部推理:
收到查询后,Congo 的内部对话可能是:
“用户需要印度的当前天气信息。 我可以使用一个获取天气数据的工具。 首先,我需要调用天气 API 来获取最新的详细信息。”
此步骤显示代理将问题分解为几个步骤:首先,收集必要的数据。
Action
工具使用:
基于其推理以及 Congo 知道 get_weather
工具,Congo 准备了一个 JSON 格式的命令,该命令调用天气 API 工具。 例如,它的第一个操作可能是:
Thought: I need to check the current weather for India.
{
"action": "get_weather",
"action_input": {
"location": "India"
}
}
在这里,操作清楚地指定了要调用的工具(例如,get_weather)以及要传递的参数(“location”: “India”)。
Observation
来自环境的反馈:
在工具调用之后,Congo 收到一个观察结果。 这可能是来自 API 的原始天气数据,例如:
“印度目前的的天气:部分多云,35°C,25% 湿度。”
然后将此观察结果作为附加上下文添加到提示中。 它充当现实世界的反馈,确认操作是否成功并提供所需的详细信息。
Updated thought
反思:
有了观察结果,Congo 会更新其内部推理:
“现在我已经获得了印度的天气数据,我可以为用户编写答案了。”
Final Action
然后,Congo 生成最终响应,其格式与我们告诉它的一样:
Thought: I have the weather data now. The current weather in New York is partly cloudy with a temperature of 15°C and 60% humidity.”
Final answer : The current weather in New York is partly cloudy with a temperature of 15°C and 60% humidity.
此最终操作将答案发送回用户,从而结束循环。
What Is Hugging Face’s Smolagents?
一个非常简单的库,它为语言模型解锁了代理功能。
“代码代理,即用代码编写其操作的代理(而不是“用于编写代码的代理”)。 为了确保安全,我们支持通过 E2B 在沙盒环境中执行。”
How do Code agents work?
Building an agen
要构建一个代理,您至少需要两个元素:
tools
:代理可以访问的工具列表model
:一个将成为您的代理引擎的 LLM。
I am bored with theory ufffff 😫*..Yeah Its Coding Time* 😜😝😘*!!!!!!!!!!!!!!!!!!!!!!!!!!*
首先安装软件包。
pip install smolagents==1.2.0
Scenario1: I want to query my model amazon “sales_data” in natural languge, for simplicity i have taken few records
Used simple code agent, sql_engine as a tool
from sqlalchemy import (
Column,
Float,
Integer,
MetaData,
String,
Table,
create_engine,
insert,
inspect,
text,
)
engine = create_engine("sqlite:///:memory:")
metadata_obj = MetaData()
## create city SQL table
table_name = "sales_data"
sales_data = Table(
table_name,
metadata_obj,
Column("product_id", Integer, primary_key=True),
Column("product_name", String(16), primary_key=True),
Column("category", String(16)),
Column("discounted_price", Float),
Column("actual_price", Float),
Column("discount_percentage", Float),
Column("rating", Integer),
Column("rating_count", Integer),
Column("about_product", String(16)),
Column("user_id", Integer),
Column("user_name", String(16)),
Column("review_id", Integer),
Column("review_title", String(16)),
Column("review_content", String(16)),
Column("img_link", String(16)),
Column("product_link", String(16))
)
metadata_obj.create_all(engine)
rows =[{
"product_id": "B0BPJBTB3F",
"product_name": "Khaitan ORFin Fan heater for Home and kitchen-K0 2215",
"category": "Home\u0026Kitchen|Heating,Cooling\u0026AirQuality|RoomHeaters|FanHeaters",
"discounted_price": "1299.0",
"actual_price": "2495.0",
"discount_percentage": "0.48",
"rating": "2",
"rating_count": "2",
"about_product": "Khaitan Orfin Fan heater for Home and kitchen|POWERFUL 2000 WATT|HEATING POSITION 1000 W-2000W|ADJUSTABLE THERMOSTAT TEMP.CONTROL|AUTOMATIC THERMAL CUTOUT FOR SAFETY|FRONT GRILL FOR SAFETY|TURBO FAN",
"user_id": "AGHT3K4KSG5MAQUSXRDT5VNB73GA,AE4Q5XQ7SZW35EEUJKQ3IV2IIBQQ",
"user_name": "Manidipa Sengupta,Vidisha",
"review_id": "R1OO2ED6615EX1,RR4S5JTJMCPA5",
"review_title": "Bad quality,Amazing product..",
"review_content": "The heating capacity is zero .Moreover i have initiated return request. Noone has come to collect it,Best heater at this price. Quality is very good . Suggest everyone to purchase this heater.......... amazing product to buy...",
"img_link": "https://m.media-amazon.com/images/W/WEBP_402378-T1/images/I/31B8Pd1SmLL._SX300_SY300_QL70_FMwebp_.jpg",
"product_link": "https://www.amazon.in/Khaitan-ORFin-heater-Home-kitchen-K0/dp/B0BPJBTB3F/ref\u003dsr_1_326?qid\u003d1672923609\u0026s\u003dkitchen\u0026sr\u003d1-326"
}, {
"product_id": "B0BFBNXS94",
"product_name": "Personal Size Blender, Portable Blender, Battery Powered USB Blender, with Four Blades, Mini Blender Travel Bottle for Juice, Shakes, and Smoothies (Pink)",
"category": "Home\u0026Kitchen|Kitchen\u0026HomeAppliances|SmallKitchenAppliances|HandBlenders",
"discounted_price": "669.0",
"actual_price": "1499.0",
"discount_percentage": "0.55",
"rating": "2.3",
"rating_count": "13",
"about_product": "✔【Easy to carry around】- This handheld blender is equipped with a travel cover for easy carrying. You can drink nutritious juices, milkshakes or smoothies wherever you want, such as home, office, gym, travel or any other outdoor activities. In addition, it can be taken on the plane.|✔【Portable design】: The unique design can separate the base and the cup body. The USB juicer cup is equipped with 1400mAh rechargeable high-quality batteries that can be recharged in a variety of ways, like charging by power bank, AC Adapter, and charging time is 3-5 hours; fully charged can produce 15-20 cups of juice.|✔【food grade material】- The portable blender is made by high-quality ABS and silicone, food-grade material. It has unique safety design including Silicone bottom, non-slip and shock absorption.This portable juicer is also a suitable gift for juice and travel enthusiasts.|✔【4 Blade design】- The portable blender for milkshakes and smoothies has a powerful motor base and 4 food-grade stainless steel 3D blades.The SUS304 Stainless Stell of cutter head made with food-grade electrolysis technology is durable and has excellent mixing ability, allowing the pulp to be quickl|✔【One button blending/cleaning】: simple button touch. 350ml capacity when cleaning, just put an appropriate amount of water in the cup and press the button to automatically clean. This can save you a lot of trouble.",
"user_id": "AHRDA66XO63XYCBZJMW4EUJN3BFQ,AELE2SOO7LBNHXU7UK5F7TGQHA6Q,AHAVCLRCPYO2MFYPTURF33N7XH5A,AE762UDUDQPW4R4QHHTIL7TPTJUA,AEGZSJIUSKF2EKIKGLNKY2CU6WXA",
"user_name": "Manya,Been,Podili Parasuram,Rejoy Jacob,Priya",
"review_id": "R1WJ8T3U9P42IU,RM9RH8FX9U95D,R31M8UXT7NLOMY,R18Q7M2R00EW68,R11NHZQ8OKA9U0",
"review_title": "Nice product i recommend to buy,Do not buy!! Defective product,Wast of money,Very very bad portable,Waste of money its not working properly",
"review_content": "I liked that it is so convenient to carry,Waste of money. Defective product, cheap quality. doesn't blend at all,https://m.media-amazon.com/images/I/71IVsjyZ13L._SY88.jpg,First charge problemSecond motor proble,https://m.media-amazon.com/images/I/61aXXxIxPwL._SY88.jpg",
"img_link": "https://m.media-amazon.com/images/I/417TQs3uroL._SX300_SY300_QL70_FMwebp_.jpg",
"product_link": "https://www.amazon.in/Personal-Blender-Portable-Battery-Smoothies/dp/B0BFBNXS94/ref\u003dsr_1_261_mod_primary_new?qid\u003d1672923605\u0026s\u003dkitchen\u0026sbo\u003dRZvfv%2F%2FHxDF%2BO5021pAnSA%3D%3D\u0026sr\u003d1-261"
}, {
"product_id": "B0B7L86YCB",
"product_name": "Green Tales Heat Seal Mini Food Sealer-Impulse Machine for Sealing Plastic Bags Packaging",
"category": "Home\u0026Kitchen|Kitchen\u0026HomeAppliances|SmallKitchenAppliances|VacuumSealers",
"discounted_price": "161.0",
"actual_price": "300.0",
```json
[
{
"product_id": "B0B7L86YCB",
"product_name": "Green Tales Mini Sealer Impulse Sealing Machine for Plastic Bags, Portable Heat Sealer for Food Storage, Snacks, Fruits, Vegetables, Travel, Kitchen Gadgets (Multicolor)",
"category": "Home\u0026Kitchen|Kitchen\u0026HomeAppliances|KitchenTools\u0026Gadgets|FoodSealers",
"discounted_price": "169.0",
"actual_price": "499.0",
"discount_percentage": "0.66",
"rating": "2.8",
"rating_count": "109",
"about_product": "Mini Heat Sealer: 这款迷你封口机非常适合包装,防止食物和零食受潮。 它可以用于各种类型的塑料袋,例如零食袋、箔袋、薯片袋和各种 PVC 材料。 它非常适合厨房、钓鱼、露营、旅行等。|易于使用:我们的食品封口机非常容易使用,只需按住并将迷你食品封口机拉过袋子即可形成气密密封。 您可以重新密封原始袋子以保持食物和零食的新鲜,也可以将食物储存在冰箱中。|高质量:这款封口机的外壳由优质 ABS 材料制成,耐高温和低温。 无毒耐用。 使用后,可以将封口机挂在挂钩上,方便存放。|便携轻便:这款口袋封口机携带非常方便,您可以轻松地将其放入您的包或口袋中。 无论您是旅行、露营还是在厨房,您都可以使用它来密封食物。|电池供电:这款封口机由 2 节 AA 电池供电(不包括在内)。 安装电池后,只需按下加号即可开始加热。 使用后,请取出电池以防止电池漏液并损坏产品。",
"user_id": "A3T39Q920K1L9U247566E2V427HQ,A18E10S313QG49K37Q55J1K3678Q,A1QJ5634F9T4834761181I25695A,A253V2299N2F1V877892F36486EQ,A1677G74S9Q356529183V593696A,A15I45354549118462154913079Q,A17F86652361521831357913241Q,A1M3P6909099113144441725589Q",
"user_name": "Sandeep,Praveen,shiva,suresh,Ravi,Naveen,Kishor,sandeep",
"review_id": "R1S1X23M91H87P,R34794363A7B7T,R1D215377J813R,R332M2I0Y22E1W,R2U021M7B9306W,R2Q2961286904U,R2J213153421J1,R1XQ000010Q74S",
"review_title": "Good product,Good,Not working,Not good,Waste of money,Good product,Good product,Good product",
"review_content": "l normal thin polybag,Good. Works",
"img_link": "https://m.media-amazon.com/images/W/WEBP_402378-T2/images/I/411NB1EXJNL._SY300_SX300_QL70_FMwebp_.jpg",
"product_link": "https://www.amazon.in/Green-Tales-Sealer-Impulse-Machine-Packaging/dp/B0B7L86YCB/ref\u003dsr_1_383?qid\u003d1672923611\u0026s\u003dkitchen\u0026sr\u003d1-383"
},
{
"product_id": "B0BNDGL26T",
"product_name": "MR. BRAND Portable USB Juicer Electric USB Juice Maker Mixer Bottle Blender Grinder Mixer,6 Blades Rechargeable Bottle with (Multi color) (MULTI MIXER 6 BLED)",
"category": "Home\u0026Kitchen|Kitchen\u0026HomeAppliances|SmallKitchenAppliances|JuicerMixerGrinders",
"discounted_price": "499.0",
"actual_price": "2199.0",
"discount_percentage": "0.77",
"rating": "2.8",
"rating_count": "109",
"about_product": "便携式和方便充电:这款小巧轻便的设计方便您携带到学校、办公室、公园、露营等任何地方。 而且它也方便通过移动电源、笔记本电脑、电脑、汽车或其他 USB 设备充电。|易于安全清洁 - 它具有智能安全保护装置,磁感应开关超安全,易于使用和清洁,榨汁杯的身体和底部可以分开,您可以轻松清洁它|多功能 - 使用我们的果汁搅拌机混合各种水果和蔬菜,您可以制作天然美味的果汁、奶昔、冰沙和其他婴儿食品。 它非常便携,非常适合旅行、户外活动。|随时随地享受您的果汁。|6 个不锈钢刀片,锋利耐用,可以使用很长时间。",
"user_id": "AEJKHGA26MUVUZIYWZOW4B6I4X7Q,AF3B47EOSBULYG63EGZZZGO6HTNA,AGNSXRFJBDVGM7FS7YYPNCEO7XFQ,AHR53IW5LAAXGGFK3DRWRMXMM7KQ,AE5W6S5KCJV6L2WMBIOKYWQJN37Q,AH5J4DROVHI6XHMTCBAK7WWU3F4Q,AE5KAK3S3XZDPRUR2VCND2QNZTUQ,AEKG7ELYA43YNPZ2YT3ORIL2VSOA",
"user_name": "Yashvant Gote,Nargis Sultana,S.I.KUMAR,Ravi,Lokesh Hegde,Abhinav Anand,Any babar,Sarada peram",
"review_id": "RGB7OLWZEBW2D,R35V1I6KBBWDA1,R2S9K0UTNSD0L6,R3RC91ZJN8FXRE,RHM5Q098AI06R,R2QOHI14M69TVA,R2PQH5L3O1O0F4,R3TYY0655P2RMO",
"review_title": "Portable but not much powerful,not so good. power back up is very poor.its more like a toy for my 9 years old girl.,500 rs ok,Don\u0027t be fooled by ratings, not a good product,Not recommended,Worst Battery, no use,It is affordable .,User friendly blender, Recommended to buy nice products",
"review_content": "Not sufficient power,the product is more like a toy for kids. can\u0027t use it as a proper juicer. power back up is very poor.,Ok,I had to replace this product first time because it was leaking and now after replacement the new one has no battery backup and vibrates too much.The MRP is above 2000 rupees which is not at all justfied by the product.After buying the product I found that with the product they are giving a cashback offer of 25 to 100 rs if you give 5 star review, probably that\u0027s why it has good ratings. I feel I was fooled by the ratings.,Waste product as the juicer is leaking which creates"
}
]
{
"product_id": "B0BBVKRP7B",
"product_name": "SHREENOVA 蓝牙智能手表健身追踪器,带心率、睡眠、血氧、活动追踪、多种运动模式、IP67 防水智能手表,适用于男士女士(黑色)",
"category": "电子产品|可穿戴技术|智能手表",
"discounted_price": "799.0",
"actual_price": "1999.0",
"discount_percentage": "0.6",
"rating": "2.6",
"rating_count": "178",
"about_product": "⌚【男士女士健身追踪器手表】:SHREENOVA 智能手表可以追踪您的日常活动,例如步数、距离、燃烧的卡路里和活动时间。它还支持多种运动模式,例如步行、跑步、骑自行车、跳绳、羽毛球、篮球和足球。有了这款智能手表,您可以更好地了解您的健身水平,并对您的锻炼计划进行调整。\n⌚【心率和睡眠追踪器】:这款健身追踪器手表可以自动、持续地监测您的实时心率,并通过对睡眠质量数据的全面分析来追踪您的睡眠时间和一致性。您可以在应用程序中查看您的睡眠数据,并对您的生活方式进行调整以改善您的睡眠质量。\n⌚【智能通知】:通过蓝牙将智能手表连接到您的手机,您可以在手表上接收来电、短信和 SNS(Facebook、WhatsApp、Instagram、Twitter 等)的通知。您还可以在手表上拒接电话。绝不会错过任何重要信息。\n⌚【IP67 防水和长电池续航时间】:这款智能手表具有 IP67 防水功能,这意味着您可以在洗手或在雨中使用它。正常使用情况下,电池可持续使用 7-10 天,待机时间为 20 天。您可以享受您的健身之旅,而无需担心电池寿命。\n⌚【更多功能】:这款智能手表还具有许多实用功能,例如音乐控制、遥控相机、久坐提醒、闹钟、秒表、查找手机等。它是送给自己、家人和朋友的绝佳礼物。",
"user_id": "A31N2051484BFF,A14X770938O75J,A19W6732V8192Q,A225589671X66H,A1775T9Q27B09N,A250X56514R99M,A19K78L405356L,A1775T9Q27B09N",
"user_name": "Amazon Customer,Ankit ,Ayush ,Saurabh ,Saurabh ,Rohit,Amazon Customer,Saurabh",
"review_id": "R2W5022N3T4H0U,R10E712533189W,R14297000T1712,R1901W3T56161E,R3538D770L6V4I,R1U06E8041J532,R21750J52M817E,R3538D770L6V4I",
"review_title": "ce product,Dislike product also not return its only replacement,पहिल्या दिवसापासूनच ती वॉच ऑन होत नाही. चार्ज केले तरी पण ऑन होत नाही. पुर्णपणे third class वॉच पाठविली Amazon ने. दिवसेंदिवस Amazon ची सर्व्हिस आणि प्रॉडक्ट bad होत चाललेले दिसत आहे.,Bhot Jada ghatia h h,All the products are very good working there is no any issue till now.",
"review_content": "ce product,Dislike product also not return its only replacement,,Iska tauch kaam nahi kar raha hai aur kewal mobile adoptot se charge karne par on dikh raha phir turat band ho ja raha hai.ise wapas karna hai.,पहिल्या दिवसापासूनच ती वॉच ऑन होत नाही. चार्ज केले तरी पण ऑन होत नाही. पुर्णपणे third class वॉच पाठविली Amazon ने. दिवसेंदिवस Amazon ची सर्व्हिस आणि प्रॉडक्ट bad होत चाललेले दिसत आहे.,Bhot Jada ghatia h h,All the products are very good working there is no any issue till now.",
"img_link": "https://m.media-amazon.com/images/I/41lnTFZGz9L._SX300_SY300_QL70_ML2_.jpg",
"product_link": "https://www.amazon.in/SHREENOVA-Bluetooth-Fitness-Activity-Tracker/dp/B0BBVKRP7B/ref\u003dsr_1_338?qid\u003d1672895850\u0026s\u003delectronics\u0026sr\u003d1-338"
}, {
"product_id": "B0BBLHTRM9",
"product_name": "IONIX 水龙头过滤器多层 | 活性炭水龙头水过滤器通用接口家用厨房水龙头水净化器过滤器滤芯五层水过滤器 - 1 个装",
"category": "家居与厨房|厨房与家用电器|净水器及配件|净水器配件",
"discounted_price": "199.0",
"actual_price": "699.0",
"discount_percentage": "0.72",
"rating": "2.9",
"rating_count": "159",
"about_product": "水龙头过滤器:内置分层过滤器可以分离椰壳活性炭、沸石、PVA 无纺布、亚硫酸钙和橡胶,适用于净化硬水和井水。|健康的生活方式:去除水中的氯、重金属和其他杂质,水更甜,更安全。|易于清洁:家庭和办公室必备品,100% 全新和高品质。耐高温,不易变形。要清洁,只需取下过滤器并在水下冲洗即可。|节水:由柔软的橡胶材料制成,可以防止漏水,从而节省您每次使用时的用水量。;包装清单:1 * 水龙头过滤器|包含的组件:1 X 五层水龙头",
"user_id": "AF6LRVDRKYWPTZXZLQERZ3LXCWDA,AG7FU75LA5ONPMNEVH6X47PHPHYA,AG3YRWMWYEW3G2WELWCNIU2H7HQQ,AGXZDH5CDJHVZVCYA6555BIZIWTQ,AEP6P6MBRADJL3SDICYEMQUWXVEA,AEVOU4VDGD6M5VOUU47DZ7JRABEA,AGA3BZEL7AM75FQS67KO32HQKWHQ,AHYU5NW2HTBFSIBPELM5BWRVFHDQ",
"user_name": "Anmol Khanna,G.l.sudhakar,Amazon Customer,manoj,Satya,Swarup Panday,Reyaansh Arora,neha keluskar",
"review_id": "R9GL8284FSYUG,R1Q6Z3DZDJMDPN,R25CLTZM7X33KC,R3EZN6N234M56M,R3V5ZJK278N7DE,R2D7IYLDOK44OG,R3E1T8ZS17TP57,R388P83LV3P6PH",
"review_title": "Stop working after few days,Ok. Changing every 4 months toomuch,Tap filter,Quality,Doesn\u0027t purify water,Very good product,REALLY GOOD!,Bad",
"review_content": "Stop working after few days,Ok,It doesn\u0027t fit easily. Little water pressure the filter falls off. Fitting is draw back for the product. Water purification method implied is good. Installation must be made easy.,Having hair problem due to water so bought this for my bathroom. Good quality product but After using it for couple of days filtered water pressure has reduced.,Pros:-Easy to install (pipe comes with 3 different dimensions)Cons:- Hoped it to purify the tap water (as mentioned in their description). Unfortunately doesn\u0027t serve the purpose - I measured my usual water with tds ppc meter - the result was 427 (usual for Bangalore).
```markdown
## 产品评论
```json
{
"product_id": "B09X29997C",
"product_name": "Nirdambhay 手持便携式迷你袋封口机,塑料袋热封机,食品储存,零食,薯片,新鲜食品保鲜器,厨房小工具(多色)",
"category": "家居与厨房|厨房与用餐|厨房用具和小工具|封口机",
"discounted_price": "199.0",
"actual_price": "499.0",
"discount_percentage": "0.6",
"rating": "3.0",
"rating_count": "129",
"about_product": "迷你热封机:迷你袋封口机由ABS材料制成,耐高温和低温。无毒耐用。封口机小巧便携,易于携带和存放。|易于使用:这款热封机非常容易使用。使用前,打开盖子,按压5秒预热,然后只需沿着任何袋子的边缘滑动即可封口。|广泛应用:这款塑料袋封口机可以封口各种塑料袋,如零食袋、铝箔袋、薯片袋和各种PVC材料。|易于携带:这款袋封口机小巧便携,易于携带和存放。您可以将其放在包里,随身携带。|电池供电:这款袋封口机由2节AA电池供电(不含)。",
"user_id": "AEO5Q4P2YQ5F6W5566J2G4L642AQ,AEMJ2V5432QW75W65663D42Q52XA,AE36D26424W6566524G3L44325HA,AG5J425634W5666524G3L44325HA,AE65J425634W5666524G3L44325HA,AE75J425634W5666524G3L44325HA,AE85J425634W5666524G3L44325HA,AE95J425634W5666524G3L44325HA",
"user_name": "Komal,Anjali,Siddharth ,Riya,Riya ,Riya,Riya,Riya",
"review_id": "R1N1339144K4,R223234234,R33234234,R44234234,R55234234,R66234234,R77234234,R88234234",
"review_title": "不好,一般工作,好,好,好,好,好,好",
"review_content": "有时会封口,有时会烧焦塑料。此外,如果施加正确的压力,封口会脱落,因此也不可靠。封口机的质量非常好,而且封口良好。唯一的事情是您在封口时必须用力按压。只需几秒钟即可封口整个包装。当您带着蹒跚学步的孩子旅行并携带大量零食包时,很好。口袋友好又可爱,工作一般",
"img_link": "https://m.media-amazon.com/images/W/WEBP_402378-T2/images/I/21rLuqop7cL._SY300_SX300_QL70_FMwebp_.jpg",
"product_link": "https://www.amazon.in/Nirdambhay-Handheld-Portable-Resealer-Including/dp/B08YK7BBD2/ref\u003dsr_1_338?qid\u003d1672923609\u0026s\u003dkitchen\u0026sr\u003d1-338"
}, {
"product_id": "B09F6D21BY",
"product_name": "7SEVEN 兼容 LG 电视遥控器,适用于 LG 非魔术智能电视遥控器(不支持鼠标和语音)MR20GA Prime Video 和 Netflix 热键",
"category": "电子产品|家庭影院、电视和视频|配件|遥控器",
"discounted_price": "790.0",
"actual_price": "1999.0",
"discount_percentage": "0.6",
"rating": "3.0",
"rating_count": "103",
"about_product": "适用于 LG 电视系列所有型号的兼容遥控器|兼容型号:适用于您的 LG 智能电视通用遥控器 AN-MR600G AN-MR650 AN-MR650G ANMR650A ANMR600 AN-MR650B AN-MR19BA AN-MR18BA 等|应用程序热键:Prime Video、Netflix 并自定义您自己的!无需编程或设置。|这是专用的替换遥控器,不是原装的,但功能与原装的 100% 相同,并且涵盖了原装遥控器的所有功能。|注意:此遥控器不支持语音命令",
"user_id": "AH7NTBDGAMGOFFADEVWJL3O4YQ2A,AEJUIUF6CYKRBWLSOPWPE7KMC3RA,AF45WMWXMOPN3ELUJ2H2N63JWKGA,AH6MPOEE6ICQG3RBULF7TOQVMMEA,AH7QLQDC5BMOKDDRGGWSEP3AQ6IQ,AEIXFEXXMTDJNPWUMOIEA34ZLC7Q,AEQV4U4ZGMGZOWC4RQSUQZGHYSHA,AG7DCRRGNMM7FSENOSNAQTVYBHPQ",
"user_name": "Jarlina Nath,Sona,Ranjit Harchekar,Myneni Suneeta,prithvi,Srinivas,upender,Ishita Bhadana",
"review_id": "R1S2PH1JD9B9XB,R3UUKCS12Q0B9X,R16YH8SVJU5W61,R32XCAYQRNE0Q3,R1FQD9T17LXHLF,R17H2I7PYTIEIA,RWEPEYF95XCK9,R14CFFXT17UAJI",
"review_title": "不好,没有语音识别,没有像原装 LG 遥控器那样的指针光线。不包括这些功能,最好的产品,无法正常工作,无法使用,不要购买,它没有指针,无法正常工作,完美",
"review_content": "遥控器的鼠标功能无法使用,带按钮的遥控器似乎还可以,但没有语音识别,也没有像原装 LG 产品那样的光线指针。希望对网站上的虚假陈述进行退款..在我的投诉后你修改了描述。最好的产品,数字按钮无法使用,有缺陷的产品,它不适用于电视,不喜欢该产品,因为它没有指针选项,无法正常工作,购买的最佳选择,因为它很难获得 OLED 电视遥控器的更换...",
"img_link": "https://m.media-amazon.com/images/W/WEBP_402378-T2/images/I/315sEpeo50L._SX300_SY300_QL70_FMwebp_.jpg",
"product_link": "https://www.amazon.in/Compatible-Suitable-Control-Non-Support-Netflix/dp/B09F6D21BY/ref\u003dsr_1_344?qid\u003d1672909141\u0026s\u003delectronics\u0026sr\u003d1-344"
}, {
"product_id": "B0B94JPY2N",
"product_name": "Amazon Brand - Solimo"
```python
from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime, Boolean, Identity
from sqlalchemy import insert, select, update, delete
from sqlalchemy.orm import Session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import inspect
import pandas as pd
import json
Base = declarative_base()
class sales_data(Base):
__tablename__ = 'sales_data'
id = Column(Integer, Identity(), primary_key=True)
product_name = Column(String)
product_id = Column(String)
user_name = Column(String)
review_id = Column(String)
review_title = Column(String)
review_content = Column(String)
img_link = Column(String)
product_link = Column(String)
def __repr__(self):
return f"<sales_data(product_name='{self.product_name}', product_id='{self.product_id}', user_name='{self.user_name}', review_id='{self.review_id}', review_title='{self.review_title}',review_content='{self.review_content}', img_link='{self.img_link}', product_link='{self.product_link}')>"
engine = create_engine("sqlite:///:memory:", echo=False, future=True)
Base.metadata.create_all(engine)
rows = [{
"product_name": "Tokdis MX1 Bluetooth Calling Smartwatch",
"product_id": "B0B82YGCF6",
"user_name": "Gourav Choudhrani,Mustak ali,Amit,Pankaj solanki,yemcee1954,Shekh ismail,Mukta,Penchalbabu",
"review_id": "RGEDIZCX7LB34,R19GGFEAAXAUKK,R3L3EFRRM8X2IY,REN3MEL7IYDKT,R2H176Z5380NWJ,R1AFCXRUZ8KCCK,R16381PP969JBP,RFDKRGYGQB7U6",
"review_title": "Its is good but battery life is very poor,Heart rate sanser and battery backup,Nice product,Good product within small price range,poor.,Cool product,Gets disconnected , time n data doesn\u0027t updates automatically,It\u0027s good deal at 849/- works fine for first few days",
"review_content": "Its is value for money,,Good product,Good, liked,,charging lasts short time. charging with straps impossible. very poor working. not worth the money paid.,It\u0027s tiny specially can be look great on tiny wrist, look is also nice but internal feature is some down it must be upgrated.,Auto data collection n update not there . Gets disconnected all time. Hard to connect. Doesn\u0027t get update automatically with time n day . Today is 12 dec Monday n it\u0027s still showing 10 dec Saturday. Had to update time everytime,It works fine for first five days, even it is cheaper, it should be worth of the money. And now two months works good",
"img_link": "https://m.media-amazon.com/images/I/71m-tK5Q-FL._AC_UY218_.jpg",
"product_link": "https://www.amazon.in/Tokdis-MX-1-Bluetooth-Calling-Smartwatch/dp/B0B82YGCF6/ref\u003dsr_1_370?qid\u003d1672895857\u0026s\u003delectronics\u0026sr\u003d1-370"
}]
for row in rows:
stmt = insert(sales_data).values(**row)
with engine.begin() as connection:
cursor = connection.execute(stmt)
inspector = inspect(engine)
columns_info = [(col["name"], col["type"]) for col in inspector.get_columns("sales_data")]
table_description = "Columns:\n" + "\n".join([f" - {name}: {col_type}" for name, col_type in columns_info])
print(table_description)
我们创建了一个sqlite表并列出了数据,并将其导入到sales_data表中
from smolagents import tool,OpenAIServerModel
api_key = # Replace with your secret name
## Specify the model, which will leverage the api_key we just got
model=OpenAIServerModel(
model_id="gemini-2.0-flash-exp",
api_base="https://generativelanguage.googleapis.com/v1beta/openai/",
api_key=api_key,
temperature=0.7
)
@tool
def sql_engine(query: str) -> str:
"""
Allows you to perform SQL queries on the table. Returns a string representation of the result.
The table is named 'sales_data'. Its description is as follows:
Columns:
- product_id: INTEGER
- product_name: VARCHAR(16)
- category: VARCHAR(16)
- discounted_price: FLOAT
- actual_price: FLOAT
- discount_percentage: FLOAT
- rating: INTEGER
- rating_count: INTEGER
- about_product: VARCHAR(16)
- user_id: INTEGER
- user_name: VARCHAR(16)
- review_id: INTEGER
- review_title: VARCHAR(16)
- review_content: VARCHAR(16)
- img_link: VARCHAR(16)
- product_link: VARCHAR(16)
Args:
query: The query to perform. This should be correct SQL.
"""
output = ""
with engine.connect() as con:
rows = con.execute(text(query))
for row in rows:
output += "\n" + str(row)
return output
from smolagents import CodeAgent, HfApiModel
agent = CodeAgent(
tools=[sql_engine],
model=model,
)
agent.run("Can you give me the rating_count for each category")
当我询问查询“Can you give me the rating_count for each category”时,agent处理了NLP查询并生成了SQL,然后针对表“sales_data”执行了SQL,如下所示
Can you give me the rating_count for each category │
│ │
╰─ OpenAIServerModel - gemini-2.0-flash-exp ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 0 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
─ Executing this code: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
query = "SELECT category, SUM(rating_count) FROM sales_data GROUP BY category"
result = sql_engine(query=query)
print(result)
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Execution logs:
('Computers&Accessories|Accessories&Peripherals|Cables&Accessories|Cables|USBCables', 200)
('Electronics|HomeTheater,TV&Video|Accessories|RemoteControls', 103)
('Electronics|WearableTechnology|SmartWatches', 768)
('Home&Kitchen|Heating,Cooling&AirQuality|RoomHeaters|FanHeaters', 2)
('Home&Kitchen|Kitchen&HomeAppliances|SmallKitchenAppliances|HandBlenders', 13)
('Home&Kitchen|Kitchen&HomeAppliances|SmallKitchenAppliances|JuicerMixerGrinders', 109)
('Home&Kitchen|Kitchen&HomeAppliances|SmallKitchenAppliances|VacuumSealers', 641)
('Home&Kitchen|Kitchen&HomeAppliances|WaterPurifiers&Accessories|WaterPurifierAccessories', 159)
Out: None
[Step 0: Duration 1.87 seconds| Input tokens: 2,373 | Output tokens: 77]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 1 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
─ Executing this code: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
query_result = sql_engine(query="SELECT category, SUM(rating_count) FROM sales_data GROUP BY category")
final_answer(query_result)
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Out - Final answer:
('Computers&Accessories|Accessories&Peripherals|Cables&Accessories|Cables|USBCables', 200)
('Electronics|HomeTheater,TV&Video|Accessories|RemoteControls', 103)
('Electronics|WearableTechnology|SmartWatches', 768)
('Home&Kitchen|Heating,Cooling&AirQuality|RoomHeaters|FanHeaters', 2)
('Home&Kitchen|Kitchen&HomeAppliances|SmallKitchenAppliances|HandBlenders', 13)
('Home&Kitchen|Kitchen&HomeAppliances|SmallKitchenAppliances|JuicerMixerGrinders', 109)
('Home&Kitchen|Kitchen&HomeAppliances|SmallKitchenAppliances|VacuumSealers', 641)
('Home&Kitchen|Kitchen&HomeAppliances|WaterPurifiers&Accessories|WaterPurifierAccessories', 159)
[Step 1: Duration 0.83 seconds| Input tokens: 5,113 | Output tokens: 154]
\n('Computers&Accessories|Accessories&Peripherals|Cables&Accessories|Cables|USBCables', 200)\n('Electronics|HomeTheater,TV&Video|Accessories|RemoteControls', 103)\n('Electronics|WearableTechnology|SmartWatches', 768)\n('Home&Kitchen|Heating,Cooling&AirQuality|RoomHeaters|FanHeaters', 2)\n('Home&Kitchen|Kitchen&HomeAppliances|SmallKitchenAppliances|HandBlenders', 13)\n('Home&Kitchen|Kitchen&HomeAppliances|SmallKitchenAppliances|JuicerMixerGrinders', 109)\n('Home&Kitchen|Kitchen&HomeAppliances|SmallKitchenAppliances|VacuumSealers', 641)\n('Home&Kitchen|Kitchen&HomeAppliances|WaterPurifiers&Accessories|WaterPurifierAccessories', 159)
场景2:获取给定股票的股票价格
使用了Code Agent和内置工具DuckDuckGoSearchTool
from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel,OpenAIServerModel
import yfinance as yf
api_key =
model=OpenAIServerModel(
mo
## 修复后的技术文章
```python
model = ChatOpenAI(
model_name="gemini-2.0-flash-exp",
api_base="https://generativelanguage.googleapis.com/v1beta/openai/",
api_key=api_key,
temperature=0.7
)
agent = CodeAgent(
tools=[DuckDuckGoSearchTool()],
additional_authorized_imports=["yfinance"],
model=model
)
response = agent.run(
"is if Microsoft Inc (NASDAQ: AAPL). Use the YFinance Library."
)
print(response)
当我提问“获取 Microsoft Inc (NASDAQ: AAPL) 的股票价格。使用 YFinance 库。”时,agent 处理了 NLP 查询并生成了输出
search_query = "Microsoft (MSFT) 在美国的当前股价,以美元计价"
search_results = web_search(query=search_query)
print(search_results)
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Execution logs:
### Search Results
[Microsoft Corporation (MSFT) Stock Price, News, Quote & History - Yahoo ...](https://finance.yahoo.com/quote/MSFT/)
Find the latest Microsoft Corporation (MSFT) stock quote, history, news and other vital information to help you with your stock trading and investing. ... Nasdaq Real Time Price • USD. Microsoft ...
[MSFT Stock Price | Microsoft Corp. Stock Quote (U.S.: Nasdaq ...](https://www.marketwatch.com/investing/stock/MSFT)
MSFT | Complete Microsoft Corp. stock news by MarketWatch. View real-time stock prices and stock quotes for a full financial overview.
[Microsoft Corp (MSFT) Stock Price & News - Google Finance](https://www.google.com/finance/quote/MSFT:NASDAQ)
Get the latest Microsoft Corp (MSFT) real-time quote, historical performance, charts, and other financial information to help you make more informed trading and investment decisions.
[Microsoft Corporation (MSFT) Real-Time Quotes - Nasdaq](https://www.nasdaq.com/market-activity/stocks/msft/real-time)
Get real-time updates on Microsoft Corporation Common Stock (MSFT) stock quotes, trades, and more. Make informed investments with Nasdaq.
[Microsoft Corporation (MSFT) Stock Price, Quote & News - Stock Analysis](https://stockanalysis.com/stocks/msft/)
Get a real-time Microsoft Corporation (MSFT) stock price quote with breaking news, financials, statistics, charts and more. ... MSFT · Real-Time Price · USD. Watchlist Compare. 408.43-2.11 (-0.51%) At
close: Feb 14, 2025, 4:00 PM. 408.10 ... But stock prices face downward pressure due to various uncertainties, with the ongoing U.S.-China ...
[Microsoft Corporation (MSFT) stock price, news, quote and history ...](https://sg.finance.yahoo.com/quote/MSFT/)
Find the latest Microsoft Corporation (MSFT) stock quote, history, news and other vital information to help you with your stock trading and investing. ... NasdaqGS - Nasdaq Real Time Price • USD.
Microsoft Corporation (MSFT) Follow. Compare. 409.64 +1.21 +(0.30%) At close: 18 February at 4:00:01 pm GMT-5 . 409.80 +0.16 ... 409.64 Current. 650 ...
[Microsoft Investor Relations - Microsoft Stock Lookup](https://www.microsoft.com/en-us/investor/stock-lookup)
D irect Stock Purchase and Dividend Reinvestment Program. Computershare, Microsoft's transfer agent, administers a direct stock purchase plan and a divident reinvestment plan for the company. To find
out more about these programs you may contact Computershare directly at (800) 285-7772, Option 1, between the hours of 8 A.M. and 8 P.M. Eastern Time, Monday through Friday, and Saturday 9 A.M ...
[MSFT Stock Chart and Price - Microsoft (NASDAQ) - TradingView](https://www.tradingview.com/symbols/NASDAQ-MSFT/)
The current price of MSFT is 409.64 USD - it has increased by 0.18% in the past 24 hours. Watch Microsoft Corp. stock price performance more closely on the chart. What is Microsoft Corp. stock ticker?
Depending on the exchange, the stock ticker may vary. For instance, ...
[Microsoft Corporation (MSFT) Stock Price, Quote, News & History - Nasdaq](https://www.nasdaq.com/market-activity/stocks/msft)
Discover real-time Microsoft Corporation Common Stock (MSFT) stock prices, quotes, historical data, news, and Insights for informed trading and investment decisions. Stay ahead with Nasdaq.
[Microsoft Corporation (MSFT) Stock Price, News, Quote & History - Yahoo ...](https://ca.finance.yahoo.com/quote/MSFT/)
Find the latest Microsoft Corporation (MSFT) stock quote, history, news and other vital information to help you with your stock trading and investing. ... NasdaqGS - Delayed Quote • USD. Microsoft
Corporation (MSFT) Follow. Compare. 408.43 -2.11 ... Current Quarterly Annual . As of 2025-02-14. Market Cap . 3.04T . Enterprise Value . 3.03T ...
Out: None
[Step 3: Duration 3.33 seconds| Input tokens: 18,430 | Output tokens: 2,240]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 4 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
─ Executing this code: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
final_answer("408.43")
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Out - Final answer: 408.43
[Step 4: Duration 2.15 seconds| Input tokens: 27,058 | Output tokens: 2,494]
408.43
场景 3:使用提示生成照片
**使用代码代理和 image_generation_tool 我们从 HuggingFace Spaces 导入了一个工具,并使用它来生成图像。简单而强大。
from smolagents import CodeAgent,OpenAIServerModel, Tool
api_key =
model=OpenAIServerModel(
model_id="gemini-2.0-flash-exp",
api_base="https://generativelanguage.googleapis.com/v1beta/openai/",
api_key=api_key,
temperature=0.7
)
image_generation_tool = Tool.from_space(
"black-forest-labs/FLUX.1-schnell",
name="image_generator",
description="Generate an image from a prompt",
token="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"
)
image_generation_tool("A sunny beach")
model =model
agent = CodeAgent(tools=[image_generation_tool], model=model)
agent.run(
"Improve this prompt, then generate an image of it. prompt='smolagents by huggingface'"
)
输出:
有了这个,你就明白了如何使用 SmolAgents by Hugging Face 通过示例创建 AI 代理
学习愉快!!!!!!
要深入了解该框架,请查看官方 <https://github.com/huggingface/s
## Mol* 代理
### 简介
Mol* 代理是一个用于在 Mol* 框架中执行任务的强大工具。它们允许您将复杂的任务分解成更小的、可管理的部分,从而提高代码的可维护性和可重用性。
### 代理的类型
Mol* 框架支持多种类型的代理,包括:
* **计算代理:** 用于执行计算密集型任务,例如数据处理和分析。
* **渲染代理:** 用于处理图形渲染和可视化。
* **数据代理:** 用于管理和操作数据。
* **用户界面代理:** 用于处理用户交互和界面更新。
### 创建代理
要创建一个代理,您需要定义一个继承自 `Molstar.Core.Computation.Computation` 类的类。这个类需要实现 `execute` 方法,该方法定义了代理执行的任务。
以下是一个简单的计算代理的示例:
```typescript
import { Computation, Task, Progress } from 'molstar/lib/mol-task';
class MyComputation extends Computation<number, number> {
constructor(private input: number) {
super();
}
async execute(ctx: Computation.Context): Promise<number> {
// 模拟一个耗时操作
await Task.sleep(500);
const result = this.input * 2;
Progress.update(ctx.progress, '计算完成', 100, 100);
return result;
}
}
在这个示例中,MyComputation
代理接受一个数字作为输入,并将其乘以 2。execute
方法模拟了一个耗时操作,并最终返回结果。
使用代理
要使用一个代理,您需要创建一个代理实例,并使用 Task.create
方法来执行它。
以下是如何使用上面创建的 MyComputation
代理的示例:
import { Task } from 'molstar/lib/mol-task';
async function runComputation() {
const computation = new MyComputation(10);
const task = Task.create('My Computation', computation);
const result = await task.run();
console.log('Result:', result); // 输出:Result: 20
}
runComputation();
在这个示例中,我们创建了一个 MyComputation
代理实例,并使用 Task.create
方法创建了一个任务。然后,我们使用 task.run()
方法来执行任务,并获取结果。
代理的优势
使用代理可以带来以下优势:
- 提高代码的可维护性: 通过将复杂的任务分解成更小的、可管理的部分,可以使代码更易于理解和维护。
- 提高代码的可重用性: 代理可以被重用于不同的场景,从而减少代码的重复。
- 提高代码的性能: 代理可以并行执行,从而提高代码的性能。
- 异步操作: 代理支持异步操作,可以避免阻塞用户界面。
总结
Mol* 代理是一个强大的工具,可以帮助您构建更复杂、更可维护、更可重用的 Mol* 应用程序。通过使用不同类型的代理,您可以将任务分解成更小的部分,并提高代码的性能和可维护性。
理解 JavaScript 中的 this
关键字
在 JavaScript 中,this
关键字是一个经常让开发者困惑的概念。它指的是函数执行的上下文,其值取决于函数是如何被调用的。理解 this
的工作方式对于编写可预测且无错误的 JavaScript 代码至关重要。
1. 默认绑定
当函数在全局作用域中被调用时,this
默认绑定到全局对象。在浏览器中,全局对象是 window
。
function myFunction() {
console.log(this);
}
myFunction(); // 输出: window
在严格模式下,全局函数调用中的 this
将是 undefined
。
"use strict";
function myFunction() {
console.log(this);
}
myFunction(); // 输出: undefined
2. 隐式绑定
当函数作为对象的方法被调用时,this
绑定到该对象。
const myObject = {
name: "示例对象",
myFunction: function() {
console.log(this.name);
}
};
myObject.myFunction(); // 输出: 示例对象
3. 显式绑定
JavaScript 提供了 call
、apply
和 bind
方法,允许我们显式地设置 this
的值。
3.1 call
方法
call
方法允许你调用一个函数,并将一个指定的 this
值和单独提供的参数传递给该函数。
function greet(greeting) {
console.log(greeting + ", " + this.name);
}
const person = { name: "Alice" };
greet.call(person, "你好"); // 输出: 你好, Alice
3.2 apply
方法
apply
方法与 call
方法类似,但它接受一个 this
值和一个参数数组。
function greet(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
const person = { name: "Bob" };
greet.apply(person, ["Hello", "!"]); // 输出: Hello, Bob!
3.3 bind
方法
bind
方法创建一个新的函数,当这个新函数被调用时,它的 this
值被设置为提供的值。
function greet() {
console.log("Hello, " + this.name);
}
const person = { name: "Charlie" };
const greetPerson = greet.bind(person);
greetPerson(); // 输出: Hello, Charlie
4. new
绑定
当使用 new
关键字调用一个函数(构造函数)时,this
绑定到新创建的对象。
function Person(name) {
this.name = name;
console.log(this); // 输出: Person { name: 'David' }
}
const david = new Person("David");
console.log(david.name); // 输出: David
5. 箭头函数
箭头函数不绑定自己的 this
值。相反,它会从其周围的(定义时的)上下文继承 this
值。
const myObject = {
name: "示例对象",
myFunction: function() {
const arrowFunction = () => {
console.log(this.name); // 继承自 myFunction 的 this
};
arrowFunction();
}
};
myObject.myFunction(); // 输出: 示例对象
如果箭头函数直接在全局作用域中定义,this
将指向全局对象(在非严格模式下)或 undefined
(在严格模式下)。
const arrowFunction = () => {
console.log(this);
};
arrowFunction(); // 在浏览器中输出: window (非严格模式) 或 undefined (严格模式)
6. 优先级
this
绑定的优先级如下(从高到低):
new
绑定- 显式绑定 (
call
,apply
,bind
) - 隐式绑定
- 默认绑定
总结
理解 JavaScript 中 this
的行为是成为一名熟练的 JavaScript 开发者的关键。通过掌握不同的绑定规则,你可以编写更清晰、更易于维护的代码,并避免常见的 this
相关错误。