Spaces:
Build error
Build error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import requests
|
| 4 |
+
import json
|
| 5 |
+
from typing import List, Optional
|
| 6 |
+
from langchain.tools import BaseTool
|
| 7 |
+
from langchain.agents import initialize_agent
|
| 8 |
+
from langchain.llms import Ollama
|
| 9 |
+
from langchain.memory import ConversationBufferMemory
|
| 10 |
+
from langchain.agents import AgentType
|
| 11 |
+
|
| 12 |
+
class Tool(BaseModel):
|
| 13 |
+
name: str
|
| 14 |
+
description: str
|
| 15 |
+
function: str
|
| 16 |
+
|
| 17 |
+
class GenerationRequest(BaseModel):
|
| 18 |
+
prompt: str
|
| 19 |
+
max_tokens: int = 100
|
| 20 |
+
temperature: float = 0.7
|
| 21 |
+
tools: Optional[List[Tool]] = None
|
| 22 |
+
|
| 23 |
+
app = FastAPI()
|
| 24 |
+
|
| 25 |
+
OLLAMA_URL = "http://localhost:11434/api/generate"
|
| 26 |
+
|
| 27 |
+
@app.post("/generate")
|
| 28 |
+
async def generate_code(request: GenerationRequest):
|
| 29 |
+
try:
|
| 30 |
+
# Initialize Ollama LLM
|
| 31 |
+
llm = Ollama(
|
| 32 |
+
base_url="http://localhost:11434",
|
| 33 |
+
model="codellama",
|
| 34 |
+
temperature=request.temperature,
|
| 35 |
+
max_tokens=request.max_tokens
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# Initialize memory
|
| 39 |
+
memory = ConversationBufferMemory(memory_key="chat_history")
|
| 40 |
+
|
| 41 |
+
# Initialize tools if provided
|
| 42 |
+
tools = []
|
| 43 |
+
if request.tools:
|
| 44 |
+
for tool in request.tools:
|
| 45 |
+
tools.append(
|
| 46 |
+
BaseTool(
|
| 47 |
+
name=tool.name,
|
| 48 |
+
description=tool.description,
|
| 49 |
+
func=lambda x: eval(tool.function)(x)
|
| 50 |
+
)
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Initialize agent
|
| 54 |
+
agent = initialize_agent(
|
| 55 |
+
tools=tools,
|
| 56 |
+
llm=llm,
|
| 57 |
+
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
|
| 58 |
+
memory=memory
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Generate response
|
| 62 |
+
response = agent.run(request.prompt)
|
| 63 |
+
|
| 64 |
+
return {"generated_code": response}
|
| 65 |
+
except Exception as e:
|
| 66 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
import uvicorn
|
| 70 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|