File size: 2,745 Bytes
e062359 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | # Anthropic Foundry
To use this library with Foundry, use the `AnthropicFoundry` class instead of the `Anthropic` class.
## Installation
```bash
pip install anthropic
```
## Usage
### Basic Usage with API Key
```python
from anthropic import AnthropicFoundry
client = AnthropicFoundry(
api_key="...", # defaults to ANTHROPIC_FOUNDRY_API_KEY environment variable
resource="my-resource", # your Foundry resource
)
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}],
)
print(message.content[0].text)
```
### Using Azure AD Token Provider
For enhanced security, you can use Azure AD (Microsoft Entra) authentication instead of an API key:
```python
from anthropic import AnthropicFoundry
from azure.identity import DefaultAzureCredential
from azure.identity import get_bearer_token_provider
credential = DefaultAzureCredential()
token_provider = get_bearer_token_provider(
credential,
"https://ai.azure.com/.default"
)
client = AnthropicFoundry(
azure_ad_token_provider=token_provider,
resource="my-resource",
)
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}],
)
print(message.content[0].text)
```
## Examples
### Streaming Messages
```python
from anthropic import AnthropicFoundry
client = AnthropicFoundry(
api_key="...",
resource="my-resource",
)
with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about programming"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
```
### Async Usage
```python
from anthropic import AsyncAnthropicFoundry
async def main():
client = AsyncAnthropicFoundry(
api_key="...",
resource="my-resource",
)
message = await client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello!"}],
)
print(message.content[0].text)
import asyncio
asyncio.run(main())
```
### Async Streaming
```python
from anthropic import AsyncAnthropicFoundry
async def main():
client = AsyncAnthropicFoundry(
api_key="...",
resource="my-resource",
)
async with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a haiku about programming"}],
) as stream:
async for text in stream.text_stream:
print(text, end="", flush=True)
import asyncio
asyncio.run(main())
``` |