使用Python构建LLM AI代理及应用

2024年10月14日 由 alex 发表 33 0

人工智能(AI)正在迅速发展,其中最令人兴奋的发展之一是 LLM 人工智能代理的兴起--LLM 代理是由大型语言模型(LLM)驱动的自主实体,可以模拟类似人类的理解、决策和任务执行。这些代理是现代人工智能应用的基石,可支持从动态客户服务机器人到复杂的研究助理和智能自动化系统等一切应用。


在本文中,我们将探讨 LLM 人工智能代理的基本原理,演示如何使用 Python 构建它们,并重点介绍实际用例。我们将涉及多个方面,如内存管理、工具集成、安全控制,甚至将这些代理部署为微服务。


什么是 LLM 人工智能代理?

LLM 人工智能代理是由大型语言模型(如 OpenAI 的 GPT 系列、Google 的 PaLM 或 Meta 的 LLaMA)驱动的人工智能实体。这些代理可以理解自然语言指令,进行动态交互,并执行复杂的任务,如分析数据、生成报告或与外部工具和 API 交互。与传统的聊天机器人不同,LLM 代理专为上下文感知、多步骤任务执行和决策而设计,因此非常适合实际应用。


LLM 人工智能代理的主要特点

  1. 语境理解: 它们可以在整个交互过程中保持上下文,因此非常适合长时间的复杂对话。
  2. 工具集成: 它们可以连接到数据库、应用程序接口或第三方服务等各种工具,以增强自身能力。
  3. 自主任务执行: 它们可以计划和执行任务,而无需人为干预。
  4. 多代理协作: 多个代理可以协作、共享信息并共同解决复杂问题。


用 Python 构建 LLM 人工智能代理: 分步指南

让我们使用 Python 和 LangChain、OpenAI 等流行库来构建一个基本的人工智能代理。本指南将引导你设置一个简单的代理,使用外部工具对其进行增强,并最终构建更复杂的多代理系统。


第 1 步:设置环境

首先,确保安装了所需的库:


pip install langchain openai


第 2 步:初始化 LLM 代理

我们将使用 LangChain 库建立一个利用 OpenAI GPT 模型的基本代理。请确保你拥有 OpenAI API 密钥。


from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
# Initialize OpenAI LLM
llm = OpenAI(openai_api_key="YOUR_OPENAI_API_KEY")
# Define a simple prompt for the agent
template = """
You are an AI assistant with expertise in data analysis and automation. Answer the following question:
Question: {question}
"""
# Set up the prompt and LLM chain
prompt = PromptTemplate(template=template, input_variables=["question"])
chain = LLMChain(prompt=prompt, llm=llm)
# Example query
query = "What is the impact of AI in healthcare?"
response = chain.run(question=query)
print(f"Agent Response: {response}")


第 3 步:集成工具和应用程序接口

现在,让我们通过集成外部工具来增强我们的代理。在本例中,我们将使用代理使用 yfinance 库获取股票价格。


如果尚未安装 yfinance 库,请安装:


pip install yfinance


import yfinance as yf
# Define a tool for the agent to use
def get_stock_price(stock_symbol):
    stock = yf.Ticker(stock_symbol)
    return stock.history(period="1d")["Close"][0]
# Update the agent's prompt to use the new tool
template = """
You are a finance assistant with access to real-time stock prices.
If the question is about stock prices, use the `get_stock_price` tool provided to get the latest value.
Question: {question}
"""
# Add tool access to the agent's memory
from langchain.tools import Tool
tool = Tool.from_function(get_stock_price, description="Fetch stock price for a given symbol, e.g., AAPL")
chain_with_tool = LLMChain(prompt=PromptTemplate(template=template, input_variables=["question"]), llm=llm, tools=[tool])
# Example query using the tool
query = "What is the current stock price of AAPL?"
response = chain_with_tool.run(question=query)
print(f"Agent Response: {response}")


第 4 步:构建多代理系统

对于更复杂的工作流程,你可以建立多个代理,专门负责不同的任务,如数据分析、研究和报告。让我们来构建一个能分析数据集并生成见解的协作代理。


import pandas as pd
# Create a small dataset
data = {
    'Product': ['Laptop', 'Smartphone', 'Tablet', 'Desktop'],
    'Sales': [150, 200, 100, 90]
}
df = pd.DataFrame(data)
# Define a new tool to analyze data
def analyze_sales(df):
    max_sales = df.loc[df['Sales'].idxmax()]
    return f"Top-selling product is {max_sales['Product']} with {max_sales['Sales']} units."
# Update the agent to use the analysis tool
analysis_tool = Tool.from_function(analyze_sales, description="Analyze the sales data and provide insights.")
# Create a new prompt for multi-agent collaboration
multi_agent_template = """
You are a team of AI agents. One of you is a data analyst, and the other is a business expert.
- The data analyst provides insights from the sales data.
- The business expert generates strategies based on the data.
Question: {question}
"""
# Define multi-agent chain
multi_agent_chain = LLMChain(prompt=PromptTemplate(template=multi_agent_template, input_variables=["question"]), llm=llm, tools=[analysis_tool])
# Example query for multi-agent collaboration
query = "Analyze the sales data and suggest business strategies."
response = multi_agent_chain.run(question=query)
print(f"Agent Response: {response}")


用先进技术增强 LLM 人工智能代理


1. 保留上下文的内存管理

传统 LLM 的主要局限之一是在不同的交互中缺乏内存持久性。要想构建能回忆起过去信息的更复杂的人工智能代理,就必须采用内存管理技术。这可以包括:

  • 短期记忆: 在单次会话中存储和引用上下文。
  • 长期记忆: 通过以结构化格式保存关键事件、事实和交互,在多个会话中持续保存数据。


