ArjunSoniK commited on
Commit
f032c49
·
0 Parent(s):

chat plus ask api using llama3.1

Browse files
Files changed (2) hide show
  1. app.py +93 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.responses import StreamingResponse
3
+ from langchain_groq import ChatGroq
4
+ from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder
5
+ from langchain_core.messages import SystemMessage
6
+ from langchain.chains.conversation.memory import ConversationBufferMemory
7
+ from langchain.chains import ConversationChain
8
+ from fastapi.middleware.cors import CORSMiddleware
9
+ from dotenv import load_dotenv
10
+ from pydantic import BaseModel
11
+ import os
12
+ import uvicorn
13
+
14
+ load_dotenv()
15
+
16
+ class Chat_input(BaseModel):
17
+ input: str
18
+
19
+ app = FastAPI()
20
+
21
+ app.add_middleware(
22
+ CORSMiddleware,
23
+ allow_origins=["*"],
24
+ allow_credentials=True,
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
28
+
29
+
30
+ llm = ChatGroq(
31
+ model="llama3-70b-8192",
32
+ temperature=0.5,
33
+ max_tokens=None,
34
+ timeout=None,
35
+ max_retries=2,
36
+ api_key=os.getenv("GROQ_API_KEY"),
37
+ )
38
+
39
+ memory = ConversationBufferMemory(k=20, memory_key="chat_history", return_messages=True)
40
+
41
+
42
+ prompt = ChatPromptTemplate.from_messages(
43
+ [
44
+ SystemMessage(content="You are an expert in talking with humans. Human will provide you some input, reply to them with a proper answer."),
45
+ MessagesPlaceholder(variable_name="chat_history"),
46
+ HumanMessagePromptTemplate.from_template("{input}"),
47
+ ]
48
+ )
49
+
50
+
51
+ chain = ConversationChain(
52
+ prompt=prompt,
53
+ llm=llm,
54
+ memory=memory,
55
+ )
56
+
57
+ # Route for chat with history
58
+ @app.post("/chat")
59
+ async def chat(input: Chat_input):
60
+ async def event_stream():
61
+ try:
62
+ async for event in chain.astream_events({"input": input.input}, version="v1"):
63
+ if event["event"] == 'on_chat_model_stream':
64
+ yield event["data"]["chunk"].content
65
+ except Exception as e:
66
+ yield f"Error: {str(e)}"
67
+
68
+ return StreamingResponse(event_stream(), media_type="text/event-stream")
69
+
70
+ # Route for simple Q&A without history
71
+ @app.post("/ask")
72
+ async def ask(input: Chat_input):
73
+ async def event_stream():
74
+ try:
75
+ simple_prompt = ChatPromptTemplate.from_messages(
76
+ [
77
+ SystemMessage(content="You are an expert in answering questions."),
78
+ HumanMessagePromptTemplate.from_template("{input}"),
79
+ ]
80
+ )
81
+
82
+ simple_chain = simple_prompt | llm
83
+
84
+ async for event in simple_chain.astream_events({"input": input.input}, version="v1"):
85
+ if event["event"] == 'on_chat_model_stream':
86
+ yield event["data"]["chunk"].content
87
+ except Exception as e:
88
+ yield f"Error: {str(e)}"
89
+
90
+ return StreamingResponse(event_stream(), media_type="text/event-stream")
91
+
92
+ while True:
93
+ uvicorn.run(app, host="127.0.0.1", port=4000)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ langchain-groq
2
+ langchain_core
3
+ fastapi
4
+ python-dotenv
5
+ pydantic
6
+ uvicorn
7
+ streamlit
8
+ requests