-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathstream_object_example.py
More file actions
52 lines (41 loc) · 1.59 KB
/
stream_object_example.py
File metadata and controls
52 lines (41 loc) · 1.59 KB
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
#!/usr/bin/env python3
"""
stream_object_example.py: CLI for streaming structured objects with ai-sdk.
Usage: stream_object_example.py --username USERNAME [--provider openai|anthropic] [--model MODEL_ID]
"""
import os
import argparse
import asyncio
from pydantic import BaseModel
from ai_sdk import openai, anthropic, stream_object
try:
from dotenv import load_dotenv # type: ignore
except Exception: # pragma: no cover
def load_dotenv() -> None: # type: ignore
return None
class UserProfile(BaseModel):
username: str
followers: int
bio: str
async def main():
load_dotenv()
parser = argparse.ArgumentParser(
description="UserProfile streaming CLI using ai-sdk."
)
parser.add_argument(
"--username", required=True, help="Username to fetch profile for."
)
parser.add_argument("--provider", choices=["openai", "anthropic"], default="openai")
parser.add_argument("--model", default=os.getenv("AI_SDK_MODEL", "gpt-4o-mini"))
args = parser.parse_args()
client = openai if args.provider == "openai" else anthropic
api_key_env = "OPENAI_API_KEY" if args.provider == "openai" else "ANTHROPIC_API_KEY"
model = client(args.model, api_key=os.getenv(api_key_env))
prompt = f"Provide profile JSON for user '{args.username}' with fields username, followers, bio."
result = stream_object(model=model, schema=UserProfile, prompt=prompt)
async for _ in result.object_stream:
pass
profile = await result.object(UserProfile)
print(profile.model_dump_json(indent=2))
if __name__ == "__main__":
asyncio.run(main())