Type something to search...
使用 smolagents 创建 AI 代理:全面的逐步指南与实用示例

使用 smolagents 创建 AI 代理:全面的逐步指南与实用示例

smolagents

Hello readers 👋 Hope all are doing well 😊

Above image is generated by smolagents framework, its looking cute right. By the end of this article you will also come to know how to create images using smolagents by hugging face

Agent Eco system

What is Agent?

An Agent is a system that leverages an AI model to interact with its environment in order to achieve a user-defined objective. It combines reasoning, planning, and the execution of actions (often via external tools) to fulfill tasks.

将 Agent 视为具有两个主要部分:

1.The Brain (AI Model)

这是所有思考发生的地方。AI 模型处理推理和规划。它根据情况决定要采取哪些 Actions。

2.The Body (Capabilities and Tools)

这部分代表了 Agent 能够做的一切。

可能的 Actions 范围取决于 Agent 配备了什么。例如,由于人类没有翅膀,他们无法执行“飞” Action,但他们可以执行“走”、“跑”、“跳”、“抓取”等 Actions。

What type of AI Models do we use for Agents?

Agents 中最常见的 AI 模型是 LLM(大型语言模型),它将 Text 作为输入并输出 Text。

众所周知的例子有 OpenAI 的 GPT4、Meta 的 LLama、Google 的 Gemini 等。这些模型已经在大量的文本上进行了训练,并且能够很好地泛化。我们将在下一节中了解更多关于 LLM 的信息。

也可以使用接受其他输入作为 Agent 核心模型的模型。例如,视觉语言模型 (VLM),它就像 LLM,但也理解图像作为输入。我们现在将重点关注 LLM,稍后将讨论其他选项。

How does an AI take action on its environment?

LLM 是令人惊叹的模型,但它们只能生成文本。

但是,如果您要求像 HuggingChat 或 ChatGPT 这样的知名聊天应用程序生成图像,它们可以!这是怎么可能的?

答案是 HuggingChat、ChatGPT 和类似应用程序的开发人员实现了附加功能(称为 Tools),LLM 可以使用这些功能来创建图像。

Credits: HuggingFace

What type of tasks can an Agent do?

一个 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”)来解决。

Note that Actions are not the same as Tools. An Action, for instance, can involve the use of multiple Tools to complete.

允许 Agent 与其环境交互,使公司和个人能够实际使用。

Example 1: Personal Virtual Assistants

像 Siri、Alexa 或 Google Assistant 这样的虚拟助手在代表用户使用其数字环境进行交互时,充当了 Agent。

他们接受用户查询,分析上下文,从数据库中检索信息,并提供响应或启动 Actions(如设置提醒、发送消息或控制智能设备)。

Example 2: Customer Service Chatbots

许多公司部署了聊天机器人作为 Agent,它们用自然语言与客户互动。

这些 Agent 可以回答问题,引导用户完成故障排除步骤,在内部数据库中打开问题,甚至完成交易。

他们预定义的 objective 可能包括提高用户满意度、减少等待时间或提高销售转化率。通过直接与客户互动、从对话中学习并随着时间的推移调整他们的回应,他们展示了 Agent 行动中的核心原则。

示例 3:视频游戏中的 AI 非玩家角色

由 LLM 驱动的 AI 代理可以使非玩家角色 (NPC) 更加动态和不可预测。

他们不再遵循僵化的行为树,而是可以根据上下文做出反应,适应玩家的互动,并生成更细致的对话。这种灵活性有助于创造更逼真、更具吸引力的角色,这些角色会随着玩家的行动而发展。

它们是如何工作的?

代理将首先思考,然后行动,然后观察以执行任何操作

Credits:HuggingFace

总览:Congo 代理

Step1:用户请求“给我拿杯咖啡” Congo 代理

