-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·85 lines (67 loc) · 2.7 KB
/
main.py
File metadata and controls
executable file
·85 lines (67 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import argparse
import os
import sys
from dotenv import load_dotenv
from google import genai
from google.genai import types
from functions.call_function import available_functions, call_function
from config import MAX_ITERS
from prompts import system_prompt
def main():
parser = argparse.ArgumentParser(description="AI Code Assistant")
parser.add_argument("user_prompt", type=str, help="Prompt to send to Gemini")
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
args = parser.parse_args()
load_dotenv()
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
raise RuntimeError("GEMINI_API_KEY environment variable not set")
client = genai.Client(api_key=api_key)
messages = [types.Content(role="user", parts=[types.Part(text=args.user_prompt)])]
if args.verbose:
print(f"User prompt: {args.user_prompt}\n")
for _ in range(MAX_ITERS):
try:
final_response = generate_content(client, messages, args.verbose)
if final_response:
print("Final response:")
print(final_response)
return
except Exception as e:
print(f"Error in generate_content: {e}")
print(f"Maximum iterations ({MAX_ITERS}) reached")
sys.exit(1)
def generate_content(client, messages, verbose):
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=messages,
config=types.GenerateContentConfig(
tools=[available_functions], system_instruction=system_prompt
),
)
if not response.usage_metadata:
raise RuntimeError("Gemini API response appears to be malformed")
if verbose:
print("Prompt tokens:", response.usage_metadata.prompt_token_count)
print("Response tokens:", response.usage_metadata.candidates_token_count)
if response.candidates:
for candidate in response.candidates:
if candidate.content:
messages.append(candidate.content)
if not response.function_calls:
return response.text
function_responses = []
for function_call in response.function_calls:
result = call_function(function_call, verbose)
if (
not result.parts
or not result.parts[0].function_response
or not result.parts[0].function_response.response
):
raise RuntimeError(f"Empty function response for {function_call.name}")
if verbose:
print(f"-> {result.parts[0].function_response.response}")
function_responses.append(result.parts[0])
messages.append(types.Content(role="user", parts=function_responses))
if __name__ == "__main__":
main()