96 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			Lua
		
	
	
	
	
	
			
		
		
	
	
			96 lines
		
	
	
		
			2.1 KiB
		
	
	
	
		
			Lua
		
	
	
	
	
	
| local config = require("gemini.config")
 | |
| local http = require("gemini.http")
 | |
| local chat = require("gemini.chat")  -- Add chat module
 | |
| local M = {}
 | |
| 
 | |
| local function get_api_key()
 | |
| 	return vim.g.gemini_api_key or os.getenv("GEMINI_API_KEY")
 | |
| end
 | |
| 
 | |
| local function create_contents(prompt, context)
 | |
| 	local contents = {}
 | |
| 	
 | |
| 	for _, message in ipairs(chat.get_conversation_history()) do
 | |
| 		table.insert(contents, {
 | |
| 			role = message.role,
 | |
| 			parts = {{text = message.content}}
 | |
| 		})
 | |
| 	end
 | |
| 
 | |
| 	if context then
 | |
| 		table.insert(contents, {
 | |
| 			role = "user",
 | |
| 			parts = {{text = "Context:\n" .. context .. "\n\nQuery: " .. prompt}}
 | |
| 		})
 | |
| 	else
 | |
| 		table.insert(contents, {
 | |
| 			role = "user",
 | |
| 			parts = {{text = prompt}}
 | |
| 		})
 | |
| 	end
 | |
| 
 | |
| 	return contents
 | |
| end
 | |
| 
 | |
| local function store_message(role, content)
 | |
| 	chat.add_message(role, content)
 | |
| end
 | |
| 
 | |
| local function handle_response(result, callback)
 | |
| 	if result.error then
 | |
| 		callback(nil, "API Error: " .. vim.inspect(result.error))
 | |
| 		return
 | |
| 	end
 | |
| 
 | |
| 	if result.candidates and
 | |
| 	   result.candidates[1] and
 | |
| 	   result.candidates[1].content and
 | |
| 	   result.candidates[1].content.parts and
 | |
| 	   result.candidates[1].content.parts[1] and
 | |
| 	   result.candidates[1].content.parts[1].text then
 | |
| 		
 | |
| 		local response_text = result.candidates[1].content.parts[1].text
 | |
| 		store_message("model", response_text)
 | |
| 		callback(response_text)
 | |
| 	else
 | |
| 		callback(nil, "Unexpected response structure")
 | |
| 	end
 | |
| end
 | |
| 
 | |
| function M.get_response(prompt, context, callback)
 | |
| 	local api_key = get_api_key()
 | |
| 	
 | |
| 	if not api_key then
 | |
| 		vim.schedule(function()
 | |
| 			callback(nil, "API key not set")
 | |
| 		end)
 | |
| 		return
 | |
| 	end
 | |
| 
 | |
| 	store_message("user", prompt)
 | |
| 
 | |
| 	local contents = create_contents(prompt, context)
 | |
| 	local payload = vim.json.encode({contents = contents})
 | |
| 	
 | |
| 	local url = string.format(
 | |
| 		config.options.api_url .. "?key=%s",
 | |
| 		config.options.model,
 | |
| 		api_key
 | |
| 	)
 | |
| 
 | |
| 	local request = http.Request.new(url, payload)
 | |
| 	request:execute(function(result, error)
 | |
| 		if error then
 | |
| 			callback(nil, error)
 | |
| 			return
 | |
| 		end
 | |
| 		handle_response(result, callback)
 | |
| 	end)
 | |
| end
 | |
| 
 | |
| function M.clear_conversation()
 | |
| 	chat.clear()  -- This will clear both the buffer and conversation history
 | |
| end
 | |
| 
 | |
| return M
 |