Step2:Congo 代理 思考和计划(将思考和计划选择哪些工具来完成用户请求)Congo 代理 参与推理和计划,弄清楚他需要的步骤和工具:

  1. 去厨房
  2. 使用咖啡机
  3. 煮咖啡
  4. 把咖啡拿回来

Step3:Congo 代理 使用工具完成用户请求

什么是 LLM?大脑(AI 模型)

正如我们已经了解了 llm,我不想详细介绍,但我将重点介绍几件事。

LLM 是一种 AI 模型,擅长理解和生成人类语言。它们接受过大量文本数据的训练,使它们能够学习语言中的模式、结构,甚至细微差别。这些模型通常由数百万个参数组成。

如今,大多数 LLM 都建立在 Transformer 架构之上——一种基于“Attention”算法的深度学习架构,自 2018 年 Google 发布 BERT 以来,引起了人们的极大兴趣。

Transformer 有 3 种类型:

Encoders 基于编码器的 Transformer 将文本(或其他数据)作为输入,并输出该文本的密集表示(或嵌入)。

示例:Google 的 BERT

  • 用例:文本分类、语义搜索、命名实体识别
  • 典型大小:数百万个参数

Decoders 基于解码器的 Transformer 侧重于一次生成一个新标记来完成一个序列。

示例:Meta 的 Llama

  • 用例:文本生成、聊天机器人、代码生成
  • 典型大小:数十亿(以美国人的说法,即 1⁰⁹)个参数

Seq2Seq (Encoder–Decoder) 一个序列到序列的 Transformer 结合 了编码器和解码器。编码器首先将输入序列处理成上下文表示,然后解码器生成一个输出序列。

示例:T5、BART

  • 用例:翻译、摘要、释义
  • 典型大小:数百万个参数

注意力机制 (Attention is all you need)

Transformer 架构的一个关键方面是注意力机制 (Attention)。当预测下一个词时,句子中的每个词的重要性并不相同;例如句子“法国的首都是……”中的“法国”和“首都”这两个词携带了最多的含义。

来源:HuggingFace

这种识别最相关词来预测下一个 token 的过程已被证明非常有效。

虽然 LLM 的基本原理——预测下一个 token——自 GPT-2 以来一直保持一致,但在扩展神经网络和使注意力机制适用于越来越长的序列方面取得了重大进展。

如果您与 LLM 进行过交互,您可能熟悉术语 context length,它指的是 LLM 可以处理的最大 token 数量,以及它拥有的最大 attention span

什么是 AI 工具?主体 (The Body)

工具是提供给 LLM 的一个函数。此函数应实现一个明确的目标。

以下是 AI 代理中一些常用的工具:

这些仅仅是示例,实际上您可以为任何用例创建工具!

一个好的工具应该能够补充 LLM 的能力。

例如,如果您需要执行算术运算,为您的 LLM 提供计算器工具将比依赖模型的原生功能提供更好的结果。

此外,LLM 会根据其训练数据预测提示的完成,这意味着它们的内部知识仅包括训练之前发生的事件。因此,如果您的代理需要最新数据,您必须通过某些工具提供它。

例如,如果您直接(没有搜索工具)询问 LLM 今天的天气,LLM 可能会产生随机的天气幻觉。

来源:Huggingface

一个工具应该包含:

  • 对函数作用的文本描述。
  • 一个 Callable(用于执行操作)。
  • 带有类型的 Arguments
  • (可选)带有类型的 Outputs。

工具如何工作?

正如我们所看到的,LLM 只能接收文本输入并生成文本输出。它们无法自行调用工具。当我们谈论向代理提供工具时,我们的意思是,我们教会 LLM 了解工具的存在,并要求模型生成文本,以便在需要时调用工具。例如,如果我们提供一个从互联网上查询某个地点天气的工具,然后询问 LLM 巴黎的天气,LLM 将识别出这个问题是使用我们教给它的“天气”工具的相关机会。LLM 将生成文本(以代码的形式)来调用该工具。代理有责任解析 LLM 的输出,识别是否需要工具调用,并代表 LLM 调用该工具。然后,来自工具的输出将被发送回 LLM,LLM 将为其用户撰写最终回复。

