Feat/add ruby sdk (#583)

This commit is contained in:
crazywoola 2023-07-18 10:18:58 +08:00 committed by GitHub
parent ecd6cbaee6
commit cb6e73347e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 460 additions and 2 deletions

View File

@ -20,16 +20,20 @@ export const routes = {
},
getConversationMessages: {
method: "GET",
url: () => "/messages",
url: () => `/messages`,
},
getConversations: {
method: "GET",
url: () => "/conversations",
url: () => `/conversations`,
},
renameConversation: {
method: "PATCH",
url: (conversation_id) => `/conversations/${conversation_id}`,
},
deleteConversation: {
method: "DELETE",
url: (conversation_id) => `/conversations/${conversation_id}`,
},
};
export class DifyClient {
@ -185,4 +189,13 @@ export class ChatClient extends DifyClient {
data
);
}
deleteConversation(conversation_id, user) {
const data = { user };
return this.sendRequest(
routes.deleteConversation.method,
routes.deleteConversation.url(conversation_id),
data
);
}
}

View File

@ -0,0 +1,18 @@
name: Ruby
on: [push,pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.0.0
- name: Run the default task
run: |
gem install bundler -v 2.2.3
bundle install
bundle exec rake

8
sdks/ruby-client/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/

View File

@ -0,0 +1,10 @@
Style/StringLiterals:
Enabled: true
EnforcedStyle: double_quotes
Style/StringLiteralsInInterpolation:
Enabled: true
EnforcedStyle: double_quotes
Layout/LineLength:
Max: 120

View File

@ -0,0 +1,84 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at 427733928@qq.com. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.

14
sdks/ruby-client/Gemfile Normal file
View File

@ -0,0 +1,14 @@
# frozen_string_literal: true
source "https://rubygems.org"
# Specify your gem's dependencies in dify_client.gemspec
gemspec
gem "rake", "~> 13.0"
gem "minitest", "~> 5.0"
gem "rubocop", "~> 0.80"
gem 'webmock'

View File

@ -0,0 +1,55 @@
PATH
remote: .
specs:
dify_client (0.1.0)
GEM
remote: https://rubygems.org/
specs:
addressable (2.8.4)
public_suffix (>= 2.0.2, < 6.0)
ast (2.4.2)
crack (0.4.5)
rexml
hashdiff (1.0.1)
minitest (5.18.1)
parallel (1.23.0)
parser (3.2.2.3)
ast (~> 2.4.1)
racc
public_suffix (5.0.3)
racc (1.7.1)
rainbow (3.1.1)
rake (13.0.6)
regexp_parser (2.8.1)
rexml (3.2.5)
rubocop (0.93.1)
parallel (~> 1.10)
parser (>= 2.7.1.5)
rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 1.8)
rexml
rubocop-ast (>= 0.6.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 1.4.0, < 2.0)
rubocop-ast (1.29.0)
parser (>= 3.2.1.0)
ruby-progressbar (1.13.0)
unicode-display_width (1.8.0)
webmock (3.18.1)
addressable (>= 2.8.0)
crack (>= 0.3.2)
hashdiff (>= 0.4.0, < 2.0.0)
PLATFORMS
arm64-darwin-21
DEPENDENCIES
dify_client!
minitest (~> 5.0)
rake (~> 13.0)
rubocop (~> 0.80)
webmock
BUNDLED WITH
2.2.3

View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2023 crazywoola
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

111
sdks/ruby-client/README.md Normal file
View File

