Microsoft Agent 框架支持创建使用 Anthropic 的 Claude 模型的代理。
即将推出……
先决条件
安装 Microsoft Agent Framework Anthropic 包。
pip install agent-framework-anthropic --pre
配置
环境变量
为人类身份验证设置所需的环境变量:
# Required for Anthropic API access
ANTHROPIC_API_KEY="your-anthropic-api-key"
ANTHROPIC_CHAT_MODEL_ID="claude-sonnet-4-5-20250929" # or your preferred model
或者,可以在项目根目录中使用 .env 文件:
ANTHROPIC_API_KEY=your-anthropic-api-key
ANTHROPIC_CHAT_MODEL_ID=claude-sonnet-4-5-20250929
可以从 人类控制台获取 API 密钥。
入门
从代理框架导入所需的类:
import asyncio
from agent_framework.anthropic import AnthropicClient
创建人类代理
基本代理创建
创建人类代理的最简单方法:
async def basic_example():
# Create an agent using Anthropic
agent = AnthropicClient().create_agent(
name="HelpfulAssistant",
instructions="You are a helpful assistant.",
)
result = await agent.run("Hello, how can you help me?")
print(result.text)
使用显式配置
可以提供显式配置,而不是依赖于环境变量:
async def explicit_config_example():
agent = AnthropicClient(
model_id="claude-sonnet-4-5-20250929",
api_key="your-api-key-here",
).create_agent(
name="HelpfulAssistant",
instructions="You are a helpful assistant.",
)
result = await agent.run("What can you do?")
print(result.text)
在 Foundry 上使用人类学
在 Foundry 上设置人类学后,请确保设置了以下环境变量:
ANTHROPIC_FOUNDRY_API_KEY="your-foundry-api-key"
ANTHROPIC_FOUNDRY_RESOURCE="your-foundry-resource-name"
然后创建代理,如下所示:
from agent_framework.anthropic import AnthropicClient
from anthropic import AsyncAnthropicFoundry
async def foundry_example():
agent = AnthropicClient(
anthropic_client=AsyncAnthropicFoundry()
).create_agent(
name="FoundryAgent",
instructions="You are a helpful assistant using Anthropic on Foundry.",
)
result = await agent.run("How do I use Anthropic on Foundry?")
print(result.text)
注意:需要安装
anthropic>=0.74.0。
代理功能
函数工具
为代理配备自定义功能:
from typing import Annotated
def get_weather(
location: Annotated[str, "The location to get the weather for."],
) -> str:
"""Get the weather for a given location."""
conditions = ["sunny", "cloudy", "rainy", "stormy"]
return f"The weather in {location} is {conditions[randint(0, 3)]} with a high of {randint(10, 30)}°C."
async def tools_example():
agent = AnthropicClient().create_agent(
name="WeatherAgent",
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 Seattle?")
print(result.text)
流式处理响应
对即时生成的响应进行获取,以提升用户体验。
async def streaming_example():
agent = AnthropicClient().create_agent(
name="WeatherAgent",
instructions="You are a helpful weather agent.",
tools=get_weather,
)
query = "What's the weather like in Portland and in Paris?"
print(f"User: {query}")
print("Agent: ", end="", flush=True)
async for chunk in agent.run_stream(query):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
托管工具
人类代理支持托管的工具,例如 Web 搜索、MCP(模型上下文协议)和代码执行:
from agent_framework import HostedMCPTool, HostedWebSearchTool
async def hosted_tools_example():
agent = AnthropicClient().create_agent(
name="DocsAgent",
instructions="You are a helpful agent for both Microsoft docs questions and general questions.",
tools=[
HostedMCPTool(
name="Microsoft Learn MCP",
url="https://learn.microsoft.com/api/mcp",
),
HostedWebSearchTool(),
],
max_tokens=20000,
)
result = await agent.run("Can you compare Python decorators with C# attributes?")
print(result.text)
扩展思维(推理)
Anthropic通过thinking功能支持扩展思维能力,使模型能够展示其推理过程。
from agent_framework import TextReasoningContent, UsageContent
async def thinking_example():
agent = AnthropicClient().create_agent(
name="DocsAgent",
instructions="You are a helpful agent.",
tools=[HostedWebSearchTool()],
max_tokens=20000,
additional_chat_options={
"thinking": {"type": "enabled", "budget_tokens": 10000}
},
)
query = "Can you compare Python decorators with C# attributes?"
print(f"User: {query}")
print("Agent: ", end="", flush=True)
async for chunk in agent.run_stream(query):
for content in chunk.contents:
if isinstance(content, TextReasoningContent):
# Display thinking in a different color
print(f"\033[32m{content.text}\033[0m", end="", flush=True)
if isinstance(content, UsageContent):
print(f"\n\033[34m[Usage: {content.details}]\033[0m\n", end="", flush=True)
if chunk.text:
print(chunk.text, end="", flush=True)
print()
使用代理
代理是标准 BaseAgent 代理,支持所有标准代理操作。
有关如何运行和与代理交互的详细信息,请参阅 代理入门教程 。