Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Microsoft Agent Framework mendukung pembuatan agen yang menggunakan layanan OpenAI ChatCompletion .
Memulai Langkah Awal
Tambahkan paket NuGet yang diperlukan ke proyek Anda.
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
Membuat Sebuah Agen OpenAI ChatCompletion
Sebagai langkah pertama, Anda perlu membuat klien untuk terhubung ke layanan OpenAI.
using System;
using Microsoft.Agents.AI;
using OpenAI;
OpenAIClient client = new OpenAIClient("<your_api_key>");
OpenAI mendukung beberapa layanan yang semuanya menyediakan kemampuan panggilan model. Pilih layanan ChatCompletion untuk membuat agen berbasis ChatCompletion.
var chatCompletionClient = client.GetChatClient("gpt-4o-mini");
Terakhir, buat agen menggunakan AsAIAgent metode ekstensi pada ChatCompletionClient.
AIAgent agent = chatCompletionClient.AsAIAgent(
instructions: "You are good at telling jokes.",
name: "Joker");
// Invoke the agent and output the text result.
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));
Menggunakan Agen
Agen adalah standar AIAgent dan mendukung semua operasi standar AIAgent .
Untuk informasi selengkapnya tentang cara menjalankan dan berinteraksi dengan agen, lihat tutorial Memulai Agen.
Prasyarat
Diinstal paket Microsoft Agent Framework.
pip install agent-framework-core --pre
Konfigurasi
Variabel Lingkungan
Siapkan variabel lingkungan yang diperlukan untuk autentikasi OpenAI:
# Required for OpenAI API access
OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL_ID="gpt-4o-mini" # or your preferred model
Atau, Anda dapat menggunakan .env file di akar proyek Anda:
OPENAI_API_KEY=your-openai-api-key
OPENAI_CHAT_MODEL_ID=gpt-4o-mini
Memulai Langkah Awal
Impor kelas yang diperlukan dari Agent Framework:
import asyncio
from agent_framework import ChatAgent
from agent_framework.openai import OpenAIChatClient
Membuat Sebuah Agen OpenAI ChatCompletion
Pembuatan Agen Dasar
Cara paling sederhana untuk membuat agen penyelesaian obrolan:
async def basic_example():
# Create an agent using OpenAI ChatCompletion
agent = OpenAIChatClient().as_agent(
name="HelpfulAssistant",
instructions="You are a helpful assistant.",
)
result = await agent.run("Hello, how can you help me?")
print(result.text)
Menggunakan Konfigurasi Eksplisit
Anda dapat menyediakan konfigurasi eksplisit alih-alih mengandalkan variabel lingkungan:
async def explicit_config_example():
agent = OpenAIChatClient(
ai_model_id="gpt-4o-mini",
api_key="your-api-key-here",
).as_agent(
instructions="You are a helpful assistant.",
)
result = await agent.run("What can you do?")
print(result.text)
Fitur Agen
Perangkat Fungsional
Lengkapi agen Anda dengan fungsi kustom:
from typing import Annotated
from pydantic import Field
def get_weather(
location: Annotated[str, Field(description="The location to get weather for")]
) -> str:
"""Get the weather for a given location."""
# Your weather API implementation here
return f"The weather in {location} is sunny with 25°C."
async def tools_example():
agent = ChatAgent(
chat_client=OpenAIChatClient(),
instructions="You are a helpful weather assistant.",
tools=get_weather, # Add tools to the agent
)
result = await agent.run("What's the weather like in Tokyo?")
print(result.text)
Web Search
Aktifkan kemampuan pencarian web real-time:
from agent_framework import HostedWebSearchTool
async def web_search_example():
agent = OpenAIChatClient(model_id="gpt-4o-search-preview").as_agent(
name="SearchBot",
instructions="You are a helpful assistant that can search the web for current information.",
tools=HostedWebSearchTool(),
)
result = await agent.run("What are the latest developments in artificial intelligence?")
print(result.text)
Alat Protokol Konteks Model (MCP)
Sambungkan ke server MCP lokal untuk kemampuan yang diperluas:
from agent_framework import MCPStreamableHTTPTool
async def local_mcp_example():
agent = OpenAIChatClient().as_agent(
name="DocsAgent",
instructions="You are a helpful assistant that can help with Microsoft documentation.",
tools=MCPStreamableHTTPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
),
)
result = await agent.run("How do I create an Azure storage account using az cli?")
print(result.text)
Manajemen Utas
Pertahankan konteks percakapan di beberapa interaksi:
async def thread_example():
agent = OpenAIChatClient().as_agent(
name="Agent",
instructions="You are a helpful assistant.",
)
# Create a persistent thread for conversation context
thread = agent.get_new_thread()
# First interaction
first_query = "My name is Alice"
print(f"User: {first_query}")
first_result = await agent.run(first_query, thread=thread)
print(f"Agent: {first_result.text}")
# Second interaction - agent remembers the context
second_query = "What's my name?"
print(f"User: {second_query}")
second_result = await agent.run(second_query, thread=thread)
print(f"Agent: {second_result.text}") # Should remember "Alice"
Respons yang Mengalir
Dapatkan respons saat dihasilkan untuk pengalaman pengguna yang lebih baik:
async def streaming_example():
agent = OpenAIChatClient().as_agent(
name="StoryTeller",
instructions="You are a creative storyteller.",
)
print("Agent: ", end="", flush=True)
async for chunk in agent.run_stream("Tell me a short story about AI."):
if chunk.text:
print(chunk.text, end="", flush=True)
print() # New line after streaming
Menggunakan Agen
Agen ini adalah BaseAgent standar dan mendukung semua operasi agen standar.
Untuk informasi selengkapnya tentang cara menjalankan dan berinteraksi dengan agen, lihat tutorial Memulai Agen.