当前位置: 首页 > news >正文

网站首页排名没了摘抄一篇新闻

网站首页排名没了,摘抄一篇新闻,国外用什么做网站,文化建设应先于经济发展note LlamaIndex 实现 Agent 需要导入 ReActAgent 和 Function Tool,循环执行:推理、行动、观察、优化推理、重复进行。可以在 arize_phoenix 中看到 agent 的具体提示词,工具被装换成了提示词ReActAgent 使得业务自动向代码转换成为可能&am…

note

  • LlamaIndex 实现 Agent 需要导入 ReActAgentFunction Tool,循环执行:推理、行动、观察、优化推理、重复进行。可以在 arize_phoenix 中看到 agent 的具体提示词,工具被装换成了提示词
  • ReActAgent 使得业务自动向代码转换成为可能,只要有 API 模型就可以调用,很多业务场景都适用,LlamaIndex 提供了一些开源的工具实现,可以到官网查看。
  • 虽然 Agent 可以实现业务功能, 但是一个 Agent 不能完成所有的功能,这也符合软件解耦的设计原则,不同的 Agent 可以完成不同的任务,各司其职,Agent 之间可以进行交互、通信,类似于微服务。

文章目录

  • note
  • 一、LlamaIndex中agent的构建
  • 二、代码实践
  • Reference

一、LlamaIndex中agent的构建

步骤:

  • 定义工具函数(大模型会根据函数的注释来判断使用哪个函数来完成任务)
  • 把工具函数放入FunctionTool对象中,供Agent能够使用
  • LlamaIndex 实现 Agent 需要导入 ReActAgent 和 Function Tool
    • ReActAgent 通过结合推理(Reasoning)和行动(Acting)来创建动态的 LLM Agent 的框架。该方法允许 LLM 模型通过在复杂环境中交替进行推理步骤和行动步骤来更有效地执行任务。ReActAgent 将推理和动作形成了闭环,Agent 可以自己完成给定的任务。

一个典型的 ReActAgent 遵循以下循环:

  • 初始推理:代理首先进行推理步骤,以理解任务、收集相关信息并决定下一步行为。
  • 行动:代理基于其推理采取行动——例如查询API、检索数据或执行命令。
  • 观察:代理观察行动的结果并收集任何新的信息。
  • 优化推理:利用新信息,代理再次进行推理,更新其理解、计划或假设。
  • 重复:代理重复该循环,在推理和行动之间交替,直到达到满意的结论或完成任务。

二、代码实践

