21CTO导读:本文将为您分享AI Agent分步入门包,您将在 5 天内从空白屏幕转变为可以工作的AI代理。
如果您是 AI 代理的新手,那么来对地方了。
这个领域的每个人都是从零开始的。我多年来一直在构建人工智能代理和自动化技术,同时也为一家人工智能/机器学习初创公司撰写内容,所以我既花时间构建技术,又可以用通俗易懂的语言解释它。
在本指南中,我省略那些空谈和炒作,并向您展示快速构建第一个 AI 代理所需的具体工具。
如果您今天来到这里,说“我想在本周末之前从零开始构建一个可以运行的代理”,这里会把这些东西交给您。
我们从这里开始。
OpenAI GPT 是快速启动程序的最简单方法。您可以构建一个功能齐全的 AI 助手,无需修改代码、托管服务器或使用 API。只需输入指令,上传所需文件,它即可准备就绪。
有没有“更好”的模型?当然有。如果你花费数周时间编写自定义解决方案,能否挤出更多性能?或许有。如果目标是立即完成某件事,GPT 比其他任何方法都能让你更快地实现目标。
这是你的第一步:
当你喝完咖啡时,你就会拥有一个可以正常工作的个人人工智能代理。
n8n 是一款开源自动化工具,可将您的 AI 连接到其他应用、API 和数据源。它类似于 Zapier,但控制力更强,支持自托管,并且不受供应商锁定。
例如,您可以:
我还刚刚构建了一个由 AI 驱动的工作流程,无需从头开始编写庞大的后端。
尝试以下方法开始:
一旦您看到它发挥作用,您就会意识到可以将几十种工具链接成一个强大的工具。
当你准备开始编程时,CrewAI 是一个很棒的多智能体系统 Python 框架。多智能体系统是指多个专门的智能体协同工作,共同实现一个目标的设置。
想象一下“研究团队”:
CrewAI 负责协调,因此您可以专注于代理的实际操作。
您不需要高级的机器学习知识,只需要基本的 Python 技能,例如设置虚拟环境和运行脚本。
请从这个开始:
这会让你将代理视为队友,而不仅仅是聊天机器人。
Cursor 是一款 AI 驱动的代码编辑器,可直接在您的开发环境中运行。它可以读取您的代码库并按需生成新代码,就像 GitHub Copilot 一样,但它的控制力更强。
乐趣就在这里:告诉 Cursor 建立一个 CrewAI 项目,其中包含三个负责研究、总结和写作的智能体。它会在你的项目中搭建整个框架。无需在文档之间跳转,也无需无休止地从教程中复制粘贴。
我们来尝试一下:
只需几分钟,您便会拥有一个可正常运行的多代理系统,而无需手动将各个部分连接在一起。
有时,您还需要一个简洁的界面来方便用户使用您的代理,无论是用于演示、内部测试还是公开发布。
Streamlit 正是我们的理想之选。
它是一个 Python 库,可让您在几分钟内创建一个简洁、功能齐全的 Web 应用,不需要 HTML、CSS 或 JavaScript,只需编写 Python 代码,运行它后,即可在浏览器中运行。
例如,您可以构建:
要构建你的第一个代理:
专业提示:如果您使用 Cursor,请提示它“为我的 CrewAI 聊天机器人构建 Streamlit UI”,它将为您编写整个界面。
按回车键或单击即可查看完整尺寸的图像
抛开那些流行术语。代理只是运行在服务器上的代码,使用了语言模型和调用工具。
没有魔法,只有工程。
当你不再把它们当成神秘的黑匣子时,你的构建速度会更快。你也不会再浪费时间追逐“最先进的框架”,而是专注于让项目上线。
想象一下每个代理项目都是这样的:
列表中的所有内容:GPT、n8n、CrewAI、Cursor、Streamlit,都完美契合该结构。
我们可以从小处着手,逐步增加复杂性,并持续改进。
可以将其视为构建任何 AI 代理的蓝图,无论你使用哪种工具。你可以将项目分解为以下核心部分:
如何使用此食谱
首先,选择适合每个部分的工具。例如:
然后,逐步构建:
想要在一周内拥有一个可以运行的AI代理系统吗?请您严格按照以下步骤操作:
最后,您将不再只是简单的聊天,而是开始完成真正的任务。
以下是一个您可以在 Python 中修改的最小示例:
import openai
import os
import requests # Example for a web API tool
# --- Brain: Use OpenAI GPT API ---
def ask_gpt(prompt):
"""
Calls the OpenAI API to get a response based on the provided prompt.
"""
# Ensure you have your OpenAI API key set as an environment variable
# export OPENAI_API_KEY='your-api-key'
openai.api_key = os.getenv("OPENAI_API_KEY")
if not openai.api_key:
return "Error: OpenAI API key not found. Please set the OPENAI_API_KEY environment variable."
try:
# Using ChatCompletion for newer models like gpt-3.5-turbo or gpt-4
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # Or "gpt-4" if you have access
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
],
max_tokens=150, # Adjust as needed
temperature=0.7 # Adjust for creativity
)
return response.choices[0].message['content'].strip()
except Exception as e:
return f"Error calling OpenAI API: {e}"
# --- Tool: Simple API call (replace with your tool) ---
def get_data(query):
"""
Fetches data from an external source based on the query.
Replace this with your actual tool implementation.
"""
print(f"Fetching data for query: '{query}'...")
# --- Example: Using a hypothetical public API ---
# Let's assume there's an API that returns information based on a search term.
# You would replace this with your actual API endpoint and parameters.
# Example using a dummy API that just returns the query in a string
# In a real scenario, you'd make a request like:
# try:
# api_url = f"https://api.example.com/data?q={query}"
# response = requests.get(api_url)
# response.raise_for_status() # Raise an exception for bad status codes
# data = response.json() # Assuming API returns JSON
# return str(data) # Convert to string for the prompt
# except requests.exceptions.RequestException as e:
# return f"Error fetching data from API: {e}"
# For this example, we'll just return a placeholder string
return f"Placeholder data for '{query}' from my tool."
# --- End of Example ---
# --- Orchestration: Combine brain and tool ---
def agent_workflow(question):
"""
Orchestrates the workflow: gets data from the tool and then asks the
GPT brain to respond using that data.
"""
print("Starting agent workflow...")
data_from_tool = get_data(question)
if data_from_tool.startswith("Error"):
return data_from_tool # Return the error from the tool
print(f"Data received from tool: '{data_from_tool}'")
# Construct the prompt for the GPT model
prompt_for_gpt = f"Use the following data to answer the question: '{question}'\n\nData:\n{data_from_tool}"
response_from_gpt = ask_gpt(prompt_for_gpt)
return response_from_gpt
# --- Interface: Command line ---
if __name__ == "__main__":
print("Welcome to your AI Agent!")
print("Type 'quit' or 'exit' to stop.")
while True:
user_input = input("\nAsk your agent: ")
if user_input.lower() in ["quit", "exit"]:
print("Exiting agent. Goodbye!")
break
if not user_input.strip():
print("Please enter a question.")
continue
agent_response = agent_workflow(user_input)
print("\nAgent's Answer:")
print(agent_response)Swap in your actual API calls, hosting, and UI as needed.
遵循我分享的工具顺序,但不要急于一次性掌握所有细节。快速运行你的第一个版本,然后持续推进便可。
真正的学习是在实践中构建、测试和改进的过程中实现的。学习AI Agent的最快方法就是自己构建一个,即使一开始很粗糙。
作者:场长
参考:
https://medium.com/data-science-collective/the-zero-to-agent-playbook-53b8ea6dd099
本篇文章为 @ 场长 创作并授权 21CTO 发布,未经许可,请勿转载。
内容授权事宜请您联系 webmaster@21cto.com或关注 21CTO 公众号。
该文观点仅代表作者本人,21CTO 平台仅提供信息存储空间服务。