@ -0,0 +1,111 @@
# DifyClient
Welcome to the DifyClient gem! This gem provides a Ruby client for interacting with the Dify.ai API. It allows you to perform various actions such as sending requests, providing feedback, creating completion messages, managing conversations, and more.
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'dify_client'
```
And then execute:
$ bundle install
Or install it yourself as:
$ gem install dify_client
## Usage
To use the DifyClient gem, follow these steps:
1 Require the gem:
```ruby
require 'dify_client'
```
2 Create a new client instance:
```ruby
api_key = 'YOUR_API_KEY'
client = DifyClient::Client.new(api_key)
```
3 Use the available methods to interact with the Dify.ai API. Here are the methods provided by the DifyClient::Client class:
### Update API Key
```ruby
client.update_api_key('NEW_API_KEY')
```
Updates the API key used by the client.
### Message Feedback
```ruby
client.message_feedback(message_id, rating, user)
```
Submits feedback for a specific message identified by `message_id`. The `rating` parameter should be the rating value, and `user` is the user identifier.
### Get Application Parameters
```ruby
client.get_application_parameters(user)
```
### Create Completion Message
```ruby
client.create_completion_message(inputs, query, user, stream = false)
```
Creates a completion message with the provided `inputs`, `query`, and `user`. The stream parameter is optional and set to `false` by default. Set it to `true` to enable streaming response mode.
### Create Chat Message
```ruby
client.create_chat_message(inputs, query, user, stream = false, conversation_id = nil)
```
Creates a chat message with the provided `inputs`, `query`, and `user`. The stream parameter is optional and set to `false` by default. Set it to `true` to enable streaming response mode. The `conversation_id` parameter is optional and can be used to specify the conversation ID.
### Get Conversations
```ruby
client.get_conversations(user, first_id = nil, limit = nil, pinned = nil)
```
Retrieves the conversations for a given `user`. You can provide `first_id`, `limit`, and `pinned` parameters to customize the retrieval.
### Rename Conversation
```ruby
client.rename_conversation(conversation_id, name, user)
```
Renames a conversation identified by conversatio`n_id with the provided `name` for the given `user`.
### Delete Conversation
```ruby
client.delete_conversation(conversation_id, user)
```
Deletes a conversation identified by `conversation_id` for the given `user`.
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run` bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the .gem file to rubygems.org.
## Contributing
Bug reports and pull requests are welcome on GitHub at [https://github.com/langgenius/dify/issues](https://github.com/langgenius/dify/issues).
## License
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).

16
sdks/ruby-client/Rakefile Normal file
View File

@ -0,0 +1,16 @@
# frozen_string_literal: true
require "bundler/gem_tasks"
require "rake/testtask"
Rake::TestTask.new(:test) do |t|
t.libs << "test"
t.libs << "lib"
t.test_files = FileList["test/**/*_test.rb"]
end
require "rubocop/rake_task"
RuboCop::RakeTask.new
task default: %i[test rubocop]

15
sdks/ruby-client/bin/console Executable file
View File

@ -0,0 +1,15 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require "bundler/setup"
require "dify_client"
# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.
# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start
require "irb"
IRB.start(__FILE__)

8
sdks/ruby-client/bin/setup Executable file
View File

@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx
bundle install
# Do any other automated setup that you need to do here

View File

@ -0,0 +1,37 @@
# frozen_string_literal: true
require_relative "lib/dify_client/version"
Gem::Specification.new do |spec|
spec.name = "dify_client"
spec.version = DifyClient::VERSION
spec.authors = ["crazywoola"]
spec.email = ["427733928@qq.com"]
spec.summary = "Ruby client for Dify"
spec.description = "Ruby client for Dify"
spec.homepage = "https://dify.ai"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
# spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/langgenius/dify/tree/main/sdks"
spec.metadata["changelog_uri"] = "https://github.com/langgenius/dify/tree/main/sdks"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
# Uncomment to register a new dependency of your gem
# spec.add_dependency "example-gem", "~> 1.0"
# For more information and examples about making a new gem, checkout our
# guide at: https://bundler.io/guides/creating_gem.html
end

View File

@ -0,0 +1,42 @@
require 'test_helper'
require 'webmock/minitest'
require 'json'
require 'dify_client'
class DifyClientTest < Minitest::Test
def setup
@api_key = 'YOUR_API_KEY'
@client = DifyClient::Client.new(@api_key)
end
def test_update_api_key
new_api_key = 'NEW_API_KEY'
@client.update_api_key(new_api_key)
assert_equal new_api_key, @client.instance_variable_get(:@api_key)
end
def test_get_application_parameters
user = 'USER_ID'
expected_response = {}
stub_request(:get, "https://api.dify.ai/v1/parameters").
with(
body: {"user"=>"USER_ID"},
headers: {
'Accept'=>'*/*',
'Accept-Encoding'=>'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Authorization'=>'Bearer YOUR_API_KEY',
'Content-Type'=>'application/x-www-form-urlencoded',
'Responsetype'=>'json',
'User-Agent'=>'Ruby'
}).
to_return(status: 200, body: expected_response.to_json, headers: {})
response = @client.get_application_parameters(user)
assert_equal expected_response, response
end
end

View File

@ -0,0 +1,6 @@
# frozen_string_literal: true
$LOAD_PATH.unshift File.expand_path("../lib", __dir__)
require "dify_client"
require "minitest/autorun"