来自工具调用的输出是对话中的另一种类型的消息。工具调用步骤通常不会显示给用户:代理检索对话,调用工具,获取输出,将它们添加为新的对话消息,并将更新后的对话再次发送给 LLM。从用户的角度来看,就像 LLM 使用了该工具,但实际上是我们的应用程序代码(代理)完成了它。

核心组件 (The Core Components)

代理以一个持续的循环工作:思考 (Thought) → 行动 (Act) 和观察 (Observe)。

让我们一起分解这些动作:

  1. 思考 (Thought):代理的 LLM 部分决定下一步应该做什么。
  2. 行动 (Action):代理通过使用相关的参数调用工具来采取行动。
  3. 观察 (Observation):模型反思来自工具的响应。

思考-行动-观察循环 (The Thought-Action-Observation Cycle)

这三个组件协同工作,形成一个持续的循环。用编程中的类比来说,代理使用一个 while 循环:循环持续进行,直到代理的目标得到实现。

从视觉上看,它看起来像这样:

来源:HuggingFace

在许多代理框架中,规则和指南直接嵌入到系统提示中,确保每个循环都遵循定义的逻辑。

在一个简化版本中,我们的系统提示可能看起来像这样:

来源:HuggingFace

我们在这里看到,在系统消息中,我们定义了:

  • 代理的行为
  • 我们的代理可以访问的工具,正如我们在上一节中所描述的。
  • 思考-行动-观察循环,我们将其嵌入到 LLM 指令中。

让我们以一个小例子来理解这个过程,然后再深入研究过程的每个步骤。

Congo,天气代理

我们创建了 Congo,天气代理。

用户向 Congo 提问:“今天印度的天气怎么样?”

Congo 的工作是使用天气 API 工具来回答这个问题。

循环的展开方式如下:

思考

内部推理:

收到查询后,Congo 的内部对话可能是:

“用户需要印度的当前天气信息。 我可以使用一个获取天气数据的工具。 首先,我需要调用天气 API 来获取最新的详细信息。”

此步骤显示代理将问题分解为几个步骤:首先,收集必要的数据。

行动

工具使用:

根据其推理以及 Congo 知道 get_weather 工具的事实,Congo 准备了一个 JSON 格式的命令,该命令调用天气 API 工具。 例如,它的第一个操作可能是:

思考:我需要检查印度的当前天气。

{
     "action": "get_weather",
     "action_input": {
       "location": "India"
     }
   }

在这里,操作清楚地指定了要调用的工具(例如,get_weather)以及要传递的参数(“location”:“India”)。

观察

来自环境的反馈:

在工具调用之后,Congo 收到一个观察结果。 这可能是来自 API 的原始天气数据,例如:

“印度的当前天气:部分多云,35°C,25% 湿度。”

然后将此观察结果作为额外的上下文添加到提示中。 它的作用是现实世界的反馈,确认操作是否成功并提供所需的详细信息。

更新后的思考

反思:

有了观察结果,Congo 会更新其内部推理:

“现在我有了印度的天气数据,我可以为用户编写一个答案。”

最终行动

然后,Congo 生成一个最终响应,其格式与我们告诉它的一样:

思考:我现在有了天气数据。 纽约的当前天气是部分多云,温度为 15°C,湿度为 60%。

最终答案:纽约的当前天气是部分多云,温度为 15°C,湿度为 60%。

此最终操作将答案发送回用户,从而结束循环。

什么是 Hugging Face 的 Smolagents?

一个非常简单的库,可为语言模型解锁代理功能。

“代码代理,即以代码形式编写其操作的代理(而不是“用于编写代码的代理”)。 为了确保安全,我们支持通过 E2B 在沙盒环境中执行。”

