由 大语言模型(LLMs) 提供支持的 AI 智能体 可帮助组织简化和减少手动工作负载。这些智能体使用多层迭代推理来分析问题、设计解决方案,并使用各种工具执行任务。与传统聊天机器人不同,LLM 提供支持的智能体能够有效理解和处理信息,从而实现复杂任务的自动化。为避免特定应用中的潜在风险,在使用自主 AI 智能体时,保持人工监督仍然至关重要。
在本文中,您将学习如何使用 NVIDIA NIM 微服务 (一种针对 AI 推理优化的加速 API)构建人类在环 AI 智能体。该博文介绍了一个社交媒体用例,展示了这些多功能 AI 智能体如何轻松处理复杂任务。借助 NIM 微服务,您可以将高级 LLM(如 Llama 3.1-70B-Instruct 和 Falcon 180B 等)无缝集成到工作流中,从而提供 AI 驱动任务所需的可扩展性和灵活性。无论您是使用 PyTorch、pandas 和 LangChain 等工具创建宣传内容,还是实现复杂工作流程的自动化,本教程都旨在加速您的流程。
如需观看演示,请观看 如何使用 NVIDIA NIM 在 5 分钟内构建简单的 AI 代理 。
为个性化社交媒体内容构建 AI 智能体
如今,营销人员面临的最大挑战之一是跨平台生成高质量的创意推广内容。我们的目标是创建可在社交媒体上发布的各种促销信息和艺术作品。
传统上,项目负责人会将这些任务分配给内容编写人员和数字艺术家等专家。但是,如果人工智能智能体有助于提高此流程的效率,该怎么办?
此用例涉及两个 AI 智能体——Content Creator 智能体和 Digital Artist 智能体。这些 AI 智能体将生成宣传内容并提交给人类决策者进行最终审批,从而确保人类控制仍然是创意流程的核心。
构建人机决策工作流程
构建这种人在环系统需要创建认知工作流,其中 AI 智能体协助完成特定任务,而人类执行最终决策。图 1 概述了人类决策者与智能体之间的交互。
内容创作者代理使用 Llama 3.1 405B 模型 ,该模型由 NVIDIA LLM NIM 微服务 加速。此外,还集成了 LangChain ChatNVIDIA 与 NIM 函数调用和 结构化输出 ,以确保结果井然有序、可靠。ChatNVIDIA 是 NVIDIA 为 LangChain 提供的开源 Python 库,可让开发者轻松连接 NVIDIA NIM。这些组合功能被整合到 LangChain 可运行链(LCEL) 表达式中,从而创建稳健的智能体工作流。
构建 Content Creator Agent
首先构建 Content Creator Agent。此智能体使用 NVIDIA API Catalog 预览 API 端点,按照特定格式指南生成促销消息。 NVIDIA AI Enterprise 客户还可以在本地下载并运行 NIM 端点。
使用以下 Python 代码开始使用:
from langchain_nvidia_ai_endpoints import ChatNVIDIA
from langchain import prompts, chat_models, hub
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
from langchain_core.pydantic_v1 import BaseModel, Field, validator
from typing import Optional, List
## 1. construct the system prompt ---------
prompt_template = """
### [INST]
You are an expert social media content creator.
Your task is to create a different promotion message with the following
Product Description :
------
{product_desc}
------
The output promotion message MUST use the following format :
'''
Title: a powerful, short message that dipict what this product is about
Message: be creative for the promotion message, but make it short and ready for social media feeds.
Tags: the hash tag human will nomally use in social media
'''
Begin!
[/INST]
"""
prompt = PromptTemplate(
input_variables=['produce_desc'],
template=prompt_template,
)
## 2. provide seeded product_desc text
product_desc="Explore the latest community-built AI models with an API optimized and accelerated by NVIDIA, then deploy anywhere with NVIDIA NIM™ inference microservices."
## 3. structural output using LMFE
class StructureOutput(BaseModel):
Title: str = Field(description="Title of the promotion message")
Message : str = Field(description="The actual promotion message")
Tags: List[str] = Field(description="Hashtags for social media, usually starts with #")
## 4. A powerful LLM
llm_with_output_structure=ChatNVIDIA(model="meta/llama-3.1-405b-instruct").with_structured_output(StructureOutput)
## construct the content_creator agent
content_creator = ( prompt | llm_with_output_structure )
out=content_creator.invoke({"product_desc":product_desc})
使用数字艺术家智能体
接下来,我们介绍 Digital Artist Agent,它使用 NVIDIA sdXL-turbo 文本转图像模型将宣传文本转换为创意视觉效果。此代理重写输入查询并生成专为社交媒体推广活动设计的高质量图像。以下代码提供了代理如何集成的示例:
import requests
import base64, io
from PIL import Image
import requests, json
def generate_image(prompt :str) -> str :
"""
generate image from text
Args:
prompt: input text
"""
## re-writing the input promotion title in to appropriate image_gen prompt
gen_prompt=llm_rewrite_to_image_prompts(prompt)
print("start generating image with llm re-write prompt:", gen_prompt)
invoke_url = "https://ai.api.nvidia.com/v1/genai/stabilityai/sdxl-turbo"
headers = {
"Authorization": f"Bearer {nvapi_key}",
"Accept": "application/json",
}
payload = {
"text_prompts": [{"text": gen_prompt}],
"seed": 0,
"sampler": "K_EULER_ANCESTRAL",
"steps": 2
}
response = requests.post(invoke_url, headers=headers, json=payload)
response.raise_for_status()
response_body = response.json()
## load back to numpy array
print(response_body['artifacts'][0].keys())
imgdata = base64.b64decode(response_body["artifacts"][0]["base64"])
filename = 'output.jpg'
with open(filename, 'wb') as f:
f.write(imgdata)
im = Image.open(filename)
img_location=f"the output of the generated image will be stored in this path : {filename}"
return img_location
使用以下 Python 脚本将用户输入的查询重写为图像生成提示:
from langchain_nvidia_ai_endpoints import ChatNVIDIA
from langchain import prompts, chat_models, hub
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
def llm_rewrite_to_image_prompts(user_query):
prompt = prompts.ChatPromptTemplate.from_messages(
[
(
"system",
"Summarize the following user query into a very short, one-sentence theme for image generation, MUST follow this format : A iconic, futuristic image of , no text, no amputation, no face, bright, vibrant",
),
("user", "{input}"),
]
)
model = ChatNVIDIA(model="mistralai/mixtral-8x7b-instruct-v0.1")
chain = ( prompt | model | StrOutputParser() )
out= chain.invoke({"input":user_query})
#print(type(out))
return out}
接下来,将图像生成与所选 LLM 绑定,并将其包装在 LCEL 中,以创建 Digital Artist Agent:
## bind image generation as tool into llama3.1-405b llm
llm=ChatNVIDIA(model="meta/llama-3.1-405b-instruct")
llm_with_img_gen_tool=llm.bind_tools([generate_image],tool_choice="generate_image")
## use LCEL to construct Digital Artist Agent
digital_artist = (
llm_with_img_gen_tool
| output_to_invoke_tools
)
将人在环与决策者的角色集成
为了保持人工监督,代理将分享他们的输出,以供最终批准。人类决策者将审核 Content Creator Agent 生成的文本和 Digital Artist Agent 制作的艺术作品。
这种交互允许进行多次迭代,确保促销消息和图像经过优化并可随时部署。
代理逻辑以人类为中心作为决策者,为每个任务分配合适的代理。 LangGraph 用于编排 代理认知架构 。
其中涉及一个请求人类输入的函数:
# Or you can directly instantiate the tool
from langchain_community.tools import HumanInputRun
from langchain.agents import AgentType, load_tools
from langchain.agents import AgentType, initialize_agent, load_tools
def get_human_input() -> str:
""" Put human as decision maker, human will decide which agent is best for the task"""
print("You have been given 2 agents. Please select exactly _ONE_ agent to help you with the task, enter 'y' to confirm your choice.")
print("""Available agents are : \n
1 ContentCreator \n
2 DigitalArtist \n
Enter 1 or 2""")
contents = []
while True:
try:
line = input()
if line=='1':
tool="ContentCreator"
line=tool
elif line=='2':
tool="DigitalArtist"
line=tool
else:
pass
except EOFError:
break
if line == "y":
print(f"tool selected : {tool} ")
break
contents.append(line)
return "\n".join(contents)
# You can modify the tool when loading
ask_human = HumanInputRun(input_func=get_human_input)
接下来,创建两个额外的 Python 函数作为图形节点,LangGraph 使用这些函数表示工作流中的步骤或操作。这些节点使智能体能够依次或并行执行特定任务,从而创建灵活的结构化流程:
from langgraph.graph import END, StateGraph
from langgraph.prebuilt import ToolInvocation
from colorama import Fore,Style
# Define the functions needed
def human_assign_to_agent(state):
# ensure using original prompt
inputs = state["input"]
input_to_agent = state["input_to_agent"]
concatenate_str = Fore.BLUE+inputs+ ' : '+Fore.CYAN+input_to_agent + Fore.RESET
print(concatenate_str)
print("---"*10)
agent_choice=ask_human.invoke(concatenate_str)
print(Fore.CYAN+ "choosen_agent : " + agent_choice + Fore.RESET)
return {"agent_choice": agent_choice }
def agent_execute_task(state):
inputs= state["input"]
input_to_agent = state["input_to_agent"]
print(Fore.CYAN+input_to_agent + Fore.RESET)
# choosen agent will execute the task
choosen_agent = state['agent_choice']
if choosen_agent=='ContentCreator':
structured_respond=content_creator.invoke({"product_desc":input_to_agent})
respond='\n'.join([structured_respond.Title,structured_respond.Message,''.join(structured_respond.Tags)])
elif choosen_agent=="DigitalArtist":
respond=digital_artist.invoke(input_to_agent)
else:
respond="please reselect the agent, there are only 2 agents available: 1.ContentCreator or 2.DigitalArtist"
print(Fore.CYAN+ "agent_output: \n" + respond + Fore.RESET)
return {"agent_use_tool_respond": respond}
最后,通过连接节点和边缘,将所有元素融合在一起,形成人类在环多智能体工作流程。一旦图形编译完成,您就可以继续:
from langgraph.graph import END, StateGraph
# Define a new graph
workflow = StateGraph(State)
# Define the two nodes
workflow.add_node("start", human_assign_to_agent)
workflow.add_node("end", agent_execute_task)
# This means that this node is the first one called
workflow.set_entry_point("start")
workflow.add_edge("start", "end")
workflow.add_edge("end", END)
# Finally, we compile it!
# This compiles it into a LangChain Runnable,
# meaning you can use it as you would any other runnable
app = workflow.compile()
启动人工智能工作流程
现在,启动应用。它会提示您为给定任务分配一个可用代理。
撰写宣传文本的提示
首先,查询 Content Creator Agent 以编写促销文本,包括标题、消息和社交媒体话题标签(图 2)。重复此操作,直到对输出感到满意。
Python 代码示例:
my_query="create a good promotional message for social promotion events using the following inputs"
product_desc="NVIDIA NIM microservices power GenAI workflow"
respond=app.invoke({"input":my_query, "input_to_agent":product_desc})
人类为该任务选择 1 个 Content Creator Agent。代理执行并返回 agent_output
,如图 3 所示。
创建插图的提示
对结果感到满意后,请继续查询数字艺术家代理(Digital Artist Agent),以创建用于社交媒体推广的艺术作品(图 4)。
以下 Python 代码示例使用 Content Creator Agent 生成的标题作为图像提示的输入:
## taken the output from the Title from the output of Content Creator Agent
prompt_for_image=respond['agent_use_tool_respond'].split('\n')[0].split(':')[-1].strip()
## Human decision maker give instruction to the agent workflow app
input_query="generate an image for me from the below promotion message"
respond2=app.invoke({"input":input_query, "input_to_agent":prompt_for_image})
生成的图像另存为 output.jpg。
迭代以获得高质量结果
您可以对生成的图像进行迭代,以获取不同的艺术作品变体,从而获得想要的结果(图 6)。通过 Content Creator Agent 略微调整输入提示,可以从 Digital Artist Agent 生成各种图像。
提炼最终产品
最后,执行后处理并优化两个智能体的组合输出,并以 Markdown 格式对其进行格式化,以便进行最终视觉审查(图 7)。
使用 NVIDIA NIM 微服务和 AI 工具增强您的 AI 智能体
在本博文中,您已学习如何使用 NVIDIA NIM 微服务 和 LangChain 的 LangGraph 构建人类在环 AI 智能体,以简化内容创作工作流程。通过将 AI 智能体融入工作流程,您可以加速内容制作、减少手动工作,并完全控制创意流程。
NVIDIA NIM 微服务使您能够高效灵活地扩展人工智能驱动的任务。无论您是在制作促销信息还是设计视觉效果,人工智能智能体都能提供强大的解决方案来优化工作流程并提高工作效率。
通过以下其他资源了解详情:
- 使用 NVIDIA NIM 微服务和 LangChain 构建 AI 智能体 (注:LangChain 是一个开源项目,用于构建大型语言模型的微服务。NVIDIA NIM 是一个用于构建 AI 智能体的微服务框架。)使用 NVIDIA NIM 微服务和 LangChain 构建 AI 智能体,可以更好地利用大型语言模型的能力,例如 Llama 3.1-70B-Instruct 和 Falcon 180B 等。此外,使用 NVIDIA NIM 微服务和 LangChain 还可以更好地支持多种 AI 框架,例如 PyTorch 和 pandas 等。
- 使用 LangGraph 在代理逻辑中整合人在环
- Notebook 的环境构建
- Llama 3.1 405B Instruct NIM 微服务