MalikShehram commited on
Commit
47e2273
·
verified ·
1 Parent(s): 05c98e4

Update services/client.py

Browse files
Files changed (1) hide show
  1. services/client.py +68 -71
services/client.py CHANGED
@@ -1,6 +1,4 @@
1
  from concurrent.futures import ThreadPoolExecutor
2
- from multiprocessing.pool import ThreadPool
3
- from pydoc import cli
4
  from openai import OpenAI
5
  import os
6
  from dotenv import load_dotenv
@@ -13,87 +11,86 @@ BASE_URL = "https://api.novita.ai/v3/openai"
13
  MODEL_NAME = "meta-llama/llama-3.2-1b-instruct"
14
 
15
  client = OpenAI(
16
- base_url= BASE_URL,
17
  api_key=os.environ.get("NOVITA_API_KEY"),
18
  )
19
 
20
- def generate_commented_code(code:str, max_token:int):
 
 
 
 
 
 
21
  try:
22
  chat_responses = client.chat.completions.create(
23
- model= MODEL_NAME,
24
- temperature=0.7,
25
- stream= False,
26
- max_tokens= max_token,
27
- messages = [
28
- {
29
- "role": "system",
30
- "content": (
31
- "You are a senior software engineer skilled in writing precise comments only. Follow these instructions strictly:\n\n"
32
- "Identify the programming language used and then do following:\n"
33
- "Add **clear, concise, and professional comments** to the provided code. Include:\n"
34
- "Docstrings for all functions and classes\n"
35
- "Inline comments explaining non-obvious or critical logic\n\n"
36
- "Strictly do not do anything else than writing comments. Stricltly do not add or provide alternative code"
37
-
38
- "Example response:"
39
- '''
40
- def add(a, b):
41
- """
42
- Returns the sum of two numbers.
43
-
44
- Args:
45
- a (int): The first number.
46
- b (int): The second number.
47
-
48
- Returns:
49
- int: The sum of a and b.
50
-
51
- Raises:
52
- TypeError: If either a or b is not an integer.
53
- ValueError: If either a or b is negative.
54
- """
55
- # Check if both inputs are integers
56
- if not isinstance(a, int) or not isinstance(b, int):
57
- raise TypeError("Both inputs must be integers.")
58
- # Check if both inputs are non-negative
59
- if a < 0 or b < 0:
60
- raise ValueError("Both inputs must be non-negative.")
61
 
62
- # Use the built-in addition operator to perform the calculation
63
- # This is more efficient and readable than using a loop or recursive function
64
- return a + b
65
- '''
66
- )
67
- },
 
 
 
 
 
 
 
 
68
  {"role": "user", "content": code}
69
  ]
70
  )
71
-
72
- result = chat_responses.choices[0].message.content
73
- return result
74
  except Exception as ex:
75
- return f"Error generating comments {ex}"
76
 
77
- def generate_documentation(code:str, max_token:int):
 
 
 
 
 
 
78
  try:
79
  chat_responses = client.chat.completions.create(
80
- model= MODEL_NAME,
81
  temperature=0.7,
82
- stream= False,
83
- max_tokens= max_token,
84
- messages = [
85
- {
86
- "role": "system",
87
- "content": (
88
- "You are a senior software engineer skilled in writing structured documentation only. Follow these instructions strictly:\n\n"
89
- "Identify the programming language used and then do following:\n"
90
- "Produce a **strictly formatted JSON** object with:\n"
91
- "name: Function or class name\n"
92
- "description: Brief summary of what it does\n"
93
- "parameters: Dictionary with param name, type, and description\n"
94
- "returns: Return name, type, and description\n"
95
- "exceptions (optional): Raised exceptions with reasons\n"
96
- "examples: Code usage examples with expected output\n\n"
 
 
97
 
98
- "Example response: "
99
- """
 
 
 
 
 
 
1
  from concurrent.futures import ThreadPoolExecutor
 
 
2
  from openai import OpenAI
3
  import os
4
  from dotenv import load_dotenv
 
11
  MODEL_NAME = "meta-llama/llama-3.2-1b-instruct"
12
 
13
  client = OpenAI(
14
+ base_url=BASE_URL,
15
  api_key=os.environ.get("NOVITA_API_KEY"),
16
  )
17
 
18
+ def generate_commented_code(code: str, max_token: int):
19
+ system_prompt = (
20
+ "You are a senior software engineer skilled in writing precise comments only. "
21
+ "Add clear, concise, and professional comments to the provided code. "
22
+ "Include docstrings for all functions/classes and inline comments for complex logic. "
23
+ "Strictly do not add or provide alternative code."
24
+ )
25
  try:
26
  chat_responses = client.chat.completions.create(
27
+ model=MODEL_NAME,
28
+ temperature=0.7,
29
+ stream=False,
30
+ max_tokens=max_token,
31
+ messages=[
32
+ {"role": "system", "content": system_prompt},
33
+ {"role": "user", "content": code}
34
+ ]
35
+ )
36
+ return chat_responses.choices[0].message.content
37
+ except Exception as ex:
38
+ return f"Error generating comments: {ex}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ def generate_documentation(code: str, max_token: int):
41
+ system_prompt = (
42
+ "You are a senior software engineer skilled in writing structured documentation only. "
43
+ "Produce a strictly formatted JSON object with the following keys: "
44
+ "'name', 'description', 'parameters', 'returns', 'exceptions', and 'examples'."
45
+ )
46
+ try:
47
+ chat_responses = client.chat.completions.create(
48
+ model=MODEL_NAME,
49
+ temperature=0.7,
50
+ stream=False,
51
+ max_tokens=max_token,
52
+ messages=[
53
+ {"role": "system", "content": system_prompt},
54
  {"role": "user", "content": code}
55
  ]
56
  )
57
+ return chat_responses.choices[0].message.content
 
 
58
  except Exception as ex:
59
+ return f"Error generating documentation: {ex}"
60
 
61
+ def generate_improved_code(code: str, max_token: int):
62
+ system_prompt = (
63
+ "You are a senior software engineer. Analyze the code for possible improvements. "
64
+ "If optimization is possible, provide a cleaner or more efficient version. "
65
+ "Otherwise, write 'Already optimal'. "
66
+ "Always report the time complexity of both the original and improved versions."
67
+ )
68
  try:
69
  chat_responses = client.chat.completions.create(
70
+ model=MODEL_NAME,
71
  temperature=0.7,
72
+ stream=False,
73
+ max_tokens=max_token,
74
+ messages=[
75
+ {"role": "system", "content": system_prompt},
76
+ {"role": "user", "content": code}
77
+ ]
78
+ )
79
+ return chat_responses.choices[0].message.content
80
+ except Exception as ex:
81
+ return f"Error generating improved code: {ex}"
82
+
83
+ def generate_code_comments_and_docs(code: str, max_token: int = 1024) -> List:
84
+ try:
85
+ with ThreadPoolExecutor() as executor:
86
+ future1 = executor.submit(generate_commented_code, code, max_token)
87
+ future2 = executor.submit(generate_documentation, code, max_token)
88
+ future3 = executor.submit(generate_improved_code, code, max_token)
89
 
90
+ commented = future1.result()
91
+ documentation = future2.result()
92
+ improved = future3.result()
93
+
94
+ return [commented, documentation, improved]
95
+ except Exception as ex:
96
+ return [f"Error generating comments: {ex}", "{}", f"Error: {ex}"]