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

AI Agent开发入门笔记(1)

目录

  • 1️⃣ 选择框架
  • 2️⃣开发操作
    • 导入Python库
    • 创建功能函数
    • 装载环境变量
    • 创建Agent
    • 运行Agent


学习参考资料:

  • 微软 AI Agents for Beginners
    • 代码仓库

1️⃣ 选择框架

semantic-kernel开发框架

  1. 导入库
  2. 创建功能函数(Agent 要完成什么功能)
  3. 创建客户端
    1. 加载环境变量(保存在.env,保证API_Key安全性)
    2. 配置基地址(URL
    3. 选择基座模型
  4. 创建Agent
    1. 将客户端配置到 service
    2. Agent 名称
  5. 运行Agent

可能头疼地方的解决方案:

  • 模型API付费:
    • 创建 Github Token
    • 基地址:https://models.inference.ai.azure.com/

2️⃣开发操作

导入Python库

import os 
from typing import Annotated
from openai import AsyncOpenAIfrom dotenv import load_dotenvfrom semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions import kernel_function

创建功能函数

import random   # Define a sample plugin for the sampleclass DestinationsPlugin:"""A List of Random Destinations for a vacation."""def __init__(self):# List of vacation destinationsself.destinations = ["Barcelona, Spain","Paris, France","Berlin, Germany","Tokyo, Japan","Sydney, Australia","New York, USA","Cairo, Egypt","Cape Town, South Africa","Rio de Janeiro, Brazil","Bali, Indonesia"]# Track last destination to avoid repeatsself.last_destination = None@kernel_function(description="Provides a random vacation destination.")def get_random_destination(self) -> Annotated[str, "Returns a random vacation destination."]:# Get available destinations (excluding last one if possible)available_destinations = self.destinations.copy()if self.last_destination and len(available_destinations) > 1:available_destinations.remove(self.last_destination)# Select a random destinationdestination = random.choice(available_destinations)# Update the last destinationself.last_destination = destinationreturn destination

装载环境变量

load_dotenv()
client = AsyncOpenAI(api_key=os.environ.get("GITHUB_TOKEN"), base_url="https://models.inference.ai.azure.com/",
)# Create an AI Service that will be used by the `ChatCompletionAgent`
chat_completion_service = OpenAIChatCompletion(# 模型可自行选择ai_model_id="gpt-4o-mini",async_client=client,
)

创建Agent

agent = ChatCompletionAgent(service=chat_completion_service, plugins=[DestinationsPlugin()],name="TravelAgent",instructions="You are a helpful AI Agent that can help plan vacations for customers at random destinations",
)

运行Agent

async def main():# Create a new thread for the agent# If no thread is provided, a new thread will be# created and returned with the initial responsethread: ChatHistoryAgentThread | None = Noneuser_inputs = ["Plan me a day trip.",]for user_input in user_inputs:print(f"# User: {user_input}\n")first_chunk = Trueasync for response in agent.invoke_stream(messages=user_input, thread=thread,):# 5. Print the responseif first_chunk:print(f"# {response.name}: ", end="", flush=True)first_chunk = Falseprint(f"{response}", end="", flush=True)thread = response.threadprint()# Clean up the threadawait thread.delete() if thread else Noneawait main()

在这里插入图片描述

http://www.xdnf.cn/news/9973.html

相关文章:

  • C++ 实现 std::move_only_function
  • DeepSeek R1 模型小版本升级,DeepSeek-R1-0528都更新了哪些新特性?
  • UniDream AI绘画——让想象力,无界绽放
  • 可定制化货代管理系统,适应不同业务模式需求!
  • 智能改变一切:当技术革命遇见人类文明
  • OpenCV---pointPolygonTest
  • 【实例】事业单位学习平台自动化操作
  • 【Web应用】若依框架:基础篇12 项目结构
  • DeepSeek 赋能文化遗产数字化修复:AI 重构千年文明密码
  • 如何从ISO镜像直接制作Docker容器基础镜像
  • 明场检测与暗场检测的原理
  • Excel 中的SUMIFS用法(基础版),重复项求和
  • 基于SpringBoot的商家销售管理网站的设计与实现
  • 第二章 2.1 数据存储安全风险之数据存储风险点
  • Java类和对象详解
  • RS232转Profinet网关在检漏仪与西门子PLC里的应用
  • 前端流式接收数据讲解
  • 万兴PDF手机版
  • audit日志轮训保留180天的日志,按天保存
  • C++17原生测试编程实践:现代特性与分支覆盖指南
  • 大疆上云API+流媒体服务器部署实现直播功能
  • 基于粒子滤波的PSK信号解调实现
  • new和delete的理解
  • ESP8266远程控制:实现网络通信与设备控制
  • 编程之巅:语言的较量
  • for(auto a:b)和for(auto a:b)的区别
  • Nginx Lua模块(OpenResty)实战:动态化、智能化你的Nginx,实现复杂Web逻辑 (2025)
  • CentOS7.9环境离线部署docker和docker-compose的两种方式
  • 小型图书管理系统案例(用于spring mvc 实践)
  • python37天打卡