llmed 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: debd145812925db06595189b22a442046f375313acce5c50ea3363193c10db78
4
- data.tar.gz: 9f1775faa255b0defd748621e5839c0dc4c6f9a6901450cd01b2517fee647f9a
3
+ metadata.gz: cfcefaf830fc657bad6d938860f95f70aea405b13b57da7a1719cab471124578
4
+ data.tar.gz: ac03fe5eeae6c3e12ea4bb8fc88d98a4a677c9f5ec98196fe03971a071dbb942
5
5
  SHA512:
6
- metadata.gz: b86466b0d9b8bbd4a45aa8657fd4bfb58ae93789495ad5d94d83f3a99ff282881ad5d44a3ad300d9f408b32ec79b4a00c97a13f14d1761d7ba1ee58fa38fe131
7
- data.tar.gz: 6b440fb0abe78ff56d26ba927aa52d961a6ea843ef432614fb36cef3d5378f8fe4c1bc77f7dc3893a7c2a6ecf0c59e919c9fafcc6603d4120d794c3a563a9352
6
+ metadata.gz: a94abc8f536632d61ad6ef1cecc68fcd0afdf73c442efc8293d9a0d002ee7bda9ba93c75ccead84d45f4cecaf04a2e088e3e7fee068f8a51da44b9667ac2c84d
7
+ data.tar.gz: ff66772e445839e293aad316dd515a99c3faf9a55ad355a990d00ae12d8e53b21fdb2537ba2d25713ad23bf479480b60b1bc825ea4f30c4c59dfb7a2cd960288
data/exe/llmed.literate CHANGED
@@ -12,6 +12,7 @@ provider = :like_openai
12
12
  provider_api_key = ENV.fetch('LLMED_PROVIDER_API_KEY', '')
13
13
  provider_model = ENV.fetch('LLMED_PROVIDER_MODEL', 'Qwen/Qwen2.5-Coder-32B-Instruct')
14
14
  provider_uri_base = ENV.fetch('LLMED_PROVIDER_URI_BASE', 'https://api.together.xyz/v1')
15
+ provider_retries = nil
15
16
  output_file = 'a.out.ollmed'
16
17
 
17
18
  template = <<~TMP
@@ -100,6 +101,8 @@ LLMed::LiterateProgramming.execute(source_code, output_file: output_file) do |co
100
101
  provider_model = v
101
102
  when :llm_provider_uri_base
102
103
  provider_uri_base = v
104
+ when :llm_provider_retries
105
+ provider_retries = v
103
106
  end
104
107
  end
105
108
 
@@ -112,6 +115,7 @@ LLMed::LiterateProgramming.execute(source_code, output_file: output_file) do |co
112
115
  logger.info "LLM Provider: #{provider} Model: #{provider_model} URI Base: #{provider_uri_base}"
113
116
 
114
117
  llmed.set_llm provider: provider, api_key: provider_api_key, model: provider_model, options: {uri_base: provider_uri_base}
118
+ llmed.set_llm_provider_retries(provider_retries) if provider_retries
115
119
  llmed.application('literate_programming', **application_args) do
116
120
  contexts.each do |lcontext|
117
121
  context(lcontext[:title]) { lcontext[:content] }
data/lib/llm.rb CHANGED
@@ -2,10 +2,15 @@ require 'openai'
2
2
  require 'langchain'
3
3
  require 'open3'
4
4
  require 'tempfile'
5
+ require 'tmpdir'
5
6
 
6
7
  Langchain.logger.level = Logger::ERROR
7
8
 
8
9
  class LLMed
10
+ # Transient, re-sample-fixable failure of a provider response
11
+ # (empty output, invalid syntax, clean transport failure).
12
+ class RetryableError < StandardError; end
13
+
9
14
  module LLM
10
15
  module Message
11
16
  System = Struct.new(:content)
@@ -22,37 +27,67 @@ class LLMed
22
27
 
23
28
  module SyntaxCheck
24
29
  PYTHON_CHECK_CODE = "import sys; compile(open(sys.argv[1]).read(), 'check', 'exec')".freeze
