-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
89 lines (69 loc) · 2.83 KB
/
main.py
File metadata and controls
89 lines (69 loc) · 2.83 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
import sys
import os
from google import genai
from google.genai import types
from dotenv import load_dotenv
from prompts import system_prompt
from call_function import call_function, available_functions
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)]),
]
generate_content(client, messages, verbose)
def generate_content(client, messages, verbose):
for _ in range(5):
response = client.models.generate_content(
model="gemini-2.5-flash",
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)
# Add all candidates to conversation history
for candidate in response.candidates:
messages.append(candidate.content)
# If no function calls, we're done - print the final response
if not response.function_calls:
if response.text:
print(response.text)
return
# Execute all function calls and collect results
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.")
# Add function results to messages and continue the loop
messages.append(types.Content(role="user", parts=function_responses))
# If we reach here, max iterations were hit without a final response
print("Error: Maximum iterations reached without a final response from the model.")
sys.exit(1)
if __name__ == "__main__":
main()