【智能体agent】入门之--1.初体验
every blog every motto: You can do more than you think.
https://blog.csdn.net/weixin_39190382?type=blog
0. 前言
agent初体验,使用semantic_kernel
1. 正文
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
from typing import Annotated
# from semantic_kernel import kernel_function# 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("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"), api_key="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", 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",
)
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 = None# "Plan me a day trip.",user_inputs = ["创建一个旅游计划"]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()
# User: 创建一个旅游计划# TravelAgent: 你的旅游计划将会是去美国纽约!以下是一个为期五天的旅游计划建议:### 第一天:抵达纽约
- **上午**: 抵达纽约,前往酒店办理入住。
- **下午**: 游览中央公园,可以租自行车或者步行,享受绿意盎然的环境。
- **晚上**: 前往时代广场,感受繁华的夜景,可以在附近的餐馆用餐。### 第二天:名胜古迹
- **上午**: 参观自由女神像和埃利斯岛,可以提前在线购票以避免排队。
- **下午**: 回到曼哈顿,参观911纪念馆,了解悲惨的历史和英雄的故事。
- **晚上**: 享受一场百老汇的音乐剧,提前预定票。### 第三天:文化日
- **上午**: 参观大都会艺术博物馆,欣赏世界各地的艺术珍品。
- **下午**: 漫步到第五大道,体验购物和时尚。
- **晚上**: 在附近的餐厅品尝意大利或中餐。### 第四天:探索街区
- **上午**: 走访格林尼治村,体验独特的文化和历史。
- **下午**: 前往布鲁克林大桥,走过大桥,享受曼哈顿的美景。
- **晚上**: 在布鲁克林的餐厅用餐,体验当地美食。### 第五天:最后的时光
- **上午**: 参观联合国总部,了解其运作和历史。
- **下午**: 前往洛克菲勒中心,爬上观景台,俯瞰纽约全景。
- **晚上**: 准备离开,结束愉快的纽约之行。希望你会喜欢这个计划,祝旅途愉快!如果你需要进一步的帮助或修改,请告诉我。