|
| 1 | +import logging |
| 2 | +import os |
| 3 | + |
| 4 | +import openai |
| 5 | +from dotenv import load_dotenv |
| 6 | +from markitdown import MarkItDown |
| 7 | +from pydantic import BaseModel |
| 8 | +from rich import print |
| 9 | + |
| 10 | +logging.basicConfig(level=logging.WARNING) |
| 11 | +load_dotenv(override=True) |
| 12 | + |
| 13 | +if os.getenv("OPENAI_HOST", "github") == "azure": |
| 14 | + import azure.identity |
| 15 | + |
| 16 | + if not os.getenv("AZURE_OPENAI_SERVICE") or not os.getenv("AZURE_OPENAI_GPT_DEPLOYMENT"): |
| 17 | + logging.warning("AZURE_OPENAI_SERVICE and AZURE_OPENAI_GPT_DEPLOYMENT env variables are empty. See README.") |
| 18 | + exit(1) |
| 19 | + credential = azure.identity.AzureDeveloperCliCredential(tenant_id=os.getenv("AZURE_TENANT_ID")) |
| 20 | + token_provider = azure.identity.get_bearer_token_provider( |
| 21 | + credential, "https://cognitiveservices.azure.com/.default" |
| 22 | + ) |
| 23 | + client = openai.OpenAI( |
| 24 | + base_url=f"https://{os.getenv('AZURE_OPENAI_SERVICE')}.openai.azure.com/openai/v1", |
| 25 | + api_key=token_provider, |
| 26 | + ) |
| 27 | + model_name = os.getenv("AZURE_OPENAI_GPT_DEPLOYMENT") |
| 28 | +else: |
| 29 | + if not os.getenv("GITHUB_TOKEN"): |
| 30 | + logging.warning("GITHUB_TOKEN env variable is empty. See README.") |
| 31 | + exit(1) |
| 32 | + client = openai.OpenAI( |
| 33 | + base_url="https://models.github.ai/inference", |
| 34 | + api_key=os.environ["GITHUB_TOKEN"], |
| 35 | + default_query={"api-version": "2024-08-01-preview"}, |
| 36 | + ) |
| 37 | + model_name = "openai/gpt-4o" |
| 38 | + |
| 39 | + |
| 40 | +# Define models for Structured Outputs |
| 41 | +class DocumentMetadata(BaseModel): |
| 42 | + title: str |
| 43 | + author: str | None |
| 44 | + headings: list[str] |
| 45 | + |
| 46 | + |
| 47 | +# Use markitdown to convert docx to markdown |
| 48 | +md = MarkItDown(enable_plugins=False) |
| 49 | +markdown_text = md.convert("example_doc.docx").text_content |
| 50 | + |
| 51 | +# Send request to LLM to extract using Structured Outputs |
| 52 | +completion = client.beta.chat.completions.parse( |
| 53 | + model=model_name, |
| 54 | + messages=[ |
| 55 | + {"role": "system", "content": "Extract the document title, author, and a list of all headings."}, |
| 56 | + {"role": "user", "content": markdown_text}, |
| 57 | + ], |
| 58 | + response_format=DocumentMetadata, |
| 59 | +) |
| 60 | + |
| 61 | +message = completion.choices[0].message |
| 62 | +if message.refusal: |
| 63 | + print(message.refusal) |
| 64 | +else: |
| 65 | + print(message.parsed) |
0 commit comments