File: main.py

package info (click to toggle)
python-azure 20251118%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 783,356 kB
  • sloc: python: 6,474,533; ansic: 804; javascript: 287; sh: 205; makefile: 198; xml: 109
file content (293 lines) | stat: -rw-r--r-- 10,493 bytes parent folder | download
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
from __future__ import annotations

import os
import json
import time
from dataclasses import dataclass
from typing import Any, AsyncGenerator, AsyncIterator, Dict, List, TypedDict

from dotenv import load_dotenv
from langgraph.graph import StateGraph, START, END
from openai import OpenAI, OpenAIError

from azure.ai.agentserver.core import AgentRunContext
from azure.ai.agentserver.core.models import Response, ResponseStreamEvent
from azure.ai.agentserver.langgraph import from_langgraph
from azure.ai.agentserver.langgraph.models import (
    LanggraphStateConverter,
)

load_dotenv()

API_KEY = os.environ.get("AZURE_OPENAI_API_KEY")
BASE_URL = os.environ.get("AZURE_OPENAI_ENDPOINT") + "openai/v1"
DEPLOYMENT = os.environ.get("AZURE_AI_MODEL_DEPLOYMENT_NAME")  # optional override
DEFAULT_MODEL = "gpt-4.1-mini"


# ---------------------------------------------------------------------------
# Simple in-memory knowledge base (replace with real vector DB in production)
# ---------------------------------------------------------------------------
@dataclass
class KBEntry:
    id: str
    text: str
    tags: List[str]


KNOWLEDGE_BASE: List[KBEntry] = [
    KBEntry(
        id="doc1",
        text="LangGraph enables stateful AI workflows via graphs of nodes.",
        tags=["langgraph", "workflow"],
    ),
    KBEntry(
        id="doc2",
        text="Retrieval augmented generation improves answer grounding by injecting documents.",
        tags=["rag", "retrieval", "grounding"],
    ),
    KBEntry(
        id="doc3",
        text="Streaming responses send partial model outputs for lower latency user experience.",
        tags=["streaming", "latency"],
    ),
]


# ---------------------------------------------------------------------------
# LangGraph State definition
# ---------------------------------------------------------------------------
class RAGState(TypedDict, total=False):
    query: str
    messages: List[Dict[str, Any]]  # simplified message records
    needs_retrieval: bool
    retrieved: List[Dict[str, Any]]  # selected documents
    answer_parts: List[str]  # incremental answer assembly
    final_answer: str  # final answer text
    _stream_events: List[Any]  # buffered upstream model delta events (if any)
    stream: bool  # whether streaming was requested


# ---------------------------------------------------------------------------
# Utility: naive keyword scoring retrieval
# ---------------------------------------------------------------------------
KEYWORDS = {
    "langgraph": ["langgraph", "graph"],
    "retrieval": ["retrieval", "rag", "ground"],
    "stream": ["stream", "latency", "partial"],
}


def retrieve_docs(question: str, k: int = 2) -> List[Dict[str, Any]]:
    scores: List[tuple[float, KBEntry]] = []
    lower_q = question.lower()
    for entry in KNOWLEDGE_BASE:
        score = 0
        for token in entry.tags:
            if token in lower_q:
                score += 2
        for kw_group in KEYWORDS.values():
            for kw in kw_group:
                if kw in lower_q and kw in entry.text.lower():
                    score += 1
        if score > 0:
            scores.append((score, entry))
    scores.sort(key=lambda t: t[0], reverse=True)
    return [{"id": e.id, "text": e.text, "score": s} for s, e in scores[:k]]