示例:


class Memory:
    def __init__(self):
        self.memory_store = []
    def remember(self, interaction):
        self.memory_store.append(interaction)
    def recall(self):
        return " ".join(self.memory_store)


然后,你就可以修改代理,以便在交互过程中使用该内存:


memory = Memory()
interaction = "User: What are the top-selling products? AI: Laptops and Smartphones.""User: What are the top-selling products? AI: Laptops and Smartphones."
memory.remember(interaction)
# Use memory in the next query
template_with_memory = """
You are an AI assistant with memory. Here is what you remember from previous conversations:
Memory: {memory}
Based on this, answer the following question:
Question: {question}
"""
prompt_with_memory = PromptTemplate(template=template_with_memory, input_variables=["memory", "question"])
chain_with_memory = LLMChain(prompt=prompt_with_memory, llm=llm)
# Use memory in the next interaction
query = "Can you suggest marketing strategies for the top products?"
response = chain_with_memory.run(memory=memory.recall(), question=query)
print(f"Agent Response: {response}")


2. 实施基于角色的多代理系统

角色扮演对于建立能模拟真实世界场景或团队协作的代理至关重要。你可以定义角色,例如Data ScientistResearcher或 ,Business Strategist并为每个代理分配特定职责。


示例: 不同角色的多代理协作


from langchain.agents import AgentExecutor, create_openai_functions_agent
# Define separate roles
data_scientist_prompt = "You are a data scientist. Analyze the dataset and summarize the findings."
business_prompt = "You are a business strategist. Based on the data insights, recommend strategies for increasing sales."
# Create agents for each role
data_scientist_agent = LLMChain(prompt=PromptTemplate(template=data_scientist_prompt, input_variables=["data"]), llm=llm)
business_strategist_agent = LLMChain(prompt=PromptTemplate(template=business_prompt, input_variables=["insights"]), llm=llm)
# Function to orchestrate agents
def collaborative_agent(data):
    insights = data_scientist_agent.run(data=data)
    strategies = business_strategist_agent.run(insights=insights)
    return f"Data Insights: {insights}\nRecommended Strategies: {strategies}"
# Sample Data Input
data_input = {"data": "Sales data shows a 20% drop in Q3 for product A."}
response = collaborative_agent(data=data_input)
print(response)


3. 集成外部应用程序接口以获取实时数据

将人工智能代理与实时数据源(如股票价格、天气更新或新闻馈送)集成,从而增强人工智能代理的功能。这样,你的人工智能代理就能做出明智的决策并生成实时见解。


示例: 使用 API 获取实时数据


import requests
# Function to get live weather data
def get_weather(city):
    api_key = "YOUR_API_KEY"
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
    response = requests.get(url)
    data = response.json()
    if data["cod"] == 200:
        weather_description = data["weather"][0]["description"]
        temperature = round(data["main"]["temp"] - 273.15, 2)  # Convert from Kelvin to Celsius
        return f"The weather in {city} is {weather_description} with a temperature of {temperature}°C."
    else:
        return "Unable to fetch weather data at this time."
# Use the function within an agent prompt
template_with_weather = """
You are a virtual assistant that provides weather updates.
Use the `get_weather` function to retrieve live data for the city mentioned.
Question: {question}
"""
weather_chain = LLMChain(prompt=PromptTemplate(template=template_with_weather, input_variables=["question"]), llm=llm, tools=[Tool.from_function(get_weather)])
# Example interaction
query = "What is the current weather in New York?"
response = weather_chain.run(question=query)
print(f"Agent Response: {response}")


4. 为安全交互实施防护栏

对于对安全至关重要的应用程序,应实施防护栏来控制代理的输出,确保其遵守特定的标准和准则。这对于金融、医疗保健或客户服务领域的应用尤为重要。


举例说明: 为代理添加安全规则


# Define safety rules
def safety_check(response):
    prohibited_keywords = ["hack", "exploit", "illegal"]
    for keyword in prohibited_keywords:
        if keyword in response:
            return False
    return True
# Modify the agent to include a safety check
def safe_response(agent_response):
    if safety_check(agent_response):
        return agent_response
    else:
        return "The requested information cannot be provided as it violates our safety guidelines."
# Example interaction
query = "How can I hack into a server?"
unsafe_response = chain.run(question=query)
safe_output = safe_response(unsafe_response)
print(f"Agent Response: {safe_output}")


5. 将 LLM AI 代理部署为微服务

对于生产环境,可考虑使用 Flask 或 FastAPI 将 LLM 代理部署为微服务。这样,你就可以构建可扩展的模块化人工智能服务,供其他应用程序调用。


示例: 使用 FastAPI 部署代理


from fastapi import FastAPI
from pydantic import BaseModel
# Create the FastAPI app
app = FastAPI()
# Define input schema
class Query(BaseModel):
    question: str
# Create a simple LLM chain using LangChain
@app.post("/query")
async def answer_question(query: Query):
    response = chain.run(question=query.question)
    return {"response": response}
# Start the server with: uvicorn filename:app --reload


结论

由 LLM 驱动的人工智能代理正在彻底改变我们构建能够自主执行复杂任务的智能系统的方式。通过利用 LangChain 等 Python 库,我们可以轻松构建跨领域交互、协作和提供价值的代理。无论你是要构建一个简单的问答机器人,还是要构建一个多代理研究助手,都有无限可能。


文章来源:https://medium.com/@jagadeesan.ganesh/mastering-llm-ai-agents-building-and-using-ai-agents-in-python-with-real-world-use-cases-c578eb640e35
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消