1+ import os
2+
3+ import azure .identity
4+ import openai
5+ import rich
6+ from dotenv import load_dotenv
7+ from pydantic import BaseModel , Field
8+
9+ # Setup the OpenAI client to use either Azure, OpenAI.com, or Ollama API
10+ load_dotenv (override = True )
11+ API_HOST = os .getenv ("API_HOST" , "github" )
12+
13+ if API_HOST == "azure" :
14+ token_provider = azure .identity .get_bearer_token_provider (
15+ azure .identity .DefaultAzureCredential (), "https://cognitiveservices.azure.com/.default"
16+ )
17+ client = openai .AzureOpenAI (
18+ api_version = os .environ ["AZURE_OPENAI_VERSION" ],
19+ azure_endpoint = os .environ ["AZURE_OPENAI_ENDPOINT" ],
20+ azure_ad_token_provider = token_provider ,
21+ )
22+ MODEL_NAME = os .environ ["AZURE_OPENAI_DEPLOYMENT" ]
23+
24+ elif API_HOST == "ollama" :
25+ client = openai .OpenAI (base_url = os .environ ["OLLAMA_ENDPOINT" ], api_key = "nokeyneeded" )
26+ MODEL_NAME = os .environ ["OLLAMA_MODEL" ]
27+
28+ elif API_HOST == "github" :
29+ client = openai .OpenAI (base_url = "https://models.inference.ai.azure.com" , api_key = os .environ ["GITHUB_TOKEN" ])
30+ MODEL_NAME = os .getenv ("GITHUB_MODEL" , "gpt-4o" )
31+
32+ else :
33+ client = openai .OpenAI (api_key = os .environ ["OPENAI_KEY" ])
34+ MODEL_NAME = os .environ ["OPENAI_MODEL" ]
35+
36+
37+
38+ class CalendarEvent (BaseModel ):
39+ name : str
40+ date : str = Field (..., description = "A date in the format YYYY-MM-DD" )
41+ participants : list [str ]
42+
43+
44+ completion = client .beta .chat .completions .parse (
45+ model = MODEL_NAME ,
46+ messages = [
47+ {"role" : "system" , "content" : "Extract the event information. If no year is specified, assume the current year (2025)." },
48+ {"role" : "user" , "content" : "Alice and Bob are going to a science fair on the 1st of april." },
49+ ],
50+ response_format = CalendarEvent ,
51+ )
52+ CalendarEvent (name = 'Science Fair' , date = '2025-04-01' , participants = ['Alice' , 'Bob' ])
53+
54+ message = completion .choices [0 ].message
55+ if (message .refusal ):
56+ rich .print (message .refusal )
57+ else :
58+ event = message .parsed
59+ rich .print (event )
0 commit comments