# ---------------------------------------------------------------------------
# Custom Converter
# ---------------------------------------------------------------------------
class RAGStateConverter(LanggraphStateConverter):
    """Converter implementing mini RAG logic (non‑streaming only)."""

    def get_stream_mode(self, context: AgentRunContext) -> str:  # noqa: D401
        if context.request.get("stream", False):  # type: ignore[attr-defined]
            raise NotImplementedError("Streaming not supported in this sample.")
        return "values"

    def request_to_state(self, context: AgentRunContext) -> Dict[str, Any]:  # noqa: D401
        req = context.request
        user_input = req.get("input")
        if isinstance(user_input, list):
            for item in user_input:
                if isinstance(item, dict) and item.get("type") in (
                    "message",
                    "input_text",
                ):
                    user_input = item.get("content") or user_input
                    break
        if isinstance(user_input, list):
            user_input = " ".join(str(x) for x in user_input)
        prompt = str(user_input or "")
        messages = []
        instructions = req.get("instructions")
        if instructions and isinstance(instructions, str):
            messages.append({"role": "system", "content": instructions})
        messages.append({"role": "user", "content": prompt})
        res = {
            "query": prompt,
            "messages": messages,
            "needs_retrieval": False,
            "retrieved": [],
            "answer_parts": [],
            "stream": False,
        }
        print("initial state:", res)
        return res

    def state_to_response(
        self, state: Dict[str, Any], context: AgentRunContext
    ) -> Response:  # noqa: D401
        final_answer = state.get("final_answer") or "(no answer generated)"
        print(f"convert state to response, state: {state}")
        citations = state.get("retrieved", [])
        output_item = {
            "type": "message",
            "role": "assistant",
            "content": [
                {
                    "type": "output_text",
                    "text": final_answer,
                    "annotations": [
                        {
                            "type": "citation",
                            "doc_id": c.get("id"),
                            "score": c.get("score"),
                        }
                        for c in citations
                    ],
                }
            ],
        }
        base = {
            "object": "response",
            "id": context.response_id,
            "agent": context.get_agent_id_object(),
            "conversation": context.get_conversation_object(),
            "status": "completed",
            "created_at": int(time.time()),
            "output": [output_item],
        }
        return Response(**base)

    async def state_to_response_stream(  # noqa: D401
        self,
        stream_state: AsyncIterator[Dict[str, Any] | Any],
        context: AgentRunContext,
    ) -> AsyncGenerator[ResponseStreamEvent, None]:
        raise NotImplementedError("Streaming not supported in this sample.")


# ---------------------------------------------------------------------------
# Graph Nodes
# ---------------------------------------------------------------------------


def _normalize_query(val: Any) -> str:
    """Extract a lowercase text query from varied structures.

    Accepts:
      * str
      * dict with 'content' or 'text'
      * list of mixed items (recursively extracts first textual segment)
    Falls back to JSON stringification for unknown structures.
    """
    if isinstance(val, str):
        return val.strip().lower()
    if isinstance(val, dict):
        for k in ("content", "text", "value"):
            v = val.get(k)
            if isinstance(v, str) and v.strip():
                return v.strip().lower()
        # flatten simple dict string values
        parts = [str(v) for v in val.values() if isinstance(v, (str, int, float))]
        if parts:
            return " ".join(parts).lower()
    if isinstance(val, list):
        for item in val:  # take first meaningful piece
            extracted = _normalize_query(item)
            if extracted:
                return extracted
        return ""
    try:
        return str(val).strip().lower()
    except Exception:  # noqa: BLE001
        return ""


def analyze_intent(state: RAGState) -> RAGState:
    raw_q = state.get("query", "")
    q = _normalize_query(raw_q)
    keywords = ("what", "how", "explain", "retrieval", "langgraph", "stream")
    needs = any(kw in q for kw in keywords)
    state["needs_retrieval"] = needs
    # Also store normalized form for downstream nodes if different
    if isinstance(raw_q, (dict, list)):
        state["query"] = q
    return state


def retrieve_if_needed(state: RAGState) -> RAGState:
    if state.get("needs_retrieval"):
        state["retrieved"] = retrieve_docs(state.get("query", ""))
    return state


def generate_answer(state: RAGState) -> RAGState:
    query = state.get("query", "")
    retrieved = state.get("retrieved", [])

    model_name = DEPLOYMENT or DEFAULT_MODEL

    def synthesize_answer() -> tuple[str, List[str]]:
        if not retrieved:
            text = f"Answer: {query}" if query else "No question provided."
            return text, [text]
        doc_summaries = "; ".join(r["text"] for r in retrieved)
        answer = f"Based on docs: {doc_summaries}\n\nAnswer: {query}"[:4000]
        return answer, [answer]

    if API_KEY and BASE_URL:
        client = OpenAI(api_key=API_KEY, base_url=BASE_URL)
        try:
            resp = client.responses.create(model=model_name, input=query)
            text = getattr(resp, "output_text", None)
            if not text:
                text = json.dumps(resp.model_dump(mode="json", exclude_none=True))[:500]
            state["final_answer"] = text
            state["answer_parts"] = [text]
            return state
        except OpenAIError:  # fallback
            state["final_answer"], state["answer_parts"] = synthesize_answer()
            return state
    state["final_answer"], state["answer_parts"] = synthesize_answer()
    return state


# ---------------------------------------------------------------------------
# Build the LangGraph
# ---------------------------------------------------------------------------


def _build_graph():
    graph = StateGraph(RAGState)
    graph.add_node("analyze", analyze_intent)
    graph.add_node("retrieve", retrieve_if_needed)
    graph.add_node("answer", generate_answer)

    graph.add_edge(START, "analyze")
    graph.add_edge("analyze", "retrieve")
    graph.add_edge("retrieve", "answer")
    graph.add_edge("answer", END)
    return graph.compile()


# ---------------------------------------------------------------------------
# Entry Point
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    graph = _build_graph()
    converter = RAGStateConverter()
    from_langgraph(graph, converter).run()