Skip to main content

Utility functions for Azure GenAI

Project description

Azure GenAI Utils

This repository contains a set of utilities for working with Azure GenAI. The utilities are written in Python and are designed to be used for Hackathons, Workshops, and other events where you need to quickly get started with Azure GenAI.

Requirements

  • Azure Subscription
  • Azure AI Foundry
  • Bing Search API Key
  • Python 3.8 or later
  • .env file: Please do not forget to modify the .env file to match your account. Rename .env.sample to .env or copy and use it

Installation

PyPI

  • pip install azure-genai-utils

From Source

  • python setup.py install

Usage

Azure OpenAI Test

from azure_genai_utils.aoai_test import AOAI
aoai = AOAI()
aoai.simple_test()

PDF RAG Chain

Expand
from azure_genai_utils.rag.pdf import PDFRetrievalChain

pdf_path = "[YOUR-PDF-PATH]"

pdf = PDFRetrievalChain(
    source_uri=[pdf_path],
    loader_type="PDFPlumber",
    model_name="gpt-4o-mini",
    embedding_name="text-embedding-3-large",
    chunk_size=500,
    chunk_overlap=50,
).create_chain()

question = "[YOUR-QUESTION]"
docs = pdf.retriever.invoke(question)
results = pdf.chain.invoke({"chat_history": "", "question": question, "context": docs})

Bing Search

Expand
from azure_genai_utils.tools import BingSearch
from dotenv import load_dotenv

# You need to add BING_SUBSCRIPTION_KEY=xxxx in .env file
load_dotenv()

# Basic usage
bing = BingSearch(max_results=2, locale="ko-KR")
results = bing.invoke("Microsoft AutoGen")
print(results)

## Include news search results and format output
bing = BingSearch(
    max_results=2,
    locale="ko-KR",
    include_news=True,
    include_entity=False,
    format_output=True,
)
results = bing.invoke("Microsoft AutoGen")
print(results)

LangGraph Example (Bing Search + Azure GenAI)

Expand
import json
from typing import Annotated
from typing_extensions import TypedDict
from langchain_openai import AzureChatOpenAI
from langchain_core.messages import ToolMessage
from langgraph.graph.message import add_messages
from langgraph.graph import StateGraph
from langgraph.prebuilt import ToolNode
from langgraph.graph import START, END
from azure_genai_utils.tools import BingSearch
from dotenv import load_dotenv

load_dotenv()

class State(TypedDict):
    messages: Annotated[list, add_messages]

llm = AzureChatOpenAI(model="gpt-4o-mini")
tool = BingSearch(max_results=3, format_output=False)
tools = [tool]
llm_with_tools = llm.bind_tools(tools)

def chatbot(state: State):
    answer = llm_with_tools.invoke(state["messages"])
    return {"messages": [answer]}

def route_tools(
    state: State,
):
    if messages := state.get("messages", []):
        ai_message = messages[-1]
    else:
        raise ValueError(f"No messages found in input state to tool_edge: {state}")

    if hasattr(ai_message, "tool_calls") and len(ai_message.tool_calls) > 0:
        return "tools"

    return END

graph_builder = StateGraph(State)
graph_builder.add_node("chatbot", chatbot)
tool_node = ToolNode(tools=[tool])
graph_builder.add_node("tools", tool_node)

graph_builder.add_conditional_edges(
    source="chatbot",
    path=route_tools,
    path_map={"tools": "tools", END: END},
)

graph_builder.add_edge("tools", "chatbot")
graph_builder.add_edge(START, "chatbot")
graph = graph_builder.compile()

# Test
inputs = {"messages": "Microsoft AutoGen"}

for event in graph.stream(inputs, stream_mode="values"):
    for key, value in event.items():
        print(f"\n==============\nSTEP: {key}\n==============\n")
        print(value[-1])

Synthetic Data Generation

Expand
from azure_genai_utils.synthetic import (
    QADataGenerator,
    CustomQADataGenerator,
    QAType,
    generate_qas,
)

input_batch = [
    "The quick brown fox jumps over the lazy dog.",
    "What is the capital of France?",
]

model_config = {
    "deployment": "gpt-4o-mini",
    "model": "gpt-4o-mini",
    "max_tokens": 256,
}

try:
    qa_generator = QADataGenerator(model_config=model_config)
    # qa_generator = CustomQADataGenerator(
    #     model_config=model_config, templates_dir=f"./azure_genai_utils/synthetic/prompt_templates/ko"
    # )
    task = generate_qas(
        input_texts=input_batch,
        qa_generator=qa_generator,
        qa_type=QAType.LONG_ANSWER,
        num_questions=2,
        concurrency=3,
    )
except Exception as e:
    print(f"Error generating QAs: {e}")

License Summary

This sample code is provided under the Apache 2.0 license. See the LICENSE file.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

azure_genai_utils-0.0.2.9.tar.gz (32.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

azure_genai_utils-0.0.2.9-py3-none-any.whl (42.1 kB view details)

Uploaded Python 3

File details

Details for the file azure_genai_utils-0.0.2.9.tar.gz.

File metadata

  • Download URL: azure_genai_utils-0.0.2.9.tar.gz
  • Upload date:
  • Size: 32.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.0.1 CPython/3.12.2

File hashes

Hashes for azure_genai_utils-0.0.2.9.tar.gz
Algorithm Hash digest
SHA256 365530fae6eb83ed02ec8c7ac14774d9127e4ec484089b402e1e1a41416b23c2
MD5 9c8f734c40cfde93ef8eff7e47a5135c
BLAKE2b-256 c0e5f5cbaabba497bd9daabb9c15dfed2944a6d4ed547141215a41efaceaa19f

See more details on using hashes here.

File details

Details for the file azure_genai_utils-0.0.2.9-py3-none-any.whl.

File metadata

File hashes

Hashes for azure_genai_utils-0.0.2.9-py3-none-any.whl
Algorithm Hash digest
SHA256 006482b25aa9e2cdb5d4f0e87b599133acdfcd1a55508808a36f3c5deb1677ae
MD5 f47511e0c9863601250d39e47405576f
BLAKE2b-256 af9d7fe980d86e038c894f950ea63b21487183d5607beaad8d2fcb20da9f289b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page