VishnuRamDebyez commited on
Commit
8550cf4
·
verified ·
1 Parent(s): 285a245

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -73
app.py CHANGED
@@ -1,85 +1,65 @@
 
 
1
  import os
2
- import requests
3
  from dotenv import load_dotenv
4
- from typing import List, Dict
5
- import json
6
 
7
- # Load environment variables (e.g., API keys)
8
  load_dotenv()
9
 
10
- class CSLAssistant:
11
- def __init__(self):
12
- self.api_token = os.getenv("TOKEN")
13
- self.api_url = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct"
14
- self.headers = {"Authorization": f"Bearer {self.api_token}"}
15
 
16
- def get_system_prompt(self) -> str:
17
- return """
18
- Identity & Purpose:
19
- You are CSL Assistant, the official AI assistant for Cochin Shipyard Limited.
20
- You specialize in providing information about shipbuilding, marine engineering,
21
- and Cochin Shipyard's capabilities and services.
22
 
23
- Guidelines:
24
- 1. Provide accurate information about CSL's shipbuilding capabilities
25
- 2. Be professional and courteous in all interactions
26
- 3. If unsure about specific details, acknowledge limitations
27
- 4. Focus on publicly available information about CSL
28
- """
29
 
30
- def get_prompt_template(self, customer_message: str) -> str:
31
- return f"{self.get_system_prompt()}\n\nCustomer Query: {customer_message}"
32
 
33
- def get_response(self, prompt: str) -> str:
34
- try:
35
- # Prepare the payload
36
- payload = {
37
- "inputs": self.get_prompt_template(prompt),
38
- "parameters": {
39
- "max_new_tokens": 3000,
40
- "temperature": 0.5,
41
- "return_full_text": False
42
- }
43
- }
44
 
45
- # Make the API request
46
- response = requests.post(
47
- self.api_url,
48
- headers=self.headers,
49
- json=payload
50
- )
 
 
 
 
 
 
51
 
52
- # Check if the request was successful
53
- response.raise_for_status()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
- # Parse the response
56
- result = response.json()
57
-
58
- if isinstance(result, list) and len(result) > 0:
59
- return result[0].get('generated_text', '').strip()
60
-
61
- return "Sorry, I couldn't generate a response right now."
62
-
63
- except requests.exceptions.RequestException as e:
64
- return f"API Request Error: {str(e)}"
65
- except json.JSONDecodeError:
66
- return "Error: Invalid response from the API"
67
- except Exception as e:
68
- return f"An unexpected error occurred: {str(e)}"
69
-
70
- def main():
71
- assistant = CSLAssistant()
72
-
73
- # Example queries
74
- test_queries = [
75
- "What types of ships do you build?",
76
- "What is your shipyard's capacity?",
77
- "Tell me about your recent projects"
78
- ]
79
-
80
- for query in test_queries:
81
- print(f"\nQuery: {query}")
82
- print("Response:", assistant.get_response(query))
83
-
84
- if __name__ == "__main__":
85
- main()
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
  import os
4
+ from openai import OpenAI
5
  from dotenv import load_dotenv
6
+ from typing import List, Optional
 
7
 
8
+ # Load environment variables
9
  load_dotenv()
10
 
11
+ app = FastAPI(title="Debyez Chatbot API")
 
 
 
 
12
 
13
+ # Initialize OpenAI client
14
+ client = OpenAI(
15
+ base_url="https://api-inference.huggingface.co/v1",
16
+ api_key=os.getenv("TOKEN")
17
+ )
 
18
 
19
+ class Message(BaseModel):
20
+ role: str
21
+ content: str
 
 
 
22
 
23
+ class ChatRequest(BaseModel):
24
+ messages: List[Message]
25
 
26
+ class ChatResponse(BaseModel):
27
+ response: str
 
 
 
 
 
 
 
 
 
28
 
29
+ def get_debyez_prompt_template(customer_message: str) -> str:
30
+ return f"""
31
+ You are a friendly and helpful virtual assistant for Debyez, a company specializing in
32
+ cutting-edge AI technology service specializing in Generative AI solutions. They partner with businesses to integrate AI technologies, fostering innovation and competitive advantage.
33
+ with services Generative AI Consulting, AI chatbot development, Custom LLM development, and ChatGPT integration service. Debyez strives to empower
34
+ businesses of all sizes, including smaller companies, with the benefits and accessibility of AI.
35
+ Your goal is to provide excellent customer service and build rapport with our customers.
36
+ Be knowledgeable about our products, services, and policies. If you are uncertain about something, it is
37
+ better to say that you will find out the information rather than providing incorrect details.
38
+ Here's the latest message from the customer: '{customer_message}'
39
+ Respond in a way that is warm, professional, and relevant to the customer's needs.
40
+ """
41
 
42
+ @app.post("/chat", response_model=ChatResponse)
43
+ async def chat_endpoint(request: ChatRequest):
44
+ try:
45
+ # Process messages with the template
46
+ formatted_messages = [
47
+ {"role": msg.role, "content": get_debyez_prompt_template(msg.content)}
48
+ for msg in request.messages
49
+ ]
50
+
51
+ # Create chat completion
52
+ completion = client.chat.completions.create(
53
+ model="meta-llama/Meta-Llama-3-8B-Instruct",
54
+ messages=formatted_messages,
55
+ temperature=0.5,
56
+ max_tokens=3000,
57
+ )
58
+
59
+ return ChatResponse(response=completion.choices[0].message.content)
60
+ except Exception as e:
61
+ raise HTTPException(status_code=500, detail=str(e))
62
 
63
+ @app.get("/health")
64
+ async def health_check():
65
+ return {"status": "healthy"}