Class: Cowrite

Inherits:
Object
  • Object
show all
Defined in:
lib/cowrite.rb,
lib/cowrite/cli.rb,
lib/cowrite/version.rb

Defined Under Namespace

Classes: CLI

Constant Summary collapse

VERSION =
"0.3.0"

Instance Method Summary collapse

Constructor Details

#initialize(url:, api_key:, model:) ⇒ Cowrite

Returns a new instance of Cowrite.



8
9
10
11
12
# File 'lib/cowrite.rb', line 8

def initialize(url:, api_key:, model:)
  @url = url
  @api_key = api_key
  @model = model
end

Instance Method Details

#diffs(prompt, files) ⇒ Object



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
# File 'lib/cowrite.rb', line 37

def diffs(prompt, files)
  # - tried "patch format" but that is often invalid
  # - tied "full fixed content" but that is always missing the fix
  # - need "ONLY" or it adds comments
  # - tried asking for a diff but it's always in the wrong direction or has sublet bugs that make it unusable
  prompt = <<~MSG
    Solve this prompt:
    ```
    #{prompt}
    ```

    By changing the content of these files:
    #{files.map { |f| "#{f}:\n```#{file_read_or_empty f}```" }.join("\n")}

    Reply with ONLY a newline separated list of changes in the format:
    - what range lines from the original content need to be removed as "FILE: <file> LINES: <start>-<end>"
    - changed chunk inside a "```code" block
  MSG

  puts "prompt:#{prompt}" if ENV["DEBUG"]
  answer = send_to_openai(prompt)
  puts "answer:\n#{answer}" if ENV["DEBUG"]

  # - also getting leading "- " since sometimes the model prefixes that
  # - getting any kind of block since sometimes the model uses "```go"
  changes = answer.scan(/-? ?FILE: (\S+) LINES: (\d+)-(\d+)\n```\S+\n(.*?)\n```/m)
  changes.map do |file, start, finish, diff|
    content = file_read_or_empty file
    [file, generate_diff(content, diff, from: Integer(start), to: Integer(finish))]
  end
end

#files(prompt) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/cowrite.rb', line 14

def files(prompt)
  # TODO: ask llm which folders to search when >1k files
  files = `git ls-files`
  abort files unless $?.success?

  prompt = <<~MSG
    Your task is to find files that need to be written or read to solve an LLM-prompt.

    Only reply with a list of files, newline separated, nothing else.

    List of local files: #{files.split("\n").inspect}

    LLM-prompt:
    ```
    #{prompt}
    ```
  MSG
  puts "prompt:#{prompt}" if ENV["DEBUG"]
  answer = send_to_openai(prompt)
  puts "answer:\n#{answer}" if ENV["DEBUG"]
  without_quotes(answer).split("\n").map(&:strip) # llms like to add extra spaces
end