代码代理如何工作?

构建代理

要构建代理,您至少需要两个元素:

  • tools:代理可以访问的工具列表
  • model:将成为您的代理引擎的 LLM。

首先安装软件包。

pip install smolagents==1.2.0

场景 1:我想用自然语言查询我的模型亚马逊“sales_data”,为了简单起见,我选取了一些记录

使用了简单的代码代理,sql_engine 作为工具

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
### Amazon 产品评论数据

```json
[
  {
    "product_id": "B0B7L86YCB",
    "product_name": "Green Tales Sealer Impulse Machine for Plastic Pouch, Normal thin polybag,Good. Works",
    "category": "Home\u0026Kitchen|Kitchen\u0026HomeAppliances|SmallKitchenAppliances|FoodSavers",
    "discounted_price": "299.0",
    "actual_price": "999.0",
    "discount_percentage": "0.7",
    "rating": "2.5",
    "rating_count": "60",
    "about_product": "Sealing Machine for Plastic Pouch|Easy to use|Portable|Good Quality",
    "user_id": "A33V806595Y197N0S971,A1J5W81C5A1787W31969,A19W96767N1819699398,A2Y17U7QW3389818441,A3730898721627714216,A1XQ44S7L7X969345893,A196Y14G66S093010405,A13K3765673834245975,A1090317196454667000,A1653396479341967893",
    "user_name": "Nitin,Sayan,Ankit,Priyanka,Ravi,sandeep,Kavita,Suraj,Suman,Anil",
    "review_id": "R22Q065I9W3347,R1C291342992I3,R10H563104U00C,R1690018704582,R1745006008Q2L,R276991930240E,R3181778191324,R1636592018734,R1845754668949,R763081376790",
    "review_title": "Not working,Not good,Good product,Good,Not working,Good product,Good product,Good product,Good product,Good",
    "review_content": "It is broken and it is not useful. Please change this product,product is so so... the plastic quality is not so good as per the price.it claims that it can be stuck in the metallic areas like fridge but the magnet is not working.,The first one was not working and the replacement was sent without box with a used piece. The battery had water while I received it and even the delivery person was shocked,This is marvellous product to use . Such a small product but does wonders . And that too given 2 batteries,Great product and lovely packaging,I don\u0027t like it the product it not working,Not satisfied,",
    "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": "Portable \u0026 Convenient to Charge: This little body light weight design is easy for you carry it to school, office, parks, camping, anywhere you want to. and it also convenient for charge by power bank, laptop, computer, car or other usb devices.|Easy and Safe Cleaning - It has have smart safety protection device, magnetic sensing switch ultra safe to use and clean, the juicer cup\u0027s body and bottom can be separated, you can easy to clean it|Multi-function - With our juice blender mixing kinds of fruit and vegetables, you can make natural tasty juice, milkshake, smoothie and other baby food. It\u0027s very portable and great for traveling, outdoor.|Enjoy your fruit juice anytime and anywhere.|6 stainless steel blades, sharp and durable, can last for long time.",
    "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 the whole place mess and the juicer doesn\u0027t grind properly where the pieces of fruits remain ungrinded. I generally dont write reviews but i was forced to write this one as this is just waste of moneySpend it wisely for something better,It\u0027s does not work properly at all, after charging for 4 hours the battery last only 30 - 45 sec. Very bad product.And they have given a cashback coupon to attract good rating.Misleading information is given on the detail page.,I bought this mostly for milk

```markdown
### SHREENOVA Bluetooth Fitness Tracker

