chatpdf 1.0.1

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 9a47d9b3731d5c619f7b0aa8098dc7e5a42540af691c88878d37b592e34425b0
4
+ data.tar.gz: cdf237a65af3119680f7d712f19b73f78d0456ec79d061b1da5d1bada0fe9b2d
5
+ SHA512:
6
+ metadata.gz: fc300f54db07b7969ca5a0507fe6f2d34c6ce62f0eb4d82f622c0155689841239dc3fa6e6a2de81be38cbd19b0272beccfd2d86298f0e35a9d36b32b2286bb1c
7
+ data.tar.gz: 64e146a96eb7a27b8e7fcd5ed1e46a2267413414fc7e85b4cdd416aba520f078108bc7da89f1ef0891e92a16905d1acb667efa8b9692d63329338ac5afc640b0
@@ -0,0 +1,27 @@
1
+ name: Release RubyGem
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ push:
10
+ name: Push gem to RubyGems.org
11
+ runs-on: ubuntu-latest
12
+
13
+ permissions:
14
+ id-token: write
15
+ contents: write
16
+
17
+ steps:
18
+ # Set up
19
+ - uses: actions/checkout@v4
20
+ - name: Set up Ruby
21
+ uses: ruby/setup-ruby@v1
22
+ with:
23
+ bundler-cache: true
24
+ ruby-version: ruby
25
+
26
+ # Release
27
+ - uses: rubygems/release-gem@v1
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ ## [Unreleased]
2
+ - None
3
+
4
+ ## [1.0.1] - 2025-06-03
5
+ - Bump version 1.0.1
6
+
7
+ ## [1.0.0] - 2025-06-03
8
+ - Basic Chatpdf wrapper With Conversation Manager.
9
+
10
+ ## [0.1.0] - 2025-05-28
11
+
12
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ abhishekka3193@gmail.com.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in chatpdf.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
data/Gemfile.lock ADDED
@@ -0,0 +1,43 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ chatpdf (1.0.1)
5
+ httparty (~> 0.23.1)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ csv (3.3.4)
11
+ diff-lcs (1.6.2)
12
+ httparty (0.23.1)
13
+ csv
14
+ mini_mime (>= 1.0.0)
15
+ multi_xml (>= 0.5.2)
16
+ mini_mime (1.1.5)
17
+ multi_xml (0.6.0)
18
+ rake (13.2.1)
19
+ rspec (3.13.1)
20
+ rspec-core (~> 3.13.0)
21
+ rspec-expectations (~> 3.13.0)
22
+ rspec-mocks (~> 3.13.0)
23
+ rspec-core (3.13.4)
24
+ rspec-support (~> 3.13.0)
25
+ rspec-expectations (3.13.5)
26
+ diff-lcs (>= 1.2.0, < 2.0)
27
+ rspec-support (~> 3.13.0)
28
+ rspec-mocks (3.13.5)
29
+ diff-lcs (>= 1.2.0, < 2.0)
30
+ rspec-support (~> 3.13.0)
31
+ rspec-support (3.13.4)
32
+
33
+ PLATFORMS
34
+ arm64-darwin-23
35
+ ruby
36
+
37
+ DEPENDENCIES
38
+ chatpdf!
39
+ rake (~> 13.0)
40
+ rspec (~> 3.0)
41
+
42
+ BUNDLED WITH
43
+ 2.5.22
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Abhishek Kanojia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,235 @@
1
+ # ChatPDF Ruby Gem
2
+
3
+ A Ruby gem for interacting with the ChatPDF API, allowing you to have conversations with your PDF documents.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'chatpdf'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ ```bash
16
+ $ bundle install
17
+ ```
18
+
19
+ Or install it yourself as:
20
+
21
+ ```bash
22
+ gem install chatpdf
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ## Creating The Config File
28
+
29
+ Config file which contains the initializer for Chatpdf can be created manually or by running the following command:
30
+
31
+ ```ruby
32
+ rails g chatpdf:install
33
+ ```
34
+
35
+ This will generate the following file:
36
+
37
+ ```ruby
38
+ # config/initializers/chatpdf_initializer.rb
39
+ Chatpdf.config do |config|
40
+ config.api_key = ENV['CHATPDF_API_KEY']
41
+ end
42
+ ```
43
+
44
+ ## Usage
45
+
46
+
47
+ ### Uploading The PDF file
48
+
49
+ Files can be added in two ways as mentioned in the chatpdf api as well.
50
+
51
+ #### Adding File via upload
52
+ ```ruby
53
+ client = Chatpdf::Client.new
54
+
55
+ file_path = '/path/to/your/file'
56
+
57
+ client.add_pdf(file_path)
58
+ =>
59
+
60
+ {"sourceId"=>"src_XXXXXXXXXXXXXXXX"}
61
+ ```
62
+ #### Adding File via URL
63
+
64
+ ```ruby
65
+ client = Chatpdf::Client.new
66
+
67
+ file_url = 'https://test.com/some/external/file.pdf'
68
+
69
+ client.add_pdf_via_url(file_url)
70
+ =>
71
+
72
+ {"sourceId"=>"src_XXXXXXXXXXXXXXXX"}
73
+ ```
74
+
75
+ ### Chat With PDF
76
+
77
+ #### Chat Message
78
+ Before you could chat with PDF, using the `chat` method available on `Chatpdf::Client` instance.
79
+
80
+ #### Create a Chat Message
81
+
82
+ ```ruby
83
+ message = Chatpdf::Message.new('Your Question Here')
84
+
85
+ message.to_h
86
+ =>
87
+ {
88
+ role: 'user',
89
+ content: 'Your Question Here'
90
+ }
91
+ ```
92
+
93
+ Once `Chatpdf::Message` is created you can now ask question as follows:
94
+
95
+ ```ruby
96
+ client.chat(source_id, [message.to_h])
97
+ =>
98
+ {
99
+ 'content' => 'Answer to your question'
100
+ }
101
+ ```
102
+
103
+ #### Chat with Reference
104
+
105
+ This just returns the page references from the provided PDF along with the response from the chatpdf.
106
+
107
+ ```ruby
108
+ client.chat_with_reference(source_id, [message.to_h])
109
+ =>
110
+ {
111
+ 'content' => 'Answer to your question',
112
+ 'references' => [{ "pageNumber" => 11 }]
113
+ }
114
+ ```
115
+
116
+ ### Chat Stream
117
+ Chatpdf also provides answers in form of stream, with this gem you can use that as well.
118
+
119
+ ```ruby
120
+ client.chat_stream(source_id, [message.to_h]) do |response_chunks|
121
+ puts response_chunks
122
+ end
123
+ ```
124
+
125
+ ### Delete Source
126
+ The source can be deleted with `delete_source` method available on client
127
+
128
+ ```ruby
129
+ client.delete_source([source_ids]) # array of source_ids to be deleted
130
+ =>
131
+ nil
132
+ ```
133
+
134
+ ### Extended Feature of Gem
135
+
136
+ If you want to use easily use the chatpdf gem, extended classes will help you achieve so.
137
+
138
+ ### Creating a Chat Session
139
+
140
+ ```ruby
141
+ file_path = '/path/to/file.pdf'
142
+
143
+ # OR
144
+
145
+ file_url = 'https://example.com/path/to/file.pdf'
146
+
147
+ session = Chatpdf::Session::Conversation.new(file_path: file_path)
148
+
149
+ # OR
150
+
151
+ session = Chatpdf::Session::Conversation.new(file_url: file_url)
152
+
153
+ # OR
154
+
155
+ session = Chatpdf::Session::Conversation.new(source_id: source_id_of_already_uploaded_file)
156
+ ```
157
+ > IMPORTANT: source_id cannot be provided if File path or File Url is provided. This will result in an error `Chatpdf::InvalidSessionInitialization`
158
+
159
+
160
+ ### Asking Questions
161
+
162
+ ```ruby
163
+ session.ask('Your question here')
164
+ => "Your answer here"
165
+ ```
166
+
167
+ With Reference
168
+
169
+ ```ruby
170
+ session.ask('Your question here', references: true)
171
+ => "Your answer here"
172
+ ```
173
+
174
+
175
+ ### Accessing The Asked Questions
176
+ Good thing about session is that it stores the asked questions in the instance itself, at a later point while using sesion, if you want to access the questions you have asked. You can do
177
+
178
+ ```ruby
179
+ session.questions.map(&:to_s)
180
+ =>
181
+ ["Your question here"]
182
+ ```
183
+
184
+ #### Accessing The Asked Question's Answers
185
+
186
+ ```ruby
187
+ session.questions.map { |question| question.answer.to_s }
188
+ =>
189
+ ["Your answer here"]
190
+ ```
191
+
192
+ ### Serialise Questions
193
+ ```ruby
194
+ session.questions.map(&:serialise)
195
+ =>
196
+ [{:id=>"0185bb65-c150-41c5-81a1-5f7f0532d8f2",
197
+ :question=>"Your Question Here",
198
+ :answer=>
199
+ {:id=>"e68c2463-88ed-4bcc-b3a8-00990d4c6cc8",
200
+ :content=>"Your Answer here",
201
+ :references=>[]}}]
202
+ ```
203
+
204
+ ### Serialise the Session
205
+
206
+ ```ruby
207
+ session.serialise
208
+ =>
209
+ {:file_path=>"/Users/abhishekkanojia/Downloads/NAB-AGM.pdf",
210
+ :url=>nil,
211
+ :source_id=>"src_vSixL2t5LY4fNLF4iGZ8f",
212
+ :questions=>
213
+ [{:id=>"0185bb65-c150-41c5-81a1-5f7f0532d8f2",
214
+ :question=>"Your Question Here",
215
+ :answer=>
216
+ {:id=>"e68c2463-88ed-4bcc-b3a8-00990d4c6cc8",
217
+ :content=>
218
+ "Your Answer Here",
219
+ :references=>[]}}]}
220
+ ```
221
+
222
+ ## Error Handling
223
+
224
+ The gem includes several error classes:
225
+
226
+ - `Chatpdf::InvalidConfiguration`: Raised when API key is not set
227
+ - `Chatpdf::InvalidSessionInitialization`: Raised when conversation parameters are invalid
228
+
229
+ ## Contributing
230
+
231
+ Bug reports and pull requests are welcome on GitHub. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](CODE_OF_CONDUCT.md).
232
+
233
+ ## License
234
+
235
+ The gem is available as open source under the terms of the [MIT License](LICENSE.txt).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "chatpdf"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ require "irb"
11
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/chatpdf.gemspec ADDED
@@ -0,0 +1,22 @@
1
+ lib = File.expand_path("../lib", __FILE__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+
4
+ require 'chatpdf/version'
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = "chatpdf"
8
+ s.version = Chatpdf::VERSION
9
+ s.summary = "[WIP] ChatPDF ruby gem around the ChatPDF API"
10
+ s.description = "[WIP] Chatpdf is a ruby gem around the ChatPDF API"
11
+ s.authors = ["Abhishek Kanojia"]
12
+ s.email = "abhishek.kanojia3193@gmail.com"
13
+ s.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
14
+ s.bindir = "exe"
15
+ s.executables = s.files.grep(%r{^exe/}) { |f| File.basename(f) }
16
+ s.homepage = "https://rubygems.org/gems/chatpdf"
17
+ s.license = "MIT"
18
+
19
+ s.add_development_dependency "rspec", "~> 3.12.0"
20
+
21
+ s.add_dependency "httparty", '~> 0.23.1'
22
+ end
@@ -0,0 +1,11 @@
1
+ module Chatpdf
2
+ module Api
3
+ class Base
4
+ attr_reader :client
5
+
6
+ def initialize(client)
7
+ @client = client
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,27 @@
1
+ module Chatpdf
2
+ module Api
3
+ class Chat < Chatpdf::Api::Base
4
+ def chat(source_id, messages = [])
5
+ response = client.request("/chats/message", {
6
+ body: {
7
+ sourceId: source_id,
8
+ messages: messages
9
+ }
10
+ })
11
+
12
+ ResponseHandler.new(response).response_body
13
+ end
14
+
15
+ def chat_with_reference(source_id, messages = [])
16
+ response = client.request("/chats/message", {
17
+ body: {
18
+ referenceSources: true,
19
+ sourceId: source_id,
20
+ messages: messages
21
+ }
22
+ })
23
+ ResponseHandler.new(response).response_body
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,27 @@
1
+ require 'net/http'
2
+ require 'uri'
3
+ require 'json'
4
+
5
+ module Chatpdf
6
+ module Api
7
+ class ChatStream < Chatpdf::Api::Base
8
+ def chat_stream(source_id, messages = [])
9
+ uri = URI.parse(client.endpoint("/chats/message"))
10
+ request = Net::HTTP::Post.new(uri, client.headers)
11
+ request.body = {
12
+ sourceId: source_id,
13
+ messages: messages,
14
+ stream: true
15
+ }.to_json
16
+
17
+ Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
18
+ http.request(request) do |response|
19
+ response.read_body do |chunk|
20
+ yield chunk
21
+ end
22
+ end
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,15 @@
1
+ module Chatpdf
2
+ module Api
3
+ class DeleteSource < Chatpdf::Api::Base
4
+ def delete_source(source_ids = [])
5
+ response = client.request("/sources/delete", {
6
+ body: {
7
+ sources: source_ids
8
+ }
9
+ })
10
+
11
+ ResponseHandler.new(response).response_body
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,27 @@
1
+ module Chatpdf
2
+ module Api
3
+ class FileUpload < Chatpdf::Api::Base
4
+ def add_pdf_via_upload(file_path)
5
+ file = File.new(file_path ,'rb')
6
+ response = client.upload_file("/sources/add-file", {
7
+ body: {
8
+ file: file
9
+ }
10
+ })
11
+ file.close
12
+
13
+ ResponseHandler.new(response).response_body
14
+ end
15
+
16
+ def add_pdf_via_url(url)
17
+ response = client.request("/sources/add-url", {
18
+ body: {
19
+ url: url
20
+ }
21
+ })
22
+
23
+ ResponseHandler.new(response).response_body
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,2 @@
1
+ module Chatpdf
2
+ end
@@ -0,0 +1,41 @@
1
+ require 'httparty'
2
+
3
+ module Chatpdf
4
+ class Client
5
+ BASE_URL = "https://api.chatpdf.com/v1".freeze
6
+
7
+ include Chatpdf::Actionable
8
+
9
+ def initialize
10
+ @api_key = api_key_or_raise
11
+ end
12
+
13
+ def request(path, options = {})
14
+ HTTParty.post(
15
+ endpoint(path),
16
+ headers: headers,
17
+ body: options[:body].to_json
18
+ )
19
+ end
20
+
21
+ def upload_file(path, options = {})
22
+ HTTParty.post(
23
+ endpoint(path),
24
+ headers: { "x-api-key" => @api_key },
25
+ body: options[:body]
26
+ )
27
+ end
28
+
29
+ def endpoint(path)
30
+ BASE_URL + path
31
+ end
32
+
33
+ def headers
34
+ { "x-api-key" => @api_key, "Content-Type" => "application/json" }
35
+ end
36
+
37
+ def api_key_or_raise
38
+ Chatpdf.configuration.api_key || raise(Chatpdf::InvalidConfiguration, "API key is not set")
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,41 @@
1
+ module Chatpdf
2
+ module Actionable
3
+ module InstanceMethods
4
+ def add_pdf(file_path)
5
+ Chatpdf::Api::FileUpload.new(self).add_pdf_via_upload(file_path)
6
+ end
7
+
8
+ def add_pdf_via_url(url)
9
+ Chatpdf::Api::FileUpload.new(self).add_pdf_via_url(url)
10
+ end
11
+
12
+ def chat(source_id, messages)
13
+ Chatpdf::Api::Chat.new(self).chat(
14
+ source_id,
15
+ messages
16
+ )
17
+ end
18
+
19
+ def chat_with_reference(source_id, messages)
20
+ Chatpdf::Api::Chat.new(self).chat_with_reference(
21
+ source_id,
22
+ messages
23
+ )
24
+ end
25
+
26
+ def delete_source(source_ids = [])
27
+ Chatpdf::Api::DeleteSource.new(self).delete_source(source_ids)
28
+ end
29
+
30
+ def chat_stream(source_id, messages)
31
+ Chatpdf::Api::ChatStream.new(self).chat_stream(source_id, messages) do |chunk|
32
+ yield chunk
33
+ end
34
+ end
35
+ end
36
+
37
+ def self.included(klass)
38
+ klass.send(:include, InstanceMethods)
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,9 @@
1
+ module Chatpdf
2
+ class Configuration
3
+ attr_accessor :api_key
4
+
5
+ def initialize
6
+ @api_key = nil
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,7 @@
1
+ module Chatpdf
2
+ class InvalidConfiguration < StandardError
3
+ def initialize(message)
4
+ super(message)
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,7 @@
1
+ module Chatpdf
2
+ class InvalidSessionInitialization < StandardError
3
+ def initialize(message)
4
+ super(message)
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,15 @@
1
+ module Chatpdf
2
+ class Message
3
+ def initialize(content, role: "user")
4
+ @content = content
5
+ @role = role
6
+ end
7
+
8
+ def to_h
9
+ {
10
+ role: @role,
11
+ content: @content,
12
+ }
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,9 @@
1
+ require 'rails/railtie'
2
+
3
+ module Chatpdf
4
+ class Railtie < ::Rails::Railtie
5
+ generators do
6
+ require 'generators/chatpdf/install/install_generator'
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,15 @@
1
+ module Chatpdf
2
+ class ResponseHandler
3
+ def initialize(response)
4
+ @response = response
5
+ end
6
+
7
+ def success?
8
+ @response.ok?
9
+ end
10
+
11
+ def response_body
12
+ @response.parsed_response
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,35 @@
1
+ module Chatpdf
2
+ module Session
3
+ class Answer
4
+ PAGE_NUMBER_KEY = "pageNumber".freeze
5
+ @@_id = 0
6
+
7
+ attr_reader :id, :content
8
+
9
+ def initialize(response = {})
10
+ @content = response["content"]
11
+ @references = response["references"]
12
+ @@_id = Random.uuid
13
+ @id = @@_id
14
+ end
15
+
16
+ def to_s
17
+ @content
18
+ end
19
+
20
+ def references
21
+ return [] if @references.nil?
22
+
23
+ @references.map { |reference| reference[PAGE_NUMBER_KEY] }
24
+ end
25
+
26
+ def serialise
27
+ {
28
+ id: id,
29
+ content: content,
30
+ references: references
31
+ }
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,73 @@
1
+ module Chatpdf
2
+ module Session
3
+ class Conversation
4
+ attr_reader :file_path, :url, :source_id, :questions
5
+
6
+ def initialize(file_path: nil, url: nil, source_id: nil)
7
+ @file_path = file_path
8
+ @url = url
9
+ @questions = []
10
+ @source_id = source_id
11
+ validate_params
12
+ end
13
+
14
+ def ask(question, references: false)
15
+ add_pdf if source_id.nil?
16
+
17
+ question = Question.new(question)
18
+ @questions << question
19
+
20
+ response = client.chat(source_id, [Chatpdf::Message.new("#{question}").to_h]) unless references
21
+ response = client.chat_with_reference(source_id, [Chatpdf::Message.new("#{question}").to_h]) if references
22
+
23
+ question.answer = Answer.new(response)
24
+
25
+ question.answer.to_s
26
+ end
27
+
28
+ def delete_source
29
+ return unless source_id
30
+
31
+ client.delete_source([source_id])
32
+ end
33
+
34
+ def serialise
35
+ {
36
+ file_path: file_path,
37
+ url: url,
38
+ source_id: source_id,
39
+ questions: questions.map(&:serialise)
40
+ }
41
+ end
42
+
43
+ private
44
+
45
+ def client
46
+ @client ||= Chatpdf::Client.new
47
+ end
48
+
49
+ def add_pdf
50
+ if file_path
51
+ response = client.add_pdf(file_path)
52
+ elsif url
53
+ response = client.add_pdf_via_url(url)
54
+ else
55
+ raise Chatpdf::InvalidSessionInitialization, "Either file_path or url or source_id must be provided"
56
+ end
57
+
58
+ @source_id = response["sourceId"]
59
+ @source_id
60
+ end
61
+
62
+ def validate_params
63
+ if !@source_id.nil? && (!@file_path.nil? || !@url.nil?)
64
+ raise Chatpdf::InvalidSessionInitialization, "Invalid parameters: source_id cannot be provided if file_path or url is provided"
65
+ end
66
+
67
+ if @file_path.nil? && @url.nil? && @source_id.nil?
68
+ raise Chatpdf::InvalidSessionInitialization, "Either file_path or url or source_id must be provided"
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,29 @@
1
+ module Chatpdf
2
+ module Session
3
+ class Question
4
+ @@_id = 0
5
+
6
+ attr_reader :id
7
+ attr_accessor :answer
8
+
9
+ def initialize(question)
10
+ @question = question
11
+ @@_id = Random.uuid
12
+ @id = @@_id
13
+ @answer = nil
14
+ end
15
+
16
+ def to_s
17
+ @question
18
+ end
19
+
20
+ def serialise
21
+ {
22
+ id: id,
23
+ question: @question,
24
+ answer: answer.serialise
25
+ }
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Chatpdf
4
+ VERSION = "1.0.1"
5
+ end
data/lib/chatpdf.rb ADDED
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'chatpdf/configuration'
4
+ require 'chatpdf/concerns/actionable'
5
+
6
+ require 'chatpdf/client'
7
+ require 'chatpdf/version'
8
+
9
+ require 'chatpdf/api/base'
10
+ require 'chatpdf/api/file_upload'
11
+ require 'chatpdf/api/chat'
12
+ require 'chatpdf/api/delete_source'
13
+ require 'chatpdf/api/chat_stream'
14
+
15
+ require 'chatpdf/exceptions/invalid_session_initialization'
16
+ require 'chatpdf/exceptions/invalid_configuration'
17
+
18
+ require 'chatpdf/session/question'
19
+ require 'chatpdf/session/answer'
20
+ require 'chatpdf/session/conversation'
21
+ require 'chatpdf/message'
22
+
23
+ require 'chatpdf/response_handler'
24
+
25
+ Gem.find_files("chatpdf/**/*.rb").each { |path| require_relative path }
26
+
27
+ require "chatpdf/railtie" if defined?(Rails)
28
+
29
+
30
+ module Chatpdf
31
+ class << self
32
+ attr_accessor :configuration
33
+ end
34
+
35
+ def self.configure
36
+ self.configuration ||= Configuration.new
37
+ yield(configuration)
38
+ end
39
+ end
@@ -0,0 +1,17 @@
1
+ require "rails/generators"
2
+
3
+ module Chatpdf
4
+ module Generators
5
+ class InstallGenerator < Rails::Generators::Base
6
+
7
+ def create_initializer_file
8
+ create_file "config/initializers/chatpdf_initializer.rb", <<~FILE
9
+ Chatpdf.config do |config|
10
+ config.api_key = ENV['CHATPDF_API_KEY']
11
+ end
12
+ FILE
13
+ end
14
+
15
+ end
16
+ end
17
+ end
metadata ADDED
@@ -0,0 +1,100 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: chatpdf
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Abhishek Kanojia
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rspec
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: 3.12.0
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: 3.12.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: httparty
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: 0.23.1
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: 0.23.1
40
+ description: "[WIP] Chatpdf is a ruby gem around the ChatPDF API"
41
+ email: abhishek.kanojia3193@gmail.com
42
+ executables: []
43
+ extensions: []
44
+ extra_rdoc_files: []
45
+ files:
46
+ - ".github/workflows/release-gem.yml"
47
+ - ".gitignore"
48
+ - ".rspec"
49
+ - CHANGELOG.md
50
+ - CODE_OF_CONDUCT.md
51
+ - Gemfile
52
+ - Gemfile.lock
53
+ - LICENSE.txt
54
+ - README.md
55
+ - Rakefile
56
+ - bin/console
57
+ - bin/setup
58
+ - chatpdf.gemspec
59
+ - lib/chatpdf.rb
60
+ - lib/chatpdf/api/base.rb
61
+ - lib/chatpdf/api/chat.rb
62
+ - lib/chatpdf/api/chat_stream.rb
63
+ - lib/chatpdf/api/delete_source.rb
64
+ - lib/chatpdf/api/file_upload.rb
65
+ - lib/chatpdf/chatpdf.rb
66
+ - lib/chatpdf/client.rb
67
+ - lib/chatpdf/concerns/actionable.rb
68
+ - lib/chatpdf/configuration.rb
69
+ - lib/chatpdf/exceptions/invalid_configuration.rb
70
+ - lib/chatpdf/exceptions/invalid_session_initialization.rb
71
+ - lib/chatpdf/message.rb
72
+ - lib/chatpdf/railtie.rb
73
+ - lib/chatpdf/response_handler.rb
74
+ - lib/chatpdf/session/answer.rb
75
+ - lib/chatpdf/session/conversation.rb
76
+ - lib/chatpdf/session/question.rb
77
+ - lib/chatpdf/version.rb
78
+ - lib/generators/chatpdf/install/install_generator.rb
79
+ homepage: https://rubygems.org/gems/chatpdf
80
+ licenses:
81
+ - MIT
82
+ metadata: {}
83
+ rdoc_options: []
84
+ require_paths:
85
+ - lib
86
+ required_ruby_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '0'
91
+ required_rubygems_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ requirements: []
97
+ rubygems_version: 3.6.7
98
+ specification_version: 4
99
+ summary: "[WIP] ChatPDF ruby gem around the ChatPDF API"
100
+ test_files: []