25
-
26
30
  CHECKERS = {
27
- 'ruby' => ->(path) { ['ruby', '-c', path] },
28
- 'node' => ->(path) { ['node', '--check', path] },
29
- 'javascript' => ->(path) { ['node', '--check', path] },
30
- 'python' => ->(path) { ['python3', '-c', PYTHON_CHECK_CODE, path] },
31
- 'python3' => ->(path) { ['python3', '-c', PYTHON_CHECK_CODE, path] }
31
+ 'ruby' => ->(path, _tmpdir) { ['ruby', '-c', path] },
32
+ 'node' => ->(path, _tmpdir) { ['node', '--check', path] },
33
+ 'javascript' => ->(path, _tmpdir) { ['node', '--check', path] },
34
+ 'python' => ->(path, _tmpdir) { ['python3', '-c', PYTHON_CHECK_CODE, path] },
35
+ 'python3' => ->(path, _tmpdir) { ['python3', '-c', PYTHON_CHECK_CODE, path] },
36
+ 'rust' => ->(path, tmpdir) { ['rustc', '--emit=metadata', '--out-dir', tmpdir, path] },
37
+ 'c' => ->(path, _tmpdir) { ['gcc', '-fsyntax-only', path] }
32
38
  }.freeze
33
39
 
34
40
  module_function
35
41
 
36
42
  def validate!(language, source, logger)
43
+ return validate_java!(source, logger) if language.to_s.downcase == 'java'
44
+
37
45
  checker = CHECKERS[language.to_s.downcase]
38
46
  unless checker
39
47
  logger.warn("syntax checker unavailable for #{language}")
40
48
  return true
41
49
  end
42
50
 
43
- Tempfile.create(['llmed-syntax-check']) do |tmpfile|
44
- tmpfile.write(source.to_s)
45
- tmpfile.flush
46
- stdout, stderr, status = Open3.capture3(*checker.call(tmpfile.path))
51
+ Dir.mktmpdir('llmed-syntax-check') do |tmpdir|
52
+ # gcc -fsyntax-only only recognizes *.c inputs; other checkers are extension-agnostic.
53
+ suffix = language.to_s.downcase == 'c' ? '.c' : ''
54
+ Tempfile.create(['llmed-syntax-check', suffix]) do |tmpfile|
55
+ tmpfile.write(source.to_s)
56
+ tmpfile.flush
57
+ stdout, stderr, status = Open3.capture3(*checker.call(tmpfile.path, tmpdir))
58
+ unless status.success?
59
+ output = [stderr, stdout].compact.join.strip
60
+ logger.error("syntax check failed for #{language}: #{output.lines.last(5).join}")
61
+ raise RetryableError, "syntax check failed for #{language}: #{output.lines.first.to_s.strip}"
62
+ end
63
+ end
64
+ end
65
+ true
66
+ rescue Errno::ENOENT, Errno::EACCES => e
67
+ logger.warn("syntax checker unavailable for #{language}: #{e.message}")
68
+ true
69
+ end
70
+
71
+ # A top-level PUBLIC java class must live in a file named exactly
72
+ # <ClassName>.java, so a generic temp name makes javac fail for
73
+ # reasons unrelated to the source.
74
+ def validate_java!(source, logger)
75
+ class_name = source.to_s[/public\s+class\s+(\w+)/, 1] || 'LlmedSyntaxCheck'
76
+ Dir.mktmpdir('llmed-syntax-check') do |tmpdir|
77
+ tmpfile = File.join(tmpdir, "#{class_name}.java")
78
+ File.write(tmpfile, source.to_s)
79
+ classes_dir = File.join(tmpdir, 'classes')
80
+ FileUtils.mkdir_p(classes_dir)
81
+ stdout, stderr, status = Open3.capture3('javac', '-d', classes_dir, tmpfile)
47
82
  unless status.success?
48
83
  output = [stderr, stdout].compact.join.strip
49
- logger.error("syntax check failed for #{language}: #{output.lines.last(5).join}")
50
- raise "syntax check failed for #{language}: #{output.lines.first.to_s.strip}"
84
+ logger.error("syntax check failed for java: #{output.lines.last(5).join}")
85
+ raise RetryableError, "syntax check failed for java: #{output.lines.first.to_s.strip}"
51
86
  end
52
87
  end
53
88
  true
54
89
  rescue Errno::ENOENT, Errno::EACCES => e
55
- logger.warn("syntax checker unavailable for #{language}: #{e.message}")
90
+ logger.warn("syntax checker unavailable for java: #{e.message}")
56
91
  true
57
92
  end
58
93
  end
@@ -64,7 +99,7 @@ class LLMed
64
99
  ].join('|').freeze
65
100
 
66
101
  def source_code(content)
