Spaces:
Sleeping
Sleeping
Ronio Jerico Roque commited on
Commit ·
83a4aff
1
Parent(s): e94f698
Add initial implementation of chatbot with PostgreSQL query tool and environment configuration
Browse filesFiles changed (7)
- .envAdded+1
- __pycache__/app.cpython-313.pycAdded
- agent.pyAdded+59
- app.py+30-7
- mcp_config.jsonAdded+7
- pythonAdded
- requirements.txt+15-4
1OPENAI_API_KEY=sk-proj-G_xZCwWLuIupf0qNUgOGJ7lnZcN-i5xU3p0tMFDntNFn4v-PQrx_cMlJ6medwDjMCu3PDkNLc_T3BlbkFJ6kVCZC3im6xrs4cD4MZ1jtr9PGTqwnENFiD87k4uzR2Jo6bm5E6jp5h_AQVuNiMZq9ajzrzEoA1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859from typing import Annotatedfrom typing_extensions import TypedDictfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.graph.message import add_messagesfrom langchain.chat_models import init_chat_modelimport os
class State(TypedDict): messages: Annotated[list, add_messages]
graph_builder = StateGraph(State)
key = os.getenv("OPENAI_API_KEY")
llm = init_chat_model("openai:gpt-4o-mini")tool = {"type": "web_search_preview"}llm_with_tools = llm.bind_tools( [ { "type": "mcp", "server_label": "clickup_data", "server_url": "http://127.0.0.1:8000", "require_approval": "never", } ] + [tool] )
def chatbot(state: State): return {"messages": [llm_with_tools.invoke(state["messages"])]}
graph_builder.add_node("chatbot", chatbot)graph_builder.add_edge(START, "chatbot")graph_builder.add_edge("chatbot", END)graph = graph_builder.compile()
if __name__ == "__main__": print("Chatbot started! Type 'quit' to exit.") while True: user_input = input("\nYou: ") if user_input.lower() in ['quit', 'exit', 'bye']: print("Goodbye!") break # Create initial state with user message initial_state = { "messages": [{"role": "user", "content": user_input}] } # Run the graph result = graph.invoke(initial_state) # Get the bot's response bot_response = result["messages"][-1].content print(f"Bot: {bot_response}")
123456789101112135 unmodified lines192021222324252627282930313233343536373839404142434445import osfrom fastapi import FastAPI, HTTPExceptionfrom fastapi_mcp import FastApiMCPfrom pydantic import BaseModelfrom typing import Optional# Create a FastAPI instanceapp = FastAPI()# --- Keep this root endpoint for health checks and basic access ---@app.get("/")async def read_root():return {"message": "Server is running and healthy!"}5 unmodified linesclass ToolOutput(BaseModel):result: str@app.post("/tools/echo", operation_id="echo_tool")async def echo_tool(input_data: ToolInput) -> ToolOutput:"""A simple echo tool that returns the input text with a prefix"""try:# Process the inputresult = f"Echo: {input_data.text}"return ToolOutput(result=result)except Exception as e:raise HTTPException(status_code=500, detail=str(e))# Initialize MCP with the tool endpointmcp = FastApiMCP(app,include_operations=["echo_tool"])mcp.mount()if __name__ == "__main__":import uvicorn# Use the PORT environment variable provided by Hugging Face, default to 7860port = int(os.environ.get("PORT", "7860"))uvicorn.run(app, host="0.0.0.0", port=port)1234567891011125 unmodified lines181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import osimport asyncpgfrom fastapi import FastAPI, HTTPExceptionfrom fastapi_mcp import FastApiMCPfrom pydantic import BaseModelfrom typing import Optionalapp = FastAPI()@app.get("/")async def read_root():return {"message": "Server is running and healthy!"}5 unmodified linesclass ToolOutput(BaseModel):result: strclass QueryInput(BaseModel):query: str@app.post("/tools/echo", operation_id="echo_tool")async def echo_tool(input_data: ToolInput) -> ToolOutput:"""A simple echo tool that returns the input text with a prefix"""try:result = f"Echo: {input_data.text}"return ToolOutput(result=result)except Exception as e:raise HTTPException(status_code=500, detail=str(e))@app.post("/tools/query_postgres", operation_id="query_postgres")async def query_postgres(input_data: QueryInput) -> ToolOutput:"""Query PostgreSQL database"""try:# Only allow SELECT queriesif not input_data.query.lower().strip().startswith('select'):return ToolOutput(result="Error: Only SELECT queries are allowed")conn = await asyncpg.connect('postgres://postgres:apple@172.17.21.23:5432/agency_data')rows = await conn.fetch(input_data.query + " LIMIT 10")await conn.close()if not rows:return ToolOutput(result="No results found")results = [dict(row) for row in rows]return ToolOutput(result=f"Found {len(results)} rows: {results}")except Exception as e:return ToolOutput(result=f"Database error: {str(e)}")# Initialize MCP with both toolsmcp = FastApiMCP(app,include_operations=["echo_tool", "query_postgres"])mcp.mount()if __name__ == "__main__":import uvicornport = int(os.environ.get("PORT", "7860"))uvicorn.run(app, host="0.0.0.0", port=port)
1234567{ "mcpServers": { "fastapi-mcp": { "serverUrl": "https://roniorque-fastapi-test-server.hf.space/mcp" } }}1234fastapiuvicornfastapi-mcppydantic123456789101112131415fastapi>=0.104.0fastapi-mcp>=0.1.0uvicorn[standard]>=0.24.0pydantic>=2.5.0asyncpg>=0.29.0psycopg2-binary>=2.9.7sqlalchemy[asyncio]>=2.0.0python-dotenv>=1.0.0httpx>=0.25.0langchain>=0.1.0langchain-community>=0.0.10langchain-core>=0.1.0langchain-openai>=0.3.1langgraph>=0.0.30typing-extensions>=4.8.0
.envAdded+1
__pycache__/app.cpython-313.pycAdded
agent.pyAdded+59
app.py+30-7
mcp_config.jsonAdded+7
pythonAdded
requirements.txt+15-4