-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
101 lines (79 loc) · 2.84 KB
/
main.py
File metadata and controls
101 lines (79 loc) · 2.84 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import os
import sys
from dotenv import load_dotenv
from google import genai
from google.genai import types
from call_function import available_functions, call_function
from config import MAX_ITERS
from prompts import system_prompt
def main():
load_dotenv()
verbose = "--verbose" in sys.argv
args = []
for arg in sys.argv[1:]:
if not arg.startswith("--"):
args.append(arg)
if not args:
print("AI Code Assistant")
print('\nUsage: python main.py "your prompt here" [--verbose]')
print('Example: python main.py "How do I fix the calculator?"')
sys.exit(1)
api_key = os.environ.get("GEMINI_API_KEY")
client = genai.Client(api_key=api_key)
user_prompt = " ".join(args)
if verbose:
print(f"User prompt: {user_prompt}\n")
messages = [
types.Content(role="user", parts=[types.Part(text=user_prompt)]),
]
iters = 0
while True:
iters += 1
if iters > MAX_ITERS:
print(f"Maximum iterations ({MAX_ITERS}) reached.")
sys.exit(1)
try:
maybe_final_response = generate_content(client, messages, verbose)
if maybe_final_response:
print("Final response:")
print(maybe_final_response)
break
except Exception as e:
print(f"Error in generate_content: {e}")
def generate_content(client, messages, verbose):
response = client.models.generate_content(
model="gemini-2.0-flash-001",
contents=messages,
config=types.GenerateContentConfig(
tools=[available_functions], system_instruction=system_prompt
),
)
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:
function_call_content = candidate.content
messages.append(function_call_content)
if not response.function_calls:
return response.text
function_responses = []
for function_call_part in response.function_calls:
function_call_result = call_function(function_call_part, verbose)
if (
not function_call_result.parts
or not function_call_result.parts[0].function_response
):
raise Exception("empty function call result")
if verbose:
print(
f"-> {function_call_result.parts[0].function_response.response}"
)
function_responses.append(function_call_result.parts[0])
if not function_responses:
raise Exception("no function responses generated, exiting.")
messages.append(types.Content(role="user", parts=function_responses))
if __name__ == "__main__":
main()