![](https://m.media-amazon.com/images/I/41lnTFZGz9L._SX300_SY300_QL70_ML2_.jpg)

*   **product_id**: B0BBVKRP7B
*   **product_name**: SHREENOVA Bluetooth Fitness Tracker
*   **category**: Electronics|WearableTechnology|Smartwatches
*   **discounted_price**: 499.0
*   **actual_price**: 1499.0
*   **discount_percentage**: 0.67
*   **rating**: 1.0
*   **rating_count**: 1
*   **about_product**: "Heart Rate Monitor: 24 hours continuous heart rate monitoring, automatically tracks your sleep duration & consistency with comprehensive analysis of sleep quality data; Call & Message Notification: Receive call, SMS and SNS notifications on display, including Facebook, Twitter, WhatsApp, Linkedin, Messenger, etc. when connected to the app. You can also reject calls directly from the watch.|Activity Tracking: Accurately record all-day activities like steps, distance, calories burned, activity minutes and sleep status. Connect the fitness tracker with your phone via Bluetooth, you can see the running route in the app.|Compatibility: The fitness tracker is compatible with smartphones that use iOS 8.0 / Android 4.4 or above, and Bluetooth 4.0 or above.|Long Battery Life & Waterproof: Low power consumption, long standby time. The fitness tracker is fully charged in about 2 hours, and can be used for 5-7 days. IP67 waterproof, you can wear it when washing hands and in the rain. (Note: It is not recommended to use in water above 37 degrees, such as showers and saunas.)|More Features: Sedentary reminder, remote camera control, music control, alarm clock, stopwatch, find phone, etc. The fitness tracker is a great gift for your family and friends."
*   **user_id**: A2X6J05113J50L7N2XQ727G462YQ
*   **user_name**: "Nitin"
*   **review_id**: R1J03Y7W9Y09O1
*   **review_title**: "Worst product"
*   **review_content**: "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

### IONIX Tap filter Multilayer | Activated Carbon Faucet Water Filters Universal Interface Home Kitchen Faucet Tap Water Clean Purifier Filter Cartridge Five Layer Water Filter-Pack of 1

![](https://m.media-amazon.com/images/I/41n90w1dlJL._SY445_SX342_QL70_FMwebp_.jpg)

*   **product_id**: B0BBLHTRM9
*   **product_name**: IONIX Tap filter Multilayer | Activated Carbon Faucet Water Filters Universal Interface Home Kitchen Faucet Tap Water Clean Purifier Filter Cartridge Five Layer Water Filter-Pack of 1
*   **category**: Home\u0026Kitchen|Kitchen\u0026HomeAppliances|WaterPurifiers\u0026Accessories|WaterPurifierAccessories
*   **discounted_price**: 199.0
*   **actual_price**: 699.0
*   **discount_percentage**: 0.72
*   **rating**: 2.9
*   **rating_count**: 159
*   **about_product**: "Faucet Water Filter: Built-in layered filter can separate coconut activated carbon, zeolite, PVA non-woven?fabrics, calcium sulfite and rubber, which applys to purify hard water and well water.|Healthy Lifestyle: Remove the water in the chlorine, heavy metals, other impurities,water more sweet, more secure.|Easy to Clean : A must item for home \u0026 office use,100% new and high quality.High temperature resistance, not easy to deform.To clean, simply remove the strainer and rinse it off under the water.|Water-saving :Made of soft rubber material can prevent water leak which can save water for your each time using.; Package List:1 * Faucet Filter|Included Components: 1 X Five Layer Faucet"
*   **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). After I installed this filter - it showed the result of 424. Disappointing. You need it less than 100 to be sure to drink it.,Easy to install \u0026 Value for money,I used it for a school project and it worked super well!,Old product received. Inside seems as rusted"
*   **img_link**: ![](https://m.media-amazon.com/images/I/41n90w1dlJL._SY445_SX342_QL70_FMwebp_.jpg)
*   **product_link**: https://www.amazon.in/IONIX-Tap-Multilayer-Filter-Filter-Pack/dp/B0BBLHTRM9/ref\u003dsr_1_488?qid\u003d1672923617\u0026s\u003dkitchen\u0026sr\u003d1-488

### Nirdambhay Mini Bag Sealer, 2 in 1 Heat Sealer and Cutter Handheld Sealing Machine Portable Bag Res

```json
[
  {
    "product_id": "B08YK7BBD2",
    "product_name": "Nirdambhay 手持便携式迷你热封口机,塑料袋封口机,用于食品储存、零食保鲜、包装和封口机(多色)",
    "category": "家居与厨房|厨房与用餐|厨房用具和小工具|食品储物容器|食品储物袋",
    "discounted_price": "249.0",
    "actual_price": "499.0",
    "discount_percentage": "0.5",
    "rating": "3.0",
    "rating_count": "27",
    "about_product": "迷你热封口机:迷你袋封口机由 ABS 材料制成,耐高温和低温。无毒、无味、耐用且安全。可用于封口塑料袋、零食袋、食品储物袋等。是您厨房和旅行的好帮手。易于使用:迷你热封口机易于使用,只需按住开关 3-5 秒即可加热袋子,然后将要封口的袋子放在中间,并沿任何要封口的袋子的边缘慢慢滑动。便携轻便:迷你热封口机小巧便携,您可以轻松地将其放入您的口袋或包中,非常适合旅行和露营。广泛应用:迷你热封口机适用于封口各种塑料袋,如零食袋、食品储物袋等。它可以有效地防止食物受潮并保持新鲜。电池供电:迷你热封口机由 2 AA 电池供电(不含),使用非常方便。",
    "user_id": "A2693687S360O,A11S338U129949,A2994B34956I9J,A185N0XW09L3S7,A1361Q41E69Y1K,A1329I23N592V7,A3281996X92E1X,A1W98698959D4V",
    "user_name": "Ankita ,Sanjukta ,Anurag ,Sathish,Tanya,Priya,Nayana,sri",
    "review_id": "R1355V2W9G0H0P,R2K6176U3L962R,R2N465325343L7,R2794XG9Q94J6C,R13C47C3493G5Y,R1J520168570O,R14Q74V9C0F84B,R25430391Q8E6S",
    "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": "亚马逊品牌 - Solimo 65W 快速充电编织 Type C 到"
```python
from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime, Boolean, insert
from sqlalchemy.orm import sessionmaker
from sqlalchemy import inspect
import json
## Database connection details
db_url = "sqlite:///sales_data.db"  # Use SQLite for simplicity
## Create an SQLite engine
engine = create_engine(db_url)
## Define the sales_data table
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class sales_data(Base):
    __tablename__ = 'sales_data'
    id = Column(Integer, primary_key=True, autoincrement=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)
## Create the table in the database
Base.metadata.create_all(engine)
## Load data from JSON
data = """
[
  {
    "product_name": "Tokdis MX-1 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't updates automatically,It's 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's 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't get update automatically with time n day . Today is 12 dec Monday n it's 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/31M4nb0+JKL._SY300_SX300_.jpg",
    "product_link": "https://www.amazon.in/Tokdis-MX-1-Bluetooth-Calling-Smartwatch/dp/B0B82YGCF6/ref=sr_1_370?qid=1672895857&s=electronics&sr=1-370"
  }
]
"""
rows = json.loads(data)
## Insert data into the database
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)

SQL Agent with OpenAIServerModel

我们创建了一个 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 = # 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
        )