67
- content = content.gsub('```', '').sub(/^(node(js)?|javascript|ruby|python(\d*)|elixir|bash|html|go|c(pp)?)([ \t]*\n)/, '')
102
+ content = content.gsub('```', '').sub(/^(node(js)?|javascript|java|ruby|python(\d*)|elixir|bash|html|go|c(pp)?|rust)([ \t]*\n)/, '')
68
103
  content.gsub(/^[ \t]*(?:#{BARE_LANGUAGE_LINE})[ \t]*\n/i, '')
69
104
  .sub(/(?:\A|(?<=\n))[ \t]*(?:#{BARE_LANGUAGE_LINE})[ \t]*\z/i, '')
70
105
  end
@@ -74,6 +109,12 @@ class LLMed
74
109
 
75
110
  DEFAULT_URI_BASE = "https://api.openai.com/".freeze
76
111
  MAX_TOKENS = 8192
112
+ # Clean transport failures (connection refused/reset, timeouts, 5xx)
113
+ # are transient and re-samplable; HTTP 4xx (auth, bad request) are not.
114
+ RETRYABLE_TRANSPORT_ERRORS = [
115
+ Faraday::ConnectionFailed,
116
+ Faraday::ServerError
117
+ ].freeze
77
118
 
78
119
  include SourceCodeScrubbing
79
120
  private :source_code
@@ -94,20 +135,31 @@ class LLMed
94
135
  end
95
136
 
96
137
  start = Time.now
97
- llm_response = @llm.chat(messages: messages, max_tokens: MAX_TOKENS)
138
+ begin
139
+ llm_response = @llm.chat(messages: messages, max_tokens: MAX_TOKENS)
140
+ rescue *RETRYABLE_TRANSPORT_ERRORS => e
141
+ @logger.error("provider transport failure: #{e.message}")
142
+ raise RetryableError, "transport failure calling #{provider}: #{e.message}"
143
+ end
98
144
  warn_token_limits(llm_response)
99
145
 
146
+ content = llm_response.chat_completion
147
+ if content.nil? || content.to_s.strip.empty?
148
+ @logger.error("provider returned empty response content")
149
+ raise RetryableError, "empty response from #{provider}"
150
+ end
151
+
100
152
  stop = Time.now
101
153
  Response.new({ provider: provider,
102
154
  model: @llm.chat_parameters[:model],
103
155
  duration_seconds: stop.to_i - start.to_i,
104
- source_code: source_code(llm_response.chat_completion),
156
+ source_code: source_code(content),
105
157
  total_tokens: llm_response.total_tokens })
106
158
  end
107
159
 
108
160
  private
109
161
  def warn_token_limits(llm_response)
110
- if llm_response.completion_tokens >= MAX_TOKENS
162
+ if llm_response.completion_tokens.to_i >= MAX_TOKENS
111
163
  @logger.warn("POSSIBLE INCONSISTENCY COMPLETED TOKENS REACHED MAX TOKENS #{MAX_TOKENS}")
112
164
  end
113
165
  end
@@ -186,10 +238,14 @@ class LLMed
186
238
  stop = Time.now
187
239
 
188
240
  cleaned = status.success? ? source_code(stdout) : ''
189
- if !status.success? || cleaned.strip.empty?
190
- @logger.error("opencode run failed (exit: #{status.success? ? 'success but empty output' : status.exitstatus}): #{stderr.to_s.lines.last(10).join}")
241
+ if !status.success?
242
+ @logger.error("opencode run failed (exit: #{status.exitstatus}): #{stderr.to_s.lines.last(10).join}")
191
243
  raise "opencode run failed for model #{@model}"
192
244
  end
245
+ if cleaned.strip.empty?
246
+ @logger.error("opencode run failed (exit: success but empty output): #{stderr.to_s.lines.last(10).join}")
247
+ raise RetryableError, "opencode run failed for model #{@model}"
248
+ end
193
249
 
194
250
  Response.new({ provider: :opencode,
195
251
  model: @model,
@@ -26,7 +26,7 @@ class LLMed
26
26
 
27
27
  def code_comment(language)
28
28
  { ruby: ['#', ''], node: ['//', ''], elixir: ['#', ''], bash: ['#', ''], python: ['#', ''], go: ['//', ''], javascript: ['//', ''], c: ['//', ''],
29
- cpp: ['//', ''], html: ['<!--', '-->'] }.fetch(language)
29
+ cpp: ['//', ''], rust: ['//', ''], java: ['//', ''], html: ['<!--', '-->'] }.fetch(language)
30
30
  end
31
31
  end
32
32
 
@@ -3,6 +3,8 @@
3
3
 
4
4
  class LLMed
5
5
  class Configuration
6
+ DEFAULT_LLM_RETRIES = 2
7
+
6
8
  def initialize(logger:)
7
9
  @logger = logger
8
10
  # Manual tested, pass 5 times execution
@@ -94,6 +96,25 @@ class LLMed
94
96
  @provider_options = options
95
97
  end
96
98
 
99
+ # Stored set_llm options, e.g. { uri_base: ..., retries: N }
100
+ def provider_options
101
+ @provider_options || {}
102
+ end
103
+
104
+ # Literate directive `#!environment llm_provider_retries N`
105
+ def set_llm_provider_retries(retries)
106
+ @llm_provider_retries = Integer(retries)
107
+ end
108
+
109
+ # Number of provider re-samples allowed; the doc directive wins over
110
+ # set_llm options when both are present.
111
+ def llm_retries
112
+ return @llm_provider_retries unless @llm_provider_retries.nil?
113
+ return Integer(provider_options[:retries]) if provider_options.key?(:retries)
114
+
115
+ DEFAULT_LLM_RETRIES
116
+ end
117
+
97
118
  def language(main)
98
119
  lang = main || @language
99
120
  raise 'Please assign a language to the application or general with the function set_languag' if lang.nil?
data/lib/llmed.rb CHANGED
@@ -32,6 +32,8 @@ class LLMed
32
32
  def_delegator :@configuration, :set_llm, :set_llm
33
33
  # changes default prompt
34
34
  def_delegator :@configuration, :set_prompt, :set_prompt
35
+ # literate directive `#!environment llm_provider_retries N`
36
+ def_delegator :@configuration, :set_llm_provider_retries, :set_llm_provider_retries
35
37
 
36
38
  def application(name, output_file:, language: nil, release: nil, output_dir: nil, release_dir: nil, &block)
37
39
  @app = Application.new(
@@ -70,23 +72,37 @@ class LLMed
70
72
  app.evaluate
71
73
  app.prepare_snapshot
72
74
  if app.rebuild?
73
- llm = @configuration.llm
75
+ compile_with_retries(app)
76
+ else
77
+ @logger.info("APPLICATION #{app.name} NOT CHANGES DETECTED")
78
+ end
79
+ end
74
80
 
75
- messages = [LLMed::LLM::Message::System.new(app.system_prompt(@configuration))]
76
- app.contexts.each do |ctx|
77
- next if ctx.skip?
81
+ def compile_with_retries(app)
82
+ llm = @configuration.llm
78
83
 
79
- messages << LLMed::LLM::Message::User.new(ctx.message)
80
- end
84
+ messages = [LLMed::LLM::Message::System.new(app.system_prompt(@configuration))]
85
+ app.contexts.each do |ctx|
86
+ next if ctx.skip?
81
87
 
82
- llm_response = llm.chat(messages: messages)
83
- @logger.info("APPLICATION #{app.name} TOTAL TOKENS #{llm_response.total_tokens}")
84
- LLMed::LLM::SyntaxCheck.validate!(app.language.to_s, llm_response.source_code, @logger) unless llm_response.provider == :test
85
- app.patch_or_create(llm_response.source_code)
86
- app.write_statistics(llm_response)
87
- app.notify("COMPILE DONE #{llm_response.duration_seconds}")
88
- else
89
- @logger.info("APPLICATION #{app.name} NOT CHANGES DETECTED")
88
+ messages << LLMed::LLM::Message::User.new(ctx.message)
89
+ end
90
+
91
+ attempts = @configuration.llm_retries + 1
92
+ (1..attempts).each do |attempt|
93
+ begin
94
+ llm_response = llm.chat(messages: messages)
95
+ @logger.info("APPLICATION #{app.name} TOTAL TOKENS #{llm_response.total_tokens}")
96
+ LLMed::LLM::SyntaxCheck.validate!(app.language.to_s, llm_response.source_code, @logger) unless llm_response.provider == :test
97
+ app.patch_or_create(llm_response.source_code)
98
+ app.write_statistics(llm_response)
99
+ app.notify("COMPILE DONE #{llm_response.duration_seconds}")
100
+ return
101
+ rescue RetryableError => e
102
+ raise if attempt == attempts
103
+
104
+ @logger.warn("APPLICATION #{app.name} RETRY #{attempt}/#{attempts} after: #{e.message}")
105
+ end
90
106
  end
91
107
  end
92
108
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: llmed
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.1
4
+ version: 0.7.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jovany Leandro G.C
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-11-21 00:00:00.000000000 Z
11
+ date: 2026-11-22 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: langchainrb