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

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()

在这里插入图片描述

相关文章:

  • 面试大厂Java:从Spring Boot到微服务架构
  • Asp.Net Core FluentValidation校验框架
  • 判断它是否引用了外部库
  • Linux Kernel动态调试:运行时调试的利器
  • 【自然语言处理】——基于与训练模型的方法【复习篇1】
  • Visual Studio 2022 发布独立的 exe 文件
  • 【android bluetooth 案例分析 04】【Carplay 详解 1】【CarPlay 在车机侧的蓝牙通信原理与角色划分详解】
  • C++ 实现 std::move_only_function
  • 西蒙诺维奇-炮弹导体粗糙度模型揭秘
  • 详解RBAC权限模型
  • 组件化开发:构建可复用的DeepSeek小程序组件
  • 公网ip怎么申请和使用?本地只有内网IP如何提供外网访问?
  • Java基础知识总结继承与多态详解
  • ESP32-C6 智能网关设备WiFi6高性能通信应用
  • 【Java学习笔记】接口
  • 群晖synology nas安装curl教程
  • 004时装购物系统技术解析:构建智能时尚消费平台
  • 领域驱动设计 (Domain-Driven Design, DDD)
  • oracle goldengate实现postgresql 到 postgresql的实时同步
  • 交错推理强化学习方法提升医疗大语言模型推理能力的深度分析
  • 衢州市住房建设局 网站/国内打开google网页的方法
  • 做网站如何链接邮箱/网络服务商怎么咨询
  • 求助如何做网站推广/运营推广seo招聘
  • 学校网站的系统建设方式/江苏网站seo
  • 公司做网站推广/重庆seo顾问
  • 做网站域名公司/企业网站优化外包