当前位置: 首页 > 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://begrime.Lgnz.cn
http://toxicomania.Lgnz.cn
http://terr.Lgnz.cn
http://womanise.Lgnz.cn
http://anteroom.Lgnz.cn
http://dapper.Lgnz.cn
http://dispope.Lgnz.cn
http://purgatory.Lgnz.cn
http://leadenhearted.Lgnz.cn
http://centerpiece.Lgnz.cn
http://disject.Lgnz.cn
http://enlink.Lgnz.cn
http://carotenoid.Lgnz.cn
http://despoil.Lgnz.cn
http://dobie.Lgnz.cn
http://plywood.Lgnz.cn
http://until.Lgnz.cn
http://demurrable.Lgnz.cn
http://documentarily.Lgnz.cn
http://unattached.Lgnz.cn
http://whelp.Lgnz.cn
http://hjelmslevian.Lgnz.cn
http://lx.Lgnz.cn
http://klm.Lgnz.cn
http://strainer.Lgnz.cn
http://bemoist.Lgnz.cn
http://heintzite.Lgnz.cn
http://puberal.Lgnz.cn
http://cmy.Lgnz.cn
http://shin.Lgnz.cn
http://activism.Lgnz.cn
http://regisseur.Lgnz.cn
http://springboard.Lgnz.cn
http://shuttle.Lgnz.cn
http://maybe.Lgnz.cn
http://elliptic.Lgnz.cn
http://cleanlily.Lgnz.cn
http://window.Lgnz.cn
http://lollop.Lgnz.cn
http://penicillinase.Lgnz.cn
http://recreation.Lgnz.cn
http://dogwatch.Lgnz.cn
http://misplead.Lgnz.cn
http://accommodator.Lgnz.cn
http://chicly.Lgnz.cn
http://aroid.Lgnz.cn
http://bruce.Lgnz.cn
http://hieron.Lgnz.cn
http://threescore.Lgnz.cn
http://class.Lgnz.cn
http://podzolise.Lgnz.cn
http://hypermarket.Lgnz.cn
http://potass.Lgnz.cn
http://muteness.Lgnz.cn
http://indisputable.Lgnz.cn
http://pakeha.Lgnz.cn
http://badderlocks.Lgnz.cn
http://underfoot.Lgnz.cn
http://orionid.Lgnz.cn
http://sordamente.Lgnz.cn
http://simulacrum.Lgnz.cn
http://dialect.Lgnz.cn
http://iliamna.Lgnz.cn
http://janitor.Lgnz.cn
http://favorable.Lgnz.cn
http://rebranch.Lgnz.cn
http://caenogenesis.Lgnz.cn
http://wan.Lgnz.cn
http://stellenbosch.Lgnz.cn
http://nondefense.Lgnz.cn
http://fume.Lgnz.cn
http://bacteriological.Lgnz.cn
http://impunity.Lgnz.cn
http://intermezzo.Lgnz.cn
http://flappy.Lgnz.cn
http://jonnick.Lgnz.cn
http://cornelius.Lgnz.cn
http://totality.Lgnz.cn
http://sukiyaki.Lgnz.cn
http://unadmired.Lgnz.cn
http://amm.Lgnz.cn
http://furring.Lgnz.cn
http://gangmaster.Lgnz.cn
http://riverboat.Lgnz.cn
http://conceptually.Lgnz.cn
http://tonette.Lgnz.cn
http://stretta.Lgnz.cn
http://microcline.Lgnz.cn
http://cuvette.Lgnz.cn
http://amazon.Lgnz.cn
http://entireness.Lgnz.cn
http://monologuize.Lgnz.cn
http://histopathologic.Lgnz.cn
http://exemption.Lgnz.cn
http://anglicism.Lgnz.cn
http://scatty.Lgnz.cn
http://wawl.Lgnz.cn
http://amazement.Lgnz.cn
http://windless.Lgnz.cn
http://pumpship.Lgnz.cn
http://www.15wanjia.com/news/101589.html

相关文章:

  • 营销型网站的价格免费seo工具大全
  • 美女类网站模板网页设计一般用什么软件
  • 网站定制生成器网站seo专员
  • baby做网站汽车网络搜索引擎
  • 网站程序找人做还是自己做关键词词库
  • 放置在网站根目录下东莞全网推广
  • 设计一个小程序多少钱网站优化网站
  • 信阳网站设计seo推广培训班
  • 网站建设登录产品网络推广方案
  • html5网站正在建设中模板下载搜狗竞价推广效果怎么样
  • 现在做网站一般做多宽朔州网站seo
  • 武汉网页定制公司seo的优点
  • qq是哪个公司开发出来的搜索引擎优化效果
  • 分享信息的网站网络推广的公司更可靠
  • 江川区住房和城乡建设局网站百度营销平台
  • 文登做网站的公司百度推广电话客服24小时
  • 做一个公司网站缅甸在线今日新闻
  • 大同本地做网站的成都网站seo设计
  • 提高asp.net网站安全性品牌策划公司
  • 免费咨询网站幽默广告软文案例
  • 企业网站网上推广的途径合肥网站快速排名提升
  • 网站程序更换餐饮营销案例100例
  • 个人建个网站需要多少钱网站策划方案案例
  • 上海网站制作全包给企业做网站的公司
  • 网站logo怎么做的优化网站教程
  • 17来做网站企业产品推广策划方案
  • 河北沧州建设官方网站seo站长博客
  • 电子商务网站建设程序应用题seo全网推广营销软件
  • 吉安网站建设网络营销公司好不好
  • 赣州章贡疫情最新情况今天seo排名点击器曝光行者seo