使用工具和导入定义代理

agent = CodeAgent(
   tools=[DuckDuckGoSearchTool()],
   additional_authorized_imports=["yfinance"],
   model=model
)

运行代理以获取 Apple Inc. 的股票价格

response = agent.run(
   "is if Microsoft Inc (NASDAQ: AAPL). Use the YFinance Library."
)

输出响应

print(response)

当我的查询是“获取 Microsoft Inc (NASDAQ: AAPL) 的股票价格。使用 YFinance 库。”时,代理处理了 NLP 查询并生成了输出

search_query = "current stock price of Microsoft (MSFT) in USD"
  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, Quote & News - Yahoo ...](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

场景 3:使用提示生成照片

使用了代码代理和 image_generation_tool ,我们从 HuggingFace Spaces 导入了一个工具,并用它来生成图像。简单而强大。

from smolagents import CodeAgent,OpenAIServerModel, Tool
api_key = # Replace with your secret name
### 指定模型,它将利用我们刚刚获得的 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'"
)

输出:

通过这个,您了解了如何使用 Hugging Face 的 SmolAgents 通过示例创建 AI 代理

要深入了解该框架,请查看官方 https://github.com/huggingface/smolagents

理解 JavaScript 中的 this 关键字

在 JavaScript 中,this 关键字是一个非常重要的概念,但同时也是一个容易让人困惑的地方。本文将深入探讨 this 关键字的含义、用法以及它在不同情况下的指向。

