RakeshUtekar
commited on
Upload generate.py
Browse files- generate.py +38 -0
generate.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import openai
|
4 |
+
from dotenv import load_dotenv
|
5 |
+
|
6 |
+
# Load environment variables from .env file
|
7 |
+
load_dotenv()
|
8 |
+
|
9 |
+
# Retrieve the OpenAI API key from the environment variable
|
10 |
+
openai.api_key = os.getenv('OPENAI_API_KEY')
|
11 |
+
|
12 |
+
def generate_response(retrieved_texts, query, max_tokens=150):
|
13 |
+
"""
|
14 |
+
Generates a response based on the retrieved texts and query.
|
15 |
+
|
16 |
+
Args:
|
17 |
+
retrieved_texts (list): List of retrieved text strings.
|
18 |
+
query (str): Query string.
|
19 |
+
max_tokens (int): Maximum number of tokens for the response.
|
20 |
+
|
21 |
+
Returns:
|
22 |
+
str: Generated response.
|
23 |
+
"""
|
24 |
+
context = "\n".join(retrieved_texts)
|
25 |
+
prompt = f"Context: {context}\n\nQuestion: {query}\n\nAnswer:"
|
26 |
+
|
27 |
+
response = openai.ChatCompletion.create(
|
28 |
+
model="gpt-3.5-turbo",
|
29 |
+
messages=[
|
30 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
31 |
+
{"role": "user", "content": prompt}
|
32 |
+
],
|
33 |
+
max_tokens=max_tokens,
|
34 |
+
n=1,
|
35 |
+
stop=None,
|
36 |
+
temperature=0.5,
|
37 |
+
)
|
38 |
+
return response.choices[0].message['content']
|