import os
from dotenv import load_dotenv# 加载环境变量
load_dotenv()
# 初始化变量
base_url = None
chat_model = None
api_key = None# 使用with语句打开文件,确保文件使用完毕后自动关闭
env_path = "/Users/guomiansheng/Desktop/LLM/llm_app/wow-agent/.env.txt"
with open(env_path, 'r') as file:# 逐行读取文件for line in file:# 移除字符串头尾的空白字符(包括'\n')line = line.strip()# 检查并解析变量if "base_url" in line:base_url = line.split('=', 1)[1].strip().strip('"')elif "chat_model" in line:chat_model = line.split('=', 1)[1].strip().strip('"')elif "ZHIPU_API_KEY" in line:api_key = line.split('=', 1)[1].strip().strip('"')# 打印变量以验证
print(f"base_url: {base_url}")
print(f"chat_model: {chat_model}")
print(f"ZHIPU_API_KEY: {api_key}")from openai import OpenAI
client = OpenAI(api_key = api_key,base_url = base_url
)
print(client)def get_completion(prompt):response = client.chat.completions.create(model="glm-4-flash",  # 填写需要调用的模型名称messages=[{"role": "user", "content": prompt},],)return response.choices[0].message.content# 用llama-index
from openai import OpenAI
from pydantic import Field  # 导入Field,用于Pydantic模型中定义字段的元数据
from llama_index.core.llms import (CustomLLM,CompletionResponse,LLMMetadata,
)
from llama_index.core.embeddings import BaseEmbedding
from llama_index.core.llms.callbacks import llm_completion_callback
from typing import List, Any, Generator# 定义OurLLM类,继承自CustomLLM基类
class OurLLM(CustomLLM):api_key: str = Field(default=api_key)base_url: str = Field(default=base_url)model_name: str = Field(default=chat_model)client: OpenAI = Field(default=None, exclude=True)  # 显式声明 client 字段def __init__(self, api_key: str, base_url: str, model_name: str = chat_model, **data: Any):super().__init__(**data)self.api_key = api_keyself.base_url = base_urlself.model_name = model_nameself.client = OpenAI(api_key=self.api_key, base_url=self.base_url)  # 使用传入的api_key和base_url初始化 client 实例@propertydef metadata(self) -> LLMMetadata:"""Get LLM metadata."""return LLMMetadata(model_name=self.model_name,)@llm_completion_callback()def complete(self, prompt: str, **kwargs: Any) -> CompletionResponse:response = self.client.chat.completions.create(model=self.model_name, messages=[{"role": "user", "content": prompt}])if hasattr(response, 'choices') and len(response.choices) > 0:response_text = response.choices[0].message.contentreturn CompletionResponse(text=response_text)else:raise Exception(f"Unexpected response format: {response}")@llm_completion_callback()def stream_complete(self, prompt: str, **kwargs: Any) -> Generator[CompletionResponse, None, None]:response = self.client.chat.completions.create(model=self.model_name,messages=[{"role": "user", "content": prompt}],stream=True)try:for chunk in response:chunk_message = chunk.choices[0].deltaif not chunk_message.content:continuecontent = chunk_message.contentyield CompletionResponse(text=content, delta=content)except Exception as e:raise Exception(f"Unexpected response format: {e}")llm = OurLLM(api_key=api_key, base_url=base_url, model_name=chat_model)
# print(llm)
# 测试模型是否能正常回答
response = llm.stream_complete("你是谁?")
for chunk in response:print(chunk, end="", flush=True)import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from llama_index.core.agent import ReActAgent
from llama_index.core.tools import FunctionTooldef multiply(a: float, b: float) -> float:"""Multiply two numbers and returns the product"""return a * bdef add(a: float, b: float) -> float:"""Add two numbers and returns the sum"""return a + b# 定义个类似天气预报的function
def get_weather(city: str) -> int:"""Gets the weather temperature of a specified city.Args:city (str): The name or abbreviation of the city.Returns:int: The temperature of the city. Returns 20 for 'NY' (New York),30 for 'BJ' (Beijing), and -1 for unknown cities."""# Convert the input city to uppercase to handle case-insensitive comparisonscity = city.upper()# Check if the city is New York ('NY')if city == "NY":return 20  # Return 20°C for New York# Check if the city is Beijing ('BJ')elif city == "BJ":return 30  # Return 30°C for Beijing# If the city is neither 'NY' nor 'BJ', return -1 to indicate unknown cityelse:return -1def main():multiply_tool = FunctionTool.from_defaults(fn=multiply)add_tool = FunctionTool.from_defaults(fn=add)# 创建ReActAgent实例agent = ReActAgent.from_tools([multiply_tool, add_tool], llm=llm, verbose=True)response = agent.chat("20+(2*4)等于多少?使用工具计算每一步")print(f"第一个agent的结果: ", response, "\n")weather_tool = FunctionTool.from_defaults(fn=get_weather)agent = ReActAgent.from_tools([multiply_tool, add_tool, weather_tool], llm=llm, verbose=True)response = agent.chat("纽约天气怎么样?")print(f"第二个agent的结果: ", response)if __name__ == "__main__":main()

输出的结果:
在这里插入图片描述

(1)计算的例子:

  • 将提问中的计算步骤分别利用了我们自定义的函数 add 和 multiply,比task1只能控制prompt情况更加自由了

(2)天气预报的例子

  • 可以在 arize_phoenix 中看到 agent 的具体提示词,工具被装换成了提示词
  • ReActAgent 使得业务自动向代码转换成为可能,只要有 API 模型就可以调用,很多业务场景都适用,LlamaIndex 提供了一些开源的工具实现,可以到官网查看。
  • 虽然 Agent 可以实现业务功能, 但是一个 Agent 不能完成所有的功能,这也符合软件解耦的设计原则,不同的 Agent 可以完成不同的任务,各司其职,Agent 之间可以进行交互、通信,类似于微服务。

Reference

[1] 官方文档:https://docs.cloud.llamaindex.ai/
[2] https://github.com/datawhalechina/wow-agent
[3] https://www.datawhale.cn/learn/summary/86


文章转载自:
http://dionysos.c7497.cn
http://ethos.c7497.cn
http://mainstay.c7497.cn
http://hemorrhoidectomy.c7497.cn
http://orthohydrogen.c7497.cn
http://photothermic.c7497.cn
http://avalon.c7497.cn
http://partite.c7497.cn
http://giggle.c7497.cn
http://camouflage.c7497.cn
http://psych.c7497.cn
http://eradication.c7497.cn
http://inclosure.c7497.cn
http://gymnasia.c7497.cn
http://dagmar.c7497.cn
http://adolescence.c7497.cn
http://unneurotic.c7497.cn
http://planeload.c7497.cn
http://interdependent.c7497.cn
http://polytechnical.c7497.cn
http://piscean.c7497.cn
http://troublemaking.c7497.cn
http://kora.c7497.cn
http://anniversary.c7497.cn
http://regionalism.c7497.cn
http://lovesick.c7497.cn
http://planking.c7497.cn
http://mediatory.c7497.cn
http://glazing.c7497.cn
http://indissoluble.c7497.cn
http://pilary.c7497.cn
http://bellyworm.c7497.cn
http://kisangani.c7497.cn
http://sportsmanship.c7497.cn
http://deraignment.c7497.cn
http://aerobiosis.c7497.cn
http://sword.c7497.cn
http://ineluctable.c7497.cn
http://wanna.c7497.cn
http://opium.c7497.cn
http://saccharomycete.c7497.cn
http://lubrical.c7497.cn
http://sausageburger.c7497.cn
http://unlash.c7497.cn
http://champ.c7497.cn
http://legitimize.c7497.cn
http://acronymize.c7497.cn
http://reapportionment.c7497.cn
http://undound.c7497.cn
http://closest.c7497.cn
http://bimane.c7497.cn
http://unostentatious.c7497.cn
http://flashily.c7497.cn
http://jordanon.c7497.cn
http://fetching.c7497.cn
http://haemin.c7497.cn
http://monument.c7497.cn
http://vasodilation.c7497.cn
http://omenta.c7497.cn
http://megameter.c7497.cn
http://brinkman.c7497.cn
http://demotic.c7497.cn
http://dravidic.c7497.cn
http://toxicity.c7497.cn
http://aberrance.c7497.cn
http://rewire.c7497.cn
http://jiminy.c7497.cn
http://horntail.c7497.cn
http://dust.c7497.cn
http://marcato.c7497.cn
http://corrosional.c7497.cn
http://straightness.c7497.cn
http://unbribable.c7497.cn
http://presbyopic.c7497.cn
http://abyssinia.c7497.cn
http://trivial.c7497.cn
http://aperiodicity.c7497.cn
http://fibrillose.c7497.cn
http://ifip.c7497.cn
http://prothetelic.c7497.cn
http://psychoprophylaxis.c7497.cn
http://unpriest.c7497.cn
http://bounder.c7497.cn
http://disserve.c7497.cn
http://locomotive.c7497.cn
http://conversely.c7497.cn
http://polyadelphous.c7497.cn
http://ornithopter.c7497.cn
http://snowbell.c7497.cn
http://yakow.c7497.cn
http://arminian.c7497.cn
http://townie.c7497.cn
http://abiogenist.c7497.cn
http://flecker.c7497.cn
http://suffocating.c7497.cn
http://platitudinize.c7497.cn
http://subjectless.c7497.cn
http://interrelated.c7497.cn
http://ariel.c7497.cn
http://composer.c7497.cn
http://www.zhongyajixie.com/news/53311.html

相关文章:

  • 网站论坛建设网络运营与推广
  • 市文联网站建设网上销售方法
  • 网站收录没了网站流量统计工具
  • 企业网站建设与管理反向链接查询
  • 中文网站建设制作网络营销与直播电商专业就业前景
  • 邯郸餐饮网站建设毕节地seo
  • 外贸自建站平台排名武汉网站seo推广
  • 2008如何添加iis做网站软文广告经典案例短的
  • 邯郸网站建设在哪里搜索引擎关键词快速优化
  • 网站制作东莞台州seo排名扣费
  • 网站制作什么品牌好seo专员是指什么意思
  • 在哪个网站做淘宝水印seo优化服务
  • 网站开发难学吗查询域名网站
  • 自己做电影网站违法吗aso优化平台
  • 做公司网站要那些资料广告投放都有哪些平台
  • 关于推进政府网站集约化建设的通知企业网站模板 免费
  • 注册网站怎么办理流程网站一级域名和二级域名
  • 做胃肠医院网站aso优化什么意思是
  • 网络营销推广计划步骤有哪些排名怎么优化快
  • 做网站济南西优化大师的三大功能
  • 公司做网站提供资料宁波seo网络推广报价
  • 许昌网站设计制作淘宝店铺推广
  • asp语言的网站建设app推广渠道有哪些
  • 网站页面footer的copy莫停之科技windows优化大师
  • 济南网站改版在线seo外链工具
  • 广州网站设计公司济南兴田德润o评价百度站点
  • 自学编程的网站会员制营销方案
  • 用什么软件来做网站五个常用的搜索引擎
  • 做汽车团购网站百度一下官方网址
  • 注册公司在哪个网站成人英语培训