Spaces:
Running
Running
langserve integration; chatUI adapter
Browse files- Dockerfile +4 -3
- app/main.py +55 -25
- params.cfg +4 -0
Dockerfile
CHANGED
@@ -7,11 +7,12 @@ WORKDIR /app
|
|
7 |
COPY requirements.txt .
|
8 |
RUN pip install --no-cache-dir -r requirements.txt
|
9 |
|
10 |
-
# copy app
|
11 |
COPY app ./app
|
|
|
12 |
|
13 |
-
# expose Gradio
|
14 |
-
EXPOSE 7860
|
15 |
|
16 |
# launch with unbuffered output
|
17 |
CMD ["python", "-u", "app/main.py"]
|
|
|
7 |
COPY requirements.txt .
|
8 |
RUN pip install --no-cache-dir -r requirements.txt
|
9 |
|
10 |
+
# copy app and config files
|
11 |
COPY app ./app
|
12 |
+
COPY params.cfg .
|
13 |
|
14 |
+
# expose both FastAPI and Gradio ports
|
15 |
+
EXPOSE 7860 7861
|
16 |
|
17 |
# launch with unbuffered output
|
18 |
CMD ["python", "-u", "app/main.py"]
|
app/main.py
CHANGED
@@ -1,14 +1,10 @@
|
|
1 |
-
#!/usr/bin/env python3
|
2 |
-
"""
|
3 |
-
Hybrid ChatFed Orchestrator with both Gradio MCP endpoints and LangServe API.
|
4 |
-
Provides MCP compatibility while adding enhanced observability through LangServe.
|
5 |
-
"""
|
6 |
-
|
7 |
import gradio as gr
|
8 |
from fastapi import FastAPI
|
9 |
from langserve import add_routes
|
10 |
from langgraph.graph import StateGraph, START, END
|
11 |
-
from typing import
|
|
|
|
|
12 |
from gradio_client import Client
|
13 |
import uvicorn
|
14 |
import os
|
@@ -18,15 +14,23 @@ from contextlib import asynccontextmanager
|
|
18 |
import io
|
19 |
from PIL import Image
|
20 |
import threading
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
# Configure logging for observability
|
23 |
logging.basicConfig(
|
24 |
level=logging.INFO,
|
25 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
26 |
)
|
27 |
logger = logging.getLogger(__name__)
|
28 |
|
29 |
-
# Define
|
30 |
class GraphState(TypedDict):
|
31 |
query: str
|
32 |
context: str
|
@@ -51,13 +55,13 @@ class ChatFedOutput(TypedDict):
|
|
51 |
result: str
|
52 |
metadata: Dict[str, Any]
|
53 |
|
54 |
-
#
|
55 |
def retrieve_node(state: GraphState) -> GraphState:
|
56 |
start_time = datetime.now()
|
57 |
logger.info(f"Starting retrieval for query: {state['query'][:100]}...")
|
58 |
|
59 |
try:
|
60 |
-
client = Client(
|
61 |
context = client.predict(
|
62 |
query=state["query"],
|
63 |
reports_filter=state.get("reports_filter", ""),
|
@@ -90,13 +94,13 @@ def retrieve_node(state: GraphState) -> GraphState:
|
|
90 |
})
|
91 |
return {"context": "", "metadata": metadata}
|
92 |
|
93 |
-
#
|
94 |
def generate_node(state: GraphState) -> GraphState:
|
95 |
start_time = datetime.now()
|
96 |
logger.info(f"Starting generation for query: {state['query'][:100]}...")
|
97 |
|
98 |
try:
|
99 |
-
client = Client(
|
100 |
result = client.predict(
|
101 |
query=state["query"],
|
102 |
context=state["context"],
|
@@ -126,7 +130,7 @@ def generate_node(state: GraphState) -> GraphState:
|
|
126 |
})
|
127 |
return {"result": f"Error generating response: {str(e)}", "metadata": metadata}
|
128 |
|
129 |
-
# Build
|
130 |
workflow = StateGraph(GraphState)
|
131 |
workflow.add_node("retrieve", retrieve_node)
|
132 |
workflow.add_node("generate", generate_node)
|
@@ -309,7 +313,7 @@ def create_gradio_interface():
|
|
309 |
return demo
|
310 |
|
311 |
# =============================================================================
|
312 |
-
# LANGSERVE API (
|
313 |
# =============================================================================
|
314 |
|
315 |
def process_chatfed_query_langserve(input_data: ChatFedInput) -> ChatFedOutput:
|
@@ -335,12 +339,14 @@ async def lifespan(app: FastAPI):
|
|
335 |
yield
|
336 |
logger.info("π Orchestrator shutting down...")
|
337 |
|
338 |
-
# Create FastAPI app
|
339 |
app = FastAPI(
|
340 |
title="ChatFed Orchestrator - Enhanced API",
|
341 |
version="1.0.0",
|
342 |
description="Enhanced API with observability. MCP endpoints available via Gradio interface.",
|
343 |
-
lifespan=lifespan
|
|
|
|
|
344 |
)
|
345 |
|
346 |
# Health check
|
@@ -352,9 +358,28 @@ async def health_check():
|
|
352 |
"enhanced_api": "available_via_langserve"
|
353 |
}
|
354 |
|
355 |
-
#
|
356 |
-
|
357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
358 |
|
359 |
class ChatMessage(BaseModel):
|
360 |
role: Literal["system", "user", "assistant"]
|
@@ -372,10 +397,15 @@ def chatui_adapter(data: ChatUIInput):
|
|
372 |
result = process_chatfed_query_core(query=last_user_msg)
|
373 |
return {"result": result, "metadata": {"source": "chatfed-langserve-adapter"}}
|
374 |
|
375 |
-
# Add LangServe routes
|
|
|
|
|
|
|
|
|
|
|
376 |
add_routes(
|
377 |
app,
|
378 |
-
|
379 |
path="/chatfed",
|
380 |
input_type=ChatFedInput,
|
381 |
output_type=ChatFedOutput
|
@@ -384,7 +414,7 @@ add_routes(
|
|
384 |
# NEW: ChatUI-compatible LangServe route
|
385 |
add_routes(
|
386 |
app,
|
387 |
-
|
388 |
path="/chatfed-chatui",
|
389 |
input_type=ChatUIInput
|
390 |
)
|
@@ -422,7 +452,7 @@ def run_gradio_server():
|
|
422 |
demo.launch(
|
423 |
server_name="0.0.0.0",
|
424 |
server_port=7861, # Different port from FastAPI
|
425 |
-
mcp_server=True,
|
426 |
show_error=True,
|
427 |
share=False,
|
428 |
quiet=True
|
@@ -439,7 +469,7 @@ if __name__ == "__main__":
|
|
439 |
port = int(os.getenv("PORT", "7860"))
|
440 |
|
441 |
logger.info(f"π Starting FastAPI server on {host}:{port}")
|
442 |
-
logger.info("π Enhanced API with
|
443 |
logger.info("π MCP endpoints available via Gradio on port 7861")
|
444 |
|
445 |
uvicorn.run(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
from fastapi import FastAPI
|
3 |
from langserve import add_routes
|
4 |
from langgraph.graph import StateGraph, START, END
|
5 |
+
from typing import Optional, Dict, Any, List, Literal
|
6 |
+
from typing_extensions import TypedDict
|
7 |
+
from pydantic import BaseModel
|
8 |
from gradio_client import Client
|
9 |
import uvicorn
|
10 |
import os
|
|
|
14 |
import io
|
15 |
from PIL import Image
|
16 |
import threading
|
17 |
+
from langchain_core.runnables import RunnableLambda
|
18 |
+
|
19 |
+
# Local imports
|
20 |
+
from utils import getconfig
|
21 |
+
|
22 |
+
config = getconfig("params.cfg")
|
23 |
+
|
24 |
+
RETRIEVER = config.get("retriever", "RETRIEVER")
|
25 |
+
GENERATOR = config.get("generator", "GENERATOR")
|
26 |
|
|
|
27 |
logging.basicConfig(
|
28 |
level=logging.INFO,
|
29 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
30 |
)
|
31 |
logger = logging.getLogger(__name__)
|
32 |
|
33 |
+
# Define langgraph state schema
|
34 |
class GraphState(TypedDict):
|
35 |
query: str
|
36 |
context: str
|
|
|
55 |
result: str
|
56 |
metadata: Dict[str, Any]
|
57 |
|
58 |
+
# Retriever
|
59 |
def retrieve_node(state: GraphState) -> GraphState:
|
60 |
start_time = datetime.now()
|
61 |
logger.info(f"Starting retrieval for query: {state['query'][:100]}...")
|
62 |
|
63 |
try:
|
64 |
+
client = Client(RETRIEVER)
|
65 |
context = client.predict(
|
66 |
query=state["query"],
|
67 |
reports_filter=state.get("reports_filter", ""),
|
|
|
94 |
})
|
95 |
return {"context": "", "metadata": metadata}
|
96 |
|
97 |
+
# Generator
|
98 |
def generate_node(state: GraphState) -> GraphState:
|
99 |
start_time = datetime.now()
|
100 |
logger.info(f"Starting generation for query: {state['query'][:100]}...")
|
101 |
|
102 |
try:
|
103 |
+
client = Client(GENERATOR)
|
104 |
result = client.predict(
|
105 |
query=state["query"],
|
106 |
context=state["context"],
|
|
|
130 |
})
|
131 |
return {"result": f"Error generating response: {str(e)}", "metadata": metadata}
|
132 |
|
133 |
+
# Build graph
|
134 |
workflow = StateGraph(GraphState)
|
135 |
workflow.add_node("retrieve", retrieve_node)
|
136 |
workflow.add_node("generate", generate_node)
|
|
|
313 |
return demo
|
314 |
|
315 |
# =============================================================================
|
316 |
+
# LANGSERVE API (TELEMETRY)
|
317 |
# =============================================================================
|
318 |
|
319 |
def process_chatfed_query_langserve(input_data: ChatFedInput) -> ChatFedOutput:
|
|
|
339 |
yield
|
340 |
logger.info("π Orchestrator shutting down...")
|
341 |
|
342 |
+
# Create FastAPI app with docs disabled
|
343 |
app = FastAPI(
|
344 |
title="ChatFed Orchestrator - Enhanced API",
|
345 |
version="1.0.0",
|
346 |
description="Enhanced API with observability. MCP endpoints available via Gradio interface.",
|
347 |
+
lifespan=lifespan,
|
348 |
+
docs_url=None, # Disable /docs endpoint
|
349 |
+
redoc_url=None # Disable /redoc endpoint
|
350 |
)
|
351 |
|
352 |
# Health check
|
|
|
358 |
"enhanced_api": "available_via_langserve"
|
359 |
}
|
360 |
|
361 |
+
# Add root endpoint
|
362 |
+
@app.get("/")
|
363 |
+
async def root():
|
364 |
+
return {
|
365 |
+
"message": "ChatFed Orchestrator API",
|
366 |
+
"version": "1.0.0",
|
367 |
+
"endpoints": {
|
368 |
+
"health": "/health",
|
369 |
+
"chatfed": "/chatfed",
|
370 |
+
"chatfed-chatui": "/chatfed-chatui",
|
371 |
+
"process_query": "/process_query"
|
372 |
+
},
|
373 |
+
"gradio_interface": "http://localhost:7861/",
|
374 |
+
"mcp_endpoints": "http://localhost:7861/gradio_api/mcp/sse",
|
375 |
+
"note": "LangServe telemetry enabled - use /chatfed and /chatfed-chatui for enhanced observability"
|
376 |
+
}
|
377 |
+
|
378 |
+
# =============================================================================
|
379 |
+
# CHATUI ADAPTER
|
380 |
+
# =============================================================================
|
381 |
+
|
382 |
+
|
383 |
|
384 |
class ChatMessage(BaseModel):
|
385 |
role: Literal["system", "user", "assistant"]
|
|
|
397 |
result = process_chatfed_query_core(query=last_user_msg)
|
398 |
return {"result": result, "metadata": {"source": "chatfed-langserve-adapter"}}
|
399 |
|
400 |
+
# Add LangServe routes with explicit schema definitions
|
401 |
+
# Convert functions to Runnables
|
402 |
+
process_chatfed_query_runnable = RunnableLambda(process_chatfed_query_langserve)
|
403 |
+
chatui_adapter_runnable = RunnableLambda(chatui_adapter)
|
404 |
+
|
405 |
+
# Add routes with explicit input/output schemas
|
406 |
add_routes(
|
407 |
app,
|
408 |
+
process_chatfed_query_runnable,
|
409 |
path="/chatfed",
|
410 |
input_type=ChatFedInput,
|
411 |
output_type=ChatFedOutput
|
|
|
414 |
# NEW: ChatUI-compatible LangServe route
|
415 |
add_routes(
|
416 |
app,
|
417 |
+
chatui_adapter_runnable,
|
418 |
path="/chatfed-chatui",
|
419 |
input_type=ChatUIInput
|
420 |
)
|
|
|
452 |
demo.launch(
|
453 |
server_name="0.0.0.0",
|
454 |
server_port=7861, # Different port from FastAPI
|
455 |
+
mcp_server=True,
|
456 |
show_error=True,
|
457 |
share=False,
|
458 |
quiet=True
|
|
|
469 |
port = int(os.getenv("PORT", "7860"))
|
470 |
|
471 |
logger.info(f"π Starting FastAPI server on {host}:{port}")
|
472 |
+
logger.info("π Enhanced API with LangServe telemetry available")
|
473 |
logger.info("π MCP endpoints available via Gradio on port 7861")
|
474 |
|
475 |
uvicorn.run(
|
params.cfg
CHANGED
@@ -1 +1,5 @@
|
|
|
|
|
|
1 |
|
|
|
|
|
|
1 |
+
[retriever]
|
2 |
+
RETRIEVER = giz/chatfed_retriever_old
|
3 |
|
4 |
+
[generator]
|
5 |
+
GENERATOR = giz/chatfed_generator
|