|
| 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 | +class CalendarEvent(BaseModel): |
| 38 | + name: str |
| 39 | + date: str = Field(..., description="A date in the format YYYY-MM-DD") |
| 40 | + participants: list[str] |
| 41 | + |
| 42 | + |
| 43 | +completion = client.beta.chat.completions.parse( |
| 44 | + model=MODEL_NAME, |
| 45 | + messages=[ |
| 46 | + { |
| 47 | + "role": "system", |
| 48 | + "content": "Extrae la info del evento. Si no dice el año, asumí que es este año (2025).", |
| 49 | + }, |
| 50 | + {"role": "user", "content": "Alice y Bob van a ir a una feria de ciencias el 1 de abril."}, |
| 51 | + ], |
| 52 | + response_format=CalendarEvent, |
| 53 | +) |
| 54 | +CalendarEvent(name="Feria de Ciencias", date="2025-04-01", participants=["Alice", "Bob"]) |
| 55 | +message = completion.choices[0].message |
| 56 | +if message.refusal: |
| 57 | + rich.print(message.refusal) |
| 58 | +else: |
| 59 | + event = message.parsed |
| 60 | + rich.print(event) |
0 commit comments