1. 什么是 this

this 关键字指的是函数运行时所处的上下文。换句话说,this 的值取决于函数是如何被调用的。它不是一个静态的、预先确定的值,而是在运行时动态确定的。

2. this 的指向规则

this 的指向主要取决于函数被调用的方式。以下是几种常见的情况:

2.1. 全局上下文

在浏览器环境中,当 this 在全局作用域中被使用时,它指向 window 对象。在 Node.js 环境中,它指向 global 对象。

console.log(this); // 在浏览器中,输出 window 对象

2.2. 函数调用

当函数直接被调用时,this 的值取决于是否在严格模式下。

  • 非严格模式: this 指向全局对象 (浏览器中的 window 或 Node.js 中的 global)。
  • 严格模式: this 的值为 undefined
function myFunction() {
  console.log(this);
}

myFunction(); // 非严格模式下,输出 window 或 global;严格模式下,输出 undefined

2.3. 方法调用

当函数作为对象的方法被调用时,this 指向调用该方法的对象。

const myObject = {
  name: "Example",
  myMethod: function() {
    console.log(this.name);
  }
};

myObject.myMethod(); // 输出 "Example"

2.4. 构造函数调用

当函数作为构造函数使用 new 关键字调用时,this 指向新创建的实例对象。

function Person(name) {
  this.name = name;
  console.log(this);
}

const person1 = new Person("Alice"); // this 指向 person1 对象
const person2 = new Person("Bob");   // this 指向 person2 对象

2.5. callapplybind 方法

JavaScript 提供了 callapplybind 这三个方法,可以显式地设置 this 的值。

  • call()apply() 它们允许你调用一个函数,并指定 this 的值。call() 接受参数列表,而 apply() 接受参数数组。

    function greet(greeting) {
      console.log(greeting + ", " + this.name);
    }
    
    const person = { name: "Alice" };
    
    greet.call(person, "Hello");   // 输出 "Hello, Alice"
    greet.apply(person, ["Hi"]);    // 输出 "Hi, Alice"
    
  • bind() 它创建一个新的函数,并将原始函数的 this 值绑定到指定的对象。

    function greet() {
      console.log("Hello, " + this.name);
    }
    
    const person = { name: "Bob" };
    const greetBob = greet.bind(person);
    
    greetBob(); // 输出 "Hello, Bob"
    

3. 箭头函数中的 this

箭头函数没有自己的 this 值。它们会从定义时所在的作用域继承 this 值。这意味着,箭头函数中的 this 始终指向定义它的上下文,而不是调用它的上下文。

const myObject = {
  name: "Example",
  myMethod: function() {
    const arrowFunction = () => {
      console.log(this.name); // 继承自 myMethod 的 this
    };
    arrowFunction();
  }
};

myObject.myMethod(); // 输出 "Example"

4. 总结

this 关键字在 JavaScript 中扮演着重要的角色。理解 this 的指向规则,对于编写高质量的 JavaScript 代码至关重要。记住以下几点:

  • this 的值取决于函数被调用的方式。
  • 全局上下文中的 this 指向 window (浏览器) 或 global (Node.js)。
  • 方法调用中,this 指向调用该方法的对象。
  • 构造函数调用中,this 指向新创建的实例对象。
  • callapplybind 可以显式地设置 this 的值。
  • 箭头函数没有自己的 this,它继承自父作用域。

掌握这些规则,可以帮助你更好地理解和使用 JavaScript 中的 this 关键字。

Related Posts

结合chatgpt-o3-mini与perplexity Deep Research的3步提示:提升论文写作质量的终极指南

结合chatgpt-o3-mini与perplexity Deep Research的3步提示:提升论文写作质量的终极指南

AI 研究报告和论文写作 合并两个系统指令以获得两个模型的最佳效果 Perplexity AI 的 Deep Research 工具提供专家级的研究报告,而 OpenAI 的 ChatGPT-o3-mini-high 擅长推理。我发现你可以将它们结合起来生成令人难以置信的论文,这些论文比任何一个模型单独撰写的都要好。你只需要将这个一次性提示复制到 **

阅读更多
让 Excel 过时的 10 种 Ai 工具:实现数据分析自动化,节省手工作业时间

让 Excel 过时的 10 种 Ai 工具:实现数据分析自动化,节省手工作业时间

Non members click here作为一名软件开发人员,多年来的一个发现总是让我感到惊讶,那就是人们还在 Excel

阅读更多
使用 ChatGPT 搜索网络功能的 10 种创意方法

使用 ChatGPT 搜索网络功能的 10 种创意方法

例如,提示和输出 你知道可以使用 ChatGPT 的“搜索网络”功能来完成许多任务,而不仅仅是基本的网络搜索吗? 对于那些不知道的人,ChatGPT 新的“搜索网络”功能提供实时信息。 截至撰写此帖时,该功能仅对使用 ChatGPT 4o 和 4o-mini 的付费会员开放。 ![](https://images.weserv.nl/?url=https://cdn-im

阅读更多
掌握Ai代理:解密Google革命性白皮书的10个关键问题解答

掌握Ai代理:解密Google革命性白皮书的10个关键问题解答

10 个常见问题解答 本文是我推出的一个名为“10 个常见问题解答”的新系列的一部分。在本系列中,我旨在通过回答关于该主题的十个最常见问题来分解复杂的概念。我的目标是使用简单的语言和相关的类比,使这些想法易于理解。 图片来自 [Solen Feyissa](https://unsplash.com/@solenfeyissa?utm_source=medium&utm_medi

阅读更多
在人工智能和技术领域保持领先地位的 10 项必学技能 📚

在人工智能和技术领域保持领先地位的 10 项必学技能 📚

在人工智能和科技这样一个动态的行业中,保持领先意味着不断提升你的技能。无论你是希望深入了解人工智能模型性能、掌握数据分析,还是希望通过人工智能转变传统领域如法律,这些课程都是你成功的捷径。以下是一个精心策划的高价值课程列表,可以助力你的职业发展,并让你始终处于创新的前沿。 1. 生成性人工智能简介课程: [生成性人工智能简介](https://genai.works

阅读更多
揭开真相!深度探悉DeepSeek AI的十大误区,您被误导了吗?

揭开真相!深度探悉DeepSeek AI的十大误区,您被误导了吗?

在AI军备竞赛中分辨事实与虚构 DeepSeek AI真的是它所宣传的游戏规则改变者,还是仅仅聪明的营销和战略炒作?👀 虽然一些人将其视为AI效率的革命性飞跃,但另一些人则认为它的成功建立在借用(甚至窃取的)创新和可疑的做法之上。传言称,DeepSeek的首席执行官在疫情期间像囤积卫生纸一样囤积Nvidia芯片——这只是冰山一角。 从其声称的550万美元培训预算到使用Open

阅读更多
Type something to search...