루비와 함께 OpenAi API를 사용하십시오! ? ❤️
GPT-4O로 스트리밍 텍스트를 스트리밍하거나 속삭임으로 오디오를 전사 및 번역하거나 Dall · E로 이미지를 만듭니다 ...
Rails+AI 앱을 만들기 위해 저를 고용하십시오 Rails ai | ? 루비 AI 건축업자 불화 | ? x | ? 인류 보석 | ? 미드 주니 보석
이 라인을 응용 프로그램의 보석에 추가하십시오.
gem "ruby-openai"
그런 다음 실행 :
$ bundle install
또는 설치 :
$ gem install ruby-openai
그리고 필요 :
require "openai"
빠른 테스트를 위해 토큰을 새 클라이언트에게 직접 전달할 수 있습니다.
client = OpenAI :: Client . new (
access_token : "access_token_goes_here" ,
log_errors : true # Highly recommended in development, so you can see what errors OpenAI is returning. Not recommended in production because it could leak private data to your logs.
)
보다 강력한 설정을 위해서는 openai.rb
이니셜 라이저 파일에서 API 키로 GEM을 구성 할 수 있습니다. 코드베이스에 비밀을 하드 코딩하지 마십시오. 대신 Dotenv와 같은 것을 사용하여 키를 환경으로 안전하게 전달하십시오.
OpenAI . configure do | config |
config . access_token = ENV . fetch ( "OPENAI_ACCESS_TOKEN" )
config . organization_id = ENV . fetch ( "OPENAI_ORGANIZATION_ID" ) # Optional
config . log_errors = true # Highly recommended in development, so you can see what errors OpenAI is returning. Not recommended in production because it could leak private data to your logs.
end
그런 다음 다음과 같은 클라이언트를 만들 수 있습니다.
client = OpenAI :: Client . new
새 클라이언트를 만들 때 여전히 구성 기본값을 무시할 수 있습니다. 포함되지 않은 옵션은 OpenAi.Configure가있는 모든 글로벌 구성으로 돌아갑니다. 예를 들어이 예에서 organivity_id, request_timeout 등은 ac
client = OpenAI :: Client . new ( access_token : "access_token_goes_here" )
request_timeout
으로 전달하여이를 변경할 수 있습니다. client = OpenAI :: Client . new (
access_token : "access_token_goes_here" ,
uri_base : "https://oai.hconeai.com/" ,
request_timeout : 240 ,
extra_headers : {
"X-Proxy-TTL" => "43200" , # For https://github.com/6/openai-caching-proxy-worker#specifying-a-cache-ttl
"X-Proxy-Refresh" : "true" , # For https://github.com/6/openai-caching-proxy-worker#refreshing-the-cache
"Helicone-Auth" : "Bearer HELICONE_API_KEY" , # For https://docs.helicone.ai/getting-started/integration-method/openai-proxy
"helicone-stream-force-format" => "true" , # Use this with Helicone otherwise streaming drops chunks # https://github.com/alexrudall/ruby-openai/issues/251
}
)
또는 보석 구성시 :
OpenAI . configure do | config |
config . access_token = ENV . fetch ( "OPENAI_ACCESS_TOKEN" )
config . log_errors = true # Optional
config . organization_id = ENV . fetch ( "OPENAI_ORGANIZATION_ID" ) # Optional
config . uri_base = "https://oai.hconeai.com/" # Optional
config . request_timeout = 240 # Optional
config . extra_headers = {
"X-Proxy-TTL" => "43200" , # For https://github.com/6/openai-caching-proxy-worker#specifying-a-cache-ttl
"X-Proxy-Refresh" : "true" , # For https://github.com/6/openai-caching-proxy-worker#refreshing-the-cache
"Helicone-Auth" : "Bearer HELICONE_API_KEY" # For https://docs.helicone.ai/getting-started/integration-method/openai-proxy
} # Optional
end
클라이언트 객체 당 헤더를 동적으로 전달할 수 있으며, 이는 OpenAi.configure를 사용하여 전 세계적으로 설정된 모든 헤더와 병합됩니다.
client = OpenAI :: Client . new ( access_token : "access_token_goes_here" )
client . add_headers ( "X-Proxy-TTL" => "43200" )
기본적으로 ruby-openai
데이터 누출을 피하기 위해 네트워크 요청을 실행하는 동안 Faraday::Error
기록하지 않습니다 (예 : 400s, 500, SSL 오류 등 - Faraday::Error
및 오류 및 오류의 전체 목록은 여기를 참조하십시오. 원인이 될 수있는 것).
이 기능을 활성화하려면 클라이언트를 구성 할 때 log_errors
true
로 설정할 수 있습니다.
client = OpenAI :: Client . new ( log_errors : true )
Faraday Middleware를 블록으로 클라이언트에게 전달할 수 있습니다. Ruby 's Logger로 Verbose Logging을 활성화하려면 :
client = OpenAI :: Client . new do | f |
f . response :logger , Logger . new ( $stdout ) , bodies : true
end
Azure OpenAI Service API를 사용하려면 다음과 같은 보석을 구성 할 수 있습니다.
OpenAI . configure do | config |
config . access_token = ENV . fetch ( "AZURE_OPENAI_API_KEY" )
config . uri_base = ENV . fetch ( "AZURE_OPENAI_URI" )
config . api_type = :azure
config . api_version = "2023-03-15-preview"
end
여기서 AZURE_OPENAI_URI
예를 들어 https://custom-domain.openai.azure.com/openai/deployments/gpt-35-turbo
입니다
Ollama를 사용하면 Llama 3과 같은 오픈 소스 LLM을 현지에서 실행할 수 있습니다. OpenAI API와 채팅 호환성을 제공합니다.
여기에서 Ollama를 다운로드 할 수 있습니다. MacOS에서는 다음과 같이 Ollama를 설치하고 실행할 수 있습니다.
brew install ollama
ollama serve
ollama pull llama3:latest # In new terminal tab.
Ollama 서버와 풀링 된 모델을 사용하여 클라이언트를 만들고 대화를 무료로 스트리밍하십시오.
client = OpenAI :: Client . new (
uri_base : "http://localhost:11434"
)
client . chat (
parameters : {
model : "llama3" , # Required.
messages : [ { role : "user" , content : "Hello!" } ] , # Required.
temperature : 0.7 ,
stream : proc do | chunk , _bytesize |
print chunk . dig ( "choices" , 0 , "delta" , "content" )
end
}
)
# => Hi! It's nice to meet you. Is there something I can help you with, or would you like to chat?
Groq API 채팅은 OpenAI API와 광범위하게 호환되며 몇 가지 사소한 차이가 있습니다. 그런 다음 여기에서 액세스 토큰을 얻으십시오.
client = OpenAI :: Client . new (
access_token : "groq_access_token_goes_here" ,
uri_base : "https://api.groq.com/openai"
)
client . chat (
parameters : {
model : "llama3-8b-8192" , # Required.
messages : [ { role : "user" , content : "Hello!" } ] , # Required.
temperature : 0.7 ,
stream : proc do | chunk , _bytesize |
print chunk . dig ( "choices" , 0 , "delta" , "content" )
end
}
)
Openai는 텍스트를 단어의 단어 나 단어의 일부인 토큰으로 구문 분석합니다. (이 토큰은 API Access_Token과 관련이 없습니다.) 토큰 계산은 비용을 추정하는 데 도움이 될 수 있습니다. 또한 프롬프트 텍스트 크기가 모델 컨텍스트 창의 최대 점수 한도 내에 있는지 확인하고 적절한 max_tokens
완료 매개 변수를 선택하여 응답에도 적합합니다.
텍스트의 토큰 수를 추정하려면 :
OpenAI . rough_token_count ( "Your text" )
보다 정확한 수가 필요하면 tiktoken_ruby를 사용해보십시오.
텍스트를 생성하는 데 사용할 수있는 다른 모델이 있습니다. 전체 목록과 단일 모델에 대한 정보를 검색하려면 :
client . models . list
client . models . retrieve ( id : "gpt-4o" )
GPT는 대화 스타일로 텍스트를 생성하는 데 사용할 수있는 모델입니다. 이를 사용하여 일련의 메시지에 대한 응답을 생성 할 수 있습니다.
response = client . chat (
parameters : {
model : "gpt-4o" , # Required.
messages : [ { role : "user" , content : "Hello!" } ] , # Required.
temperature : 0.7 ,
}
)
puts response . dig ( "choices" , 0 , "message" , "content" )
# => "Hello! How may I assist you today?"
레일 7 및 핫 와이어와 함께 스트리밍 채팅에 대한 빠른 가이드
API에서 실시간으로 스트리밍 할 수 있으며, 이는 훨씬 빠르고보다 매력적인 사용자 경험을 만드는 데 사용됩니다. Proc (또는 #call
메소드가있는 객체)를 stream
매개 변수로 전달하여 작성된 덩어리 스트림을 수신합니다. 하나 이상의 청크를받을 때마다, Proc은 각 청크와 함께 한 번 호출되며 해시로 구문 분석됩니다. OpenAI가 오류를 반환하면 ruby-openai
Faraday 오류를 발생시킵니다.
client . chat (
parameters : {
model : "gpt-4o" , # Required.
messages : [ { role : "user" , content : "Describe a character called Anna!" } ] , # Required.
temperature : 0.7 ,
stream : proc do | chunk , _bytesize |
print chunk . dig ( "choices" , 0 , "delta" , "content" )
end
}
)
# => "Anna is a young woman in her mid-twenties, with wavy chestnut hair that falls to her shoulders..."
참고 : 사용 정보를 얻으려면 stream_options
매개 변수를 제공 할 수 있으며 OpenAI는 사용량과 함께 최종 청크를 제공합니다. 예는 다음과 같습니다.
stream_proc = proc { | chunk , _bytesize | puts "--------------" ; puts chunk . inspect ; }
client . chat (
parameters : {
model : "gpt-4o" ,
stream : stream_proc ,
stream_options : { include_usage : true } ,
messages : [ { role : "user" , content : "Hello!" } ] ,
}
)
# => --------------
# => {"id"=>"chatcmpl-7bbq05PiZqlHxjV1j7OHnKKDURKaf", "object"=>"chat.completion.chunk", "created"=>1718750612, "model"=>"gpt-4o-2024-05-13", "system_fingerprint"=>"fp_9cb5d38cf7", "choices"=>[{"index"=>0, "delta"=>{"role"=>"assistant", "content"=>""}, "logprobs"=>nil, "finish_reason"=>nil}], "usage"=>nil}
# => --------------
# => {"id"=>"chatcmpl-7bbq05PiZqlHxjV1j7OHnKKDURKaf", "object"=>"chat.completion.chunk", "created"=>1718750612, "model"=>"gpt-4o-2024-05-13", "system_fingerprint"=>"fp_9cb5d38cf7", "choices"=>[{"index"=>0, "delta"=>{"content"=>"Hello"}, "logprobs"=>nil, "finish_reason"=>nil}], "usage"=>nil}
# => --------------
# => ... more content chunks
# => --------------
# => {"id"=>"chatcmpl-7bbq05PiZqlHxjV1j7OHnKKDURKaf", "object"=>"chat.completion.chunk", "created"=>1718750612, "model"=>"gpt-4o-2024-05-13", "system_fingerprint"=>"fp_9cb5d38cf7", "choices"=>[{"index"=>0, "delta"=>{}, "logprobs"=>nil, "finish_reason"=>"stop"}], "usage"=>nil}
# => --------------
# => {"id"=>"chatcmpl-7bbq05PiZqlHxjV1j7OHnKKDURKaf", "object"=>"chat.completion.chunk", "created"=>1718750612, "model"=>"gpt-4o-2024-05-13", "system_fingerprint"=>"fp_9cb5d38cf7", "choices"=>[], "usage"=>{"prompt_tokens"=>9, "completion_tokens"=>9, "total_tokens"=>18}}
GPT-4 비전 모델을 사용하여 이미지에 대한 설명을 생성 할 수 있습니다.
messages = [
{ "type" : "text" , "text" : "What’s in this image?" } ,
{ "type" : "image_url" ,
"image_url" : {
"url" : "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" ,
} ,
}
]
response = client . chat (
parameters : {
model : "gpt-4-vision-preview" , # Required.
messages : [ { role : "user" , content : messages } ] , # Required.
}
)
puts response . dig ( "choices" , 0 , "message" , "content" )
# => "The image depicts a serene natural landscape featuring a long wooden boardwalk extending straight ahead"
JSON에서 응답을 요청하도록 response_format을 설정할 수 있습니다.
response = client . chat (
parameters : {
model : "gpt-4o" ,
response_format : { type : "json_object" } ,
messages : [ { role : "user" , content : "Hello! Give me some JSON please." } ] ,
temperature : 0.7 ,
} )
puts response . dig ( "choices" , 0 , "message" , "content" )
# =>
# {
# "name": "John",
# "age": 30,
# "city": "New York",
# "hobbies": ["reading", "traveling", "hiking"],
# "isStudent": false
# }
당신도 그것을 스트리밍 할 수 있습니다!
response = client . chat (
parameters : {
model : "gpt-4o" ,
messages : [ { role : "user" , content : "Can I have some JSON please?" } ] ,
response_format : { type : "json_object" } ,
stream : proc do | chunk , _bytesize |
print chunk . dig ( "choices" , 0 , "delta" , "content" )
end
}
)
# =>
# {
# "message": "Sure, please let me know what specific JSON data you are looking for.",
# "JSON_data": {
# "example_1": {
# "key_1": "value_1",
# "key_2": "value_2",
# "key_3": "value_3"
# },
# "example_2": {
# "key_4": "value_4",
# "key_5": "value_5",
# "key_6": "value_6"
# }
# }
# }
당신은 함수를 설명하고 전달할 수 있으며 모델은 지능적으로 JSON 객체가 포함 된 인수를 출력하여 전화를 걸어 주어진 위치에서 날씨를 얻기 위해 get_current_weather
를 사용합니다. Tool_Choice는 선택 사항이지만 제외하면 모델이 함수 사용 여부를 선택합니다 (여기 참조).
def get_current_weather ( location : , unit : "fahrenheit" )
# Here you could use a weather api to fetch the weather.
"The weather in #{ location } is nice ? #{ unit } "
end
messages = [
{
"role" : "user" ,
"content" : "What is the weather like in San Francisco?" ,
} ,
]
response =
client . chat (
parameters : {
model : "gpt-4o" ,
messages : messages , # Defined above because we'll use it again
tools : [
{
type : "function" ,
function : {
name : "get_current_weather" ,
description : "Get the current weather in a given location" ,
parameters : { # Format: https://json-schema.org/understanding-json-schema
type : :object ,
properties : {
location : {
type : :string ,
description : "The city and state, e.g. San Francisco, CA" ,
} ,
unit : {
type : "string" ,
enum : %w[ celsius fahrenheit ] ,
} ,
} ,
required : [ "location" ] ,
} ,
} ,
}
] ,
# Optional, defaults to "auto"
# Can also put "none" or specific functions, see docs
tool_choice : "required"
} ,
)
message = response . dig ( "choices" , 0 , "message" )
if message [ "role" ] == "assistant" && message [ "tool_calls" ]
message [ "tool_calls" ] . each do | tool_call |
tool_call_id = tool_call . dig ( "id" )
function_name = tool_call . dig ( "function" , "name" )
function_args = JSON . parse (
tool_call . dig ( "function" , "arguments" ) ,
{ symbolize_names : true } ,
)
function_response =
case function_name
when "get_current_weather"
get_current_weather ( ** function_args ) # => "The weather is nice ?"
else
# decide how to handle
end
# For a subsequent message with the role "tool", OpenAI requires the preceding message to have a tool_calls argument.
messages << message
messages << {
tool_call_id : tool_call_id ,
role : "tool" ,
name : function_name ,
content : function_response
} # Extend the conversation with the results of the functions
end
second_response = client . chat (
parameters : {
model : "gpt-4o" ,
messages : messages
}
)
puts second_response . dig ( "choices" , 0 , "message" , "content" )
# At this point, the model has decided to call functions, you've called the functions
# and provided the response back, and the model has considered this and responded.
end
# => "It looks like the weather is nice and sunny in San Francisco! If you're planning to go out, it should be a pleasant day."
다른 GPT-3 모델을 사용하여 완료하려면 OpenAI API를 누르십시오.
response = client . completions (
parameters : {
model : "gpt-4o" ,
prompt : "Once upon a time" ,
max_tokens : 5
}
)
puts response [ "choices" ] . map { | c | c [ "text" ] }
# => [", there lived a great"]
임베딩 엔드 포인트를 사용하여 입력을 나타내는 숫자 벡터를 얻을 수 있습니다. 그런 다음 다른 입력에 대해 이러한 벡터를 비교하여 입력이 얼마나 유사한지를 효율적으로 확인할 수 있습니다.
response = client . embeddings (
parameters : {
model : "text-embedding-ada-002" ,
input : "The food was delicious and the waiter..."
}
)
puts response . dig ( "data" , 0 , "embedding" )
# => Vector representation of your embedding
배치 엔드 포인트를 사용하면 비동기 적으로 실행하기 위해 대량 배치의 API 요청을 생성하고 관리 할 수 있습니다. 현재 배치에 대한 지원되는 엔드 포인트는 /v1/chat/completions
(채팅 완료 API) 및 /v1/embeddings
(Embeddings API)입니다.
배치 엔드 포인트를 사용하려면 먼저 파일 엔드 포인트를 사용하여 배치 요청이 포함 된 JSONL 파일을 업로드해야합니다. 파일은 batch
로 설정된 목적으로 업로드해야합니다. JSONL 파일의 각 줄은 단일 요청을 나타내며 다음 형식이 있어야합니다.
{
"custom_id" : " request-1 " ,
"method" : " POST " ,
"url" : " /v1/chat/completions " ,
"body" : {
"model" : " gpt-4o " ,
"messages" : [
{ "role" : " system " , "content" : " You are a helpful assistant. " },
{ "role" : " user " , "content" : " What is 2+2? " }
]
}
}
JSONL 파일을 업로드 한 후에는 파일 ID, 엔드 포인트 및 완료 창을 제공하여 새 배치를 만들 수 있습니다.
response = client . batches . create (
parameters : {
input_file_id : "file-abc123" ,
endpoint : "/v1/chat/completions" ,
completion_window : "24h"
}
)
batch_id = response [ "id" ]
ID를 사용하여 특정 배치에 대한 정보를 검색 할 수 있습니다.
batch = client . batches . retrieve ( id : batch_id )
진행중인 배치를 취소하려면 :
client . batches . cancel ( id : batch_id )
모든 배치를 나열 할 수도 있습니다.
client . batches . list
배치 [ "완료 _at"]가 존재하면 출력 또는 오류 파일을 가져올 수 있습니다.
batch = client . batches . retrieve ( id : batch_id )
output_file_id = batch [ "output_file_id" ]
output_response = client . files . content ( id : output_file_id )
error_file_id = batch [ "error_file_id" ]
error_response = client . files . content ( id : error_file_id )
이 파일은 JSONL 형식이며 각 줄은 단일 요청에 대한 출력 또는 오류를 나타냅니다. 라인은 순서대로있을 수 있습니다.
{
"id" : " response-1 " ,
"custom_id" : " request-1 " ,
"response" : {
"id" : " chatcmpl-abc123 " ,
"object" : " chat.completion " ,
"created" : 1677858242 ,
"model" : " gpt-4o " ,
"choices" : [
{
"index" : 0 ,
"message" : {
"role" : " assistant " ,
"content" : " 2+2 equals 4. "
}
}
]
}
}
HTTP가 아닌 오류로 요청이 실패하면 오류 객체에 실패 원인에 대한 자세한 정보가 포함됩니다.
다음과 같은 .jsonl
파일에 데이터를 넣으십시오.
{ "prompt" : " Overjoyed with my new phone! -> " , "completion" : " positive " }
{ "prompt" : " @lakers disappoint for a third straight night -> " , "completion" : " negative " }
그리고 경로 (또는 stringio 객체)를 client.files.upload
로 전달하여 OpenAI에 업로드 한 다음 상호 작용하십시오.
client . files . upload ( parameters : { file : "path/to/sentiment.jsonl" , purpose : "fine-tune" } )
client . files . list
client . files . retrieve ( id : "file-123" )
client . files . content ( id : "file-123" )
client . files . delete ( id : "file-123" )
파일 경로를 보낼 수 있습니다.
client . files . upload ( parameters : { file : "path/to/file.pdf" , purpose : "assistants" } )
또는 파일 개체
my_file = File . open ( "path/to/file.pdf" , "rb" )
client . files . upload ( parameters : { file : my_file , purpose : "assistants" } )
API 문서의 지원되는 파일 유형을 참조하십시오.
위와 같이 미세 조정 데이터를 .jsonl
파일로 업로드하고 ID를 가져옵니다.
response = client . files . upload ( parameters : { file : "path/to/sarcasm.jsonl" , purpose : "fine-tune" } )
file_id = JSON . parse ( response . body ) [ "id" ]
그런 다음이 파일 ID를 사용하여 미세 조정 작업을 만들 수 있습니다.
response = client . finetunes . create (
parameters : {
training_file : file_id ,
model : "gpt-4o"
} )
fine_tune_id = response [ "id" ]
그것은 당신에게 미세 조정 ID를 줄 것입니다. 실수를 한 경우 처리하기 전에 미세 조정 모델을 취소 할 수 있습니다.
client . finetunes . cancel ( id : fine_tune_id )
처리가 완료되기까지 짧은 시간을 기다려야 할 수도 있습니다. 처리되면 목록을 사용하거나 검색하여 미세 조정 된 모델의 이름을 얻을 수 있습니다.
client . finetunes . list
response = client . finetunes . retrieve ( id : fine_tune_id )
fine_tuned_model = response [ "fine_tuned_model" ]
이 미세 조정 된 모델 이름은 채팅 완료에 사용할 수 있습니다.
response = client . chat (
parameters : {
model : fine_tuned_model ,
messages : [ { role : "user" , content : "I love Mondays!" } ]
}
)
response . dig ( "choices" , 0 , "message" , "content" )
작업의 이벤트를 캡처 할 수도 있습니다.
client . finetunes . list_events ( id : fine_tune_id )
벡터 저장 개체는 파일 검색 도구에 파일을 검색 할 수있는 기능을 제공합니다.
새 벡터 스토어를 만들 수 있습니다.
response = client . vector_stores . create (
parameters : {
name : "my vector store" ,
file_ids : [ "file-abc123" , "file-def456" ]
}
)
vector_store_id = response [ "id" ]
vector_store_id
주어지면 현재 필드 값을 retrieve
할 수 있습니다.
client . vector_stores . retrieve ( id : vector_store_id )
현재 조직에서 이용할 수있는 모든 벡터 매장 list
얻을 수 있습니다.
client . vector_stores . list
file_ids
제외하고 기존 벡터 저장소를 수정할 수 있습니다.
response = client . vector_stores . modify (
id : vector_store_id ,
parameters : {
name : "Modified Test Vector Store" ,
}
)
벡터 스토어를 삭제할 수 있습니다.
client . vector_stores . delete ( id : vector_store_id )
벡터 스토어 파일은 벡터 스토어 내부의 파일을 나타냅니다.
파일을 벡터 저장소에 첨부하여 새 벡터 스토어 파일을 만들 수 있습니다.
response = client . vector_store_files . create (
vector_store_id : "vector-store-abc123" ,
parameters : {
file_id : "file-abc123"
}
)
vector_store_file_id = response [ "id" ]
vector_store_file_id
주어지면 현재 필드 값을 retrieve
할 수 있습니다.
client . vector_store_files . retrieve (
vector_store_id : "vector-store-abc123" ,
id : vector_store_file_id
)
벡터 스토어에서 현재 사용 가능한 모든 벡터 매장 파일 list
얻을 수 있습니다.
client . vector_store_files . list ( vector_store_id : "vector-store-abc123" )
벡터 저장 파일을 삭제할 수 있습니다.
client . vector_store_files . delete (
vector_store_id : "vector-store-abc123" ,
id : vector_store_file_id
)
참고 : 벡터 스토어에서 파일이 제거되지만 파일 자체는 삭제되지 않습니다. 파일을 삭제하려면 파일 삭제 엔드 포인트를 사용하십시오.
벡터 스토어 파일 배치는 벡터 저장소에 여러 파일을 추가하기 위해 작업을 나타냅니다.
여러 파일을 벡터 저장소에 연결하여 새 벡터 스토어 파일 배치를 만들 수 있습니다.
response = client . vector_store_file_batches . create (
vector_store_id : "vector-store-abc123" ,
parameters : {
file_ids : [ "file-abc123" , "file-def456" ]
}
)
file_batch_id = response [ "id" ]
file_batch_id
주어지면 현재 필드 값을 retrieve
할 수 있습니다.
client . vector_store_file_batches . retrieve (
vector_store_id : "vector-store-abc123" ,
id : file_batch_id
)
벡터 스토어에서 현재 사용 가능한 배치에서 모든 벡터 상점 파일 list
얻을 수 있습니다.
client . vector_store_file_batches . list (
vector_store_id : "vector-store-abc123" ,
id : file_batch_id
)
벡터 저장 파일 배치를 취소 할 수 있습니다 (이 배치에서 가능한 빨리이 배치 처리를 취소하려고 시도) :
client . vector_store_file_batches . cancel (
vector_store_id : "vector-store-abc123" ,
id : file_batch_id
)
조수는 대화를 많이하고 도구를 사용하여 작업을 수행 할 수있는 상태의 배우입니다 (조수 개요 참조).
새로운 어시스턴트를 만들려면 :
response = client . assistants . create (
parameters : {
model : "gpt-4o" ,
name : "OpenAI-Ruby test assistant" ,
description : nil ,
instructions : "You are a Ruby dev bot. When asked a question, write and run Ruby code to answer the question" ,
tools : [
{ type : "code_interpreter" } ,
{ type : "file_search" }
] ,
tool_resources : {
code_interpreter : {
file_ids : [ ] # See Files section above for how to upload files
} ,
file_search : {
vector_store_ids : [ ] # See Vector Stores section above for how to add vector stores
}
} ,
"metadata" : { my_internal_version_id : "1.0.0" }
}
)
assistant_id = response [ "id" ]
assistant_id
주어지면 현재 필드 값을 retrieve
할 수 있습니다.
client . assistants . retrieve ( id : assistant_id )
현재 조직에서 이용할 수있는 모든 보조자 list
얻을 수 있습니다.
client . assistants . list
어시스턴트의 ID를 사용하여 기존 비서를 수정할 수 있습니다 (API 문서 참조).
response = client . assistants . modify (
id : assistant_id ,
parameters : {
name : "Modified Test Assistant for OpenAI-Ruby" ,
metadata : { my_internal_version_id : '1.0.1' }
}
)
보조원을 삭제할 수 있습니다.
client . assistants . delete ( id : assistant_id )
위에서 설명한대로 어시스턴트를 만든 후에는 조수가 작업 할 Messages
Thread
를 준비해야합니다 (조수 소개 참조). 예를 들어, 초기 설정으로 다음을 수행 할 수 있습니다.
# Create thread
response = client . threads . create # Note: Once you create a thread, there is no way to list it
# or recover it currently (as of 2023-12-10). So hold onto the `id`
thread_id = response [ "id" ]
# Add initial message from user (see https://platform.openai.com/docs/api-reference/messages/createMessage)
message_id = client . messages . create (
thread_id : thread_id ,
parameters : {
role : "user" , # Required for manually created messages
content : "Can you help me write an API library to interact with the OpenAI API please?"
}
) [ "id" ]
# Retrieve individual message
message = client . messages . retrieve ( thread_id : thread_id , id : message_id )
# Review all messages on the thread
messages = client . messages . list ( thread_id : thread_id )
스레드가 더 이상 필요하지 않은 후에 정리하려면 다음과 같습니다.
# To delete the thread (and all associated messages):
client . threads . delete ( id : thread_id )
client . messages . retrieve ( thread_id : thread_id , id : message_id ) # -> Fails after thread is deleted
조수 모델로 평가할 스레드를 제출하려면 다음과 같이 Run
만듭니다.
# Create run (will use instruction/model/tools from Assistant's definition)
response = client . runs . create (
thread_id : thread_id ,
parameters : {
assistant_id : assistant_id ,
max_prompt_tokens : 256 ,
max_completion_tokens : 16
}
)
run_id = response [ 'id' ]
메시지 청크를 스트리밍 할 수 있습니다.
client . runs . create (
thread_id : thread_id ,
parameters : {
assistant_id : assistant_id ,
max_prompt_tokens : 256 ,
max_completion_tokens : 16 ,
stream : proc do | chunk , _bytesize |
if chunk [ "object" ] == "thread.message.delta"
print chunk . dig ( "delta" , "content" , 0 , "text" , "value" )
end
end
}
)
실행 상태를 얻으려면 :
response = client . runs . retrieve ( id : run_id , thread_id : thread_id )
status = response [ 'status' ]
status
응답에는 다음과 같이 처리 할 수있는 다음과 같이 처리 할 수있는 다음 queued
, in_progress
, requires_action
, cancelling
, cancelled
, failed
, completed
또는 expired
이 포함될 수 있습니다.
while true do
response = client . runs . retrieve ( id : run_id , thread_id : thread_id )
status = response [ 'status' ]
case status
when 'queued' , 'in_progress' , 'cancelling'
puts 'Sleeping'
sleep 1 # Wait one second and poll again
when 'completed'
break # Exit loop and report result to user
when 'requires_action'
# Handle tool calls (see below)
when 'cancelled' , 'failed' , 'expired'
puts response [ 'last_error' ] . inspect
break # or `exit`
else
puts "Unknown status response: #{ status } "
end
end
status
응답에 run
이 completed
나타내는 경우 관련 thread
하나 이상의 새 messages
첨부됩니다.
# Either retrieve all messages in bulk again, or...
messages = client . messages . list ( thread_id : thread_id , parameters : { order : 'asc' } )
# Alternatively retrieve the `run steps` for the run which link to the messages:
run_steps = client . run_steps . list ( thread_id : thread_id , run_id : run_id , parameters : { order : 'asc' } )
new_message_ids = run_steps [ 'data' ] . filter_map do | step |
if step [ 'type' ] == 'message_creation'
step . dig ( 'step_details' , "message_creation" , "message_id" )
end # Ignore tool calls, because they don't create new messages.
end
# Retrieve the individual messages
new_messages = new_message_ids . map do | msg_id |
client . messages . retrieve ( id : msg_id , thread_id : thread_id )
end
# Find the actual response text in the content array of the messages
new_messages . each do | msg |
msg [ 'content' ] . each do | content_item |
case content_item [ 'type' ]
when 'text'
puts content_item . dig ( 'text' , 'value' )
# Also handle annotations
when 'image_file'
# Use File endpoint to retrieve file contents via id
id = content_item . dig ( 'image_file' , 'file_id' )
end
end
end
어시스턴트의 메시지를 포함하여 메시지의 메타 데이터를 업데이트 할 수도 있습니다.
metadata = {
user_id : "abc123"
}
message = client . messages . modify (
id : message_id ,
thread_id : thread_id ,
parameters : { metadata : metadata } ,
)
언제든지 특정 스레드에서 수행되었거나 현재 실행중인 모든 실행을 나열 할 수 있습니다.
client . runs . list ( thread_id : thread_id , parameters : { order : "asc" , limit : 3 } )
또한 스레드를 생성하고 다음과 같이 한 번의 호출로 실행할 수 있습니다.
response = client . runs . create_thread_and_run ( parameters : { assistant_id : assistant_id } )
run_id = response [ 'id' ]
thread_id = response [ 'thread_id' ]
스레드에 이미지를 포함시킬 수 있으며 LLM이 설명하고 읽습니다. 이 예에서는이 파일을 사용하고 있습니다.
require "openai"
# Make a client
client = OpenAI :: Client . new (
access_token : "access_token_goes_here" ,
log_errors : true # Don't log errors in production.
)
# Upload image as a file
file_id = client . files . upload (
parameters : {
file : "path/to/example.png" ,
purpose : "assistants" ,
}
) [ "id" ]
# Create assistant (You could also use an existing one here)
assistant_id = client . assistants . create (
parameters : {
model : "gpt-4o" ,
name : "Image reader" ,
instructions : "You are an image describer. You describe the contents of images." ,
}
) [ "id" ]
# Create thread
thread_id = client . threads . create [ "id" ]
# Add image in message
client . messages . create (
thread_id : thread_id ,
parameters : {
role : "user" , # Required for manually created messages
content : [
{
"type" : "text" ,
"text" : "What's in this image?"
} ,
{
"type" : "image_file" ,
"image_file" : { "file_id" : file_id }
}
]
}
)
# Run thread
run_id = client . runs . create (
thread_id : thread_id ,
parameters : { assistant_id : assistant_id }
) [ "id" ]
# Wait until run in complete
status = nil
until status == "completed" do
sleep ( 0.1 )
status = client . runs . retrieve ( id : run_id , thread_id : thread_id ) [ 'status' ]
end
# Get the response
messages = client . messages . list ( thread_id : thread_id , parameters : { order : 'asc' } )
messages . dig ( "data" , - 1 , "content" , 0 , "text" , "value" )
=> "The image contains a placeholder graphic with a tilted, stylized representation of a postage stamp in the top part, which includes an abstract landscape with hills and a sun. Below the stamp, in the middle of the image, there is italicized text in a light golden color that reads, " This is just an example. " The background is a light pastel shade, and a yellow border frames the entire image."
어시스턴트가 function
도구에 액세스 할 수 있도록 허용하는 경우 (채팅 완료시 함수와 동일한 방식으로 정의됩니다), 어시스턴트가 하나 이상의 기능 도구를 평가하기를 원할 때 requires_action
의 상태 코드를 얻을 수 있습니다.
def get_current_weather ( location : , unit : "celsius" )
# Your function code goes here
if location =~ /San Francisco/i
return unit == "celsius" ? "The weather is nice ? at 27°C" : "The weather is nice ? at 80°F"
else
return unit == "celsius" ? "The weather is icy ? at -5°C" : "The weather is icy ? at 23°F"
end
end
if status == 'requires_action'
tools_to_call = response . dig ( 'required_action' , 'submit_tool_outputs' , 'tool_calls' )
my_tool_outputs = tools_to_call . map { | tool |
# Call the functions based on the tool's name
function_name = tool . dig ( 'function' , 'name' )
arguments = JSON . parse (
tool . dig ( "function" , "arguments" ) ,
{ symbolize_names : true } ,
)
tool_output = case function_name
when "get_current_weather"
get_current_weather ( ** arguments )
end
{
tool_call_id : tool [ 'id' ] ,
output : tool_output ,
}
}
client . runs . submit_tool_outputs (
thread_id : thread_id ,
run_id : run_id ,
parameters : { tool_outputs : my_tool_outputs }
)
end
실행이 만료되기 전에 도구 출력을 10 분 동안 제출해야합니다.
심호흡을하십시오. 이것을 위해서는 음료가 필요할 수 있습니다.
OpenAI는 내부 래그 파이프 라인에 사용 된 청크를 파일 검색 결과를 생성 할 수 있습니다.
여기에서이를 수행하는 예제 사양을 찾을 수 있으므로 가능하다는 것을 알 수 있습니다.
파일 검색에 청크를 사용하는 방법은 다음과 같습니다. 이 예에서는이 파일을 사용하고 있습니다.
require "openai"
# Make a client
client = OpenAI :: Client . new (
access_token : "access_token_goes_here" ,
log_errors : true # Don't log errors in production.
)
# Upload your file(s)
file_id = client . files . upload (
parameters : {
file : "path/to/somatosensory.pdf" ,
purpose : "assistants"
}
) [ "id" ]
# Create a vector store to store the vectorised file(s)
vector_store_id = client . vector_stores . create ( parameters : { } ) [ "id" ]
# Vectorise the file(s)
vector_store_file_id = client . vector_store_files . create (
vector_store_id : vector_store_id ,
parameters : { file_id : file_id }
) [ "id" ]
# Check that the file is vectorised (wait for status to be "completed")
client . vector_store_files . retrieve ( vector_store_id : vector_store_id , id : vector_store_file_id ) [ "status" ]
# Create an assistant, referencing the vector store
assistant_id = client . assistants . create (
parameters : {
model : "gpt-4o" ,
name : "Answer finder" ,
instructions : "You are a file search tool. Find the answer in the given files, please." ,
tools : [
{ type : "file_search" }
] ,
tool_resources : {
file_search : {
vector_store_ids : [ vector_store_id ]
}
}
}
) [ "id" ]
# Create a thread with your question
thread_id = client . threads . create ( parameters : {
messages : [
{ role : "user" ,
content : "Find the description of a nociceptor." }
]
} ) [ "id" ]
# Run the thread to generate the response. Include the "GIVE ME THE CHUNKS" incantation.
run_id = client . runs . create (
thread_id : thread_id ,
parameters : {
assistant_id : assistant_id
} ,
query_parameters : { include : [ "step_details.tool_calls[*].file_search.results[*].content" ] } # incantation
) [ "id" ]
# Get the steps that happened in the run
steps = client . run_steps . list (
thread_id : thread_id ,
run_id : run_id ,
parameters : { order : "asc" }
)
# Retrieve all the steps. Include the "GIVE ME THE CHUNKS" incantation again.
steps = steps [ "data" ] . map do | step |
client . run_steps . retrieve (
thread_id : thread_id ,
run_id : run_id ,
id : step [ "id" ] ,
parameters : { include : [ "step_details.tool_calls[*].file_search.results[*].content" ] } # incantation
)
end
# Now we've got the chunk info, buried deep. Loop through the steps and find chunks if included:
chunks = steps . flat_map do | step |
included_results = step . dig ( "step_details" , "tool_calls" , 0 , "file_search" , "results" )
next if included_results . nil? || included_results . empty?
included_results . flat_map do | result |
result [ "content" ] . map do | content |
content [ "text" ]
end
end
end . compact
# The first chunk will be the closest match to the prompt. Finally, if you want to view the completed message(s):
client . messages . list ( thread_id : thread_id )
dall · e 2 또는 dall · e 3을 사용하여 이미지를 생성하십시오!
dall · e 2의 경우 생성 된 이미지의 크기는 256x256
, 512x512
또는 1024x1024
중 하나 여야합니다. 지정되지 않으면 이미지가 기본값 1024x1024
입니다.
response = client . images . generate (
parameters : {
prompt : "A baby sea otter cooking pasta wearing a hat of some sort" ,
size : "256x256" ,
}
)
puts response . dig ( "data" , 0 , "url" )
# => "https://oaidalleapiprodscus.blob.core.windows.net/private/org-Rf437IxKhh..."
dall · e 3의 경우 생성 된 이미지의 크기는 1024x1024
, 1024x1792
또는 1792x1024
중 하나 여야합니다. 또한 이미지의 품질은 standard
또는 hd
로 지정할 수 있습니다.
response = client . images . generate (
parameters : {
prompt : "A springer spaniel cooking pasta wearing a hat of some sort" ,
model : "dall-e-3" ,
size : "1024x1792" ,
quality : "standard" ,
}
)
puts response . dig ( "data" , 0 , "url" )
# => "https://oaidalleapiprodscus.blob.core.windows.net/private/org-Rf437IxKhh..."
이미지의 투명 부분을 채우거나 투명 섹션이있는 마스크를 업로드하여 프롬프트에 따라 변경할 수있는 이미지의 일부를 나타냅니다 ...
response = client . images . edit (
parameters : {
prompt : "A solid red Ruby on a blue background" ,
image : "image.png" ,
mask : "mask.png" ,
}
)
puts response . dig ( "data" , 0 , "url" )
# => "https://oaidalleapiprodscus.blob.core.windows.net/private/org-Rf437IxKhh..."
이미지의 변형을 만듭니다.
response = client . images . variations ( parameters : { image : "image.png" , n : 2 } )
puts response . dig ( "data" , 0 , "url" )
# => "https://oaidalleapiprodscus.blob.core.windows.net/private/org-Rf437IxKhh..."
OpenAI의 컨텐츠 정책을 위반하는지 확인하기 위해 문자열을 전달하십시오.
response = client . moderations ( parameters : { input : "I'm worried about that." } )
puts response . dig ( "results" , 0 , "category_scores" , "hate" )
# => 5.505014632944949e-05
Whisper는 오디오 파일을 기반으로 텍스트를 생성하는 데 사용할 수있는 텍스트 모델로의 음성입니다.
Translations API는 지원되는 언어로 오디오 파일을 입력하여 오디오를 영어로 전사합니다.
response = client . audio . translate (
parameters : {
model : "whisper-1" ,
file : File . open ( "path_to_file" , "rb" ) ,
}
)
puts response [ "text" ]
# => "Translation of the text"
Transcriptions API는 전사하려는 오디오 파일을 입력하고 원하는 출력 파일 형식으로 텍스트를 반환합니다.
전사 품질을 향상시키기 위해 오디오 파일의 언어를 전달할 수 있습니다. 지원되는 언어는 여기에 나열되어 있습니다. 언어를 ISO-639-1 코드로 제공해야합니다. 영어의 경우 "en"또는 네팔의 경우 "NE". 여기에서 코드를 찾을 수 있습니다.
response = client . audio . transcribe (
parameters : {
model : "whisper-1" ,
file : File . open ( "path_to_file" , "rb" ) ,
language : "en" , # Optional
}
)
puts response [ "text" ]
# => "Transcription of the text"
Speech API는 텍스트를 입력하고 음성을 입력하고들을 수있는 오디오 파일의 내용을 반환합니다.
response = client . audio . speech (
parameters : {
model : "tts-1" ,
input : "This is a speech test!" ,
voice : "alloy" ,
response_format : "mp3" , # Optional
speed : 1.0 , # Optional
}
)
File . binwrite ( 'demo.mp3' , response )
# => mp3 file that plays: "This is a speech test!"
HTTP 오류는 다음과 같이 잡을 수 있습니다.
begin
OpenAI :: Client . new . models . retrieve ( id : "gpt-4o" )
rescue Faraday :: Error => e
raise "Got a Faraday error: #{ e } "
end
레포를 확인한 후 bin/setup
실행하여 종속성을 설치하십시오. 실험 할 수있는 대화식 프롬프트를 위해 bin/console
실행할 수 있습니다.
이 보석을 로컬 컴퓨터에 설치하려면 bundle exec rake install
실행하십시오.
모든 테스트를 실행하려면 Linter (RuboCop)를 실행하는 명령 bundle exec rake
실행하십시오. 이 저장소는 VCR을 사용하여 API 요청을 기록합니다.
경고
ENV
에 OPENAI_ACCESS_TOKEN
있는 경우 사양을 실행하면 실제 API에 대한 사양을 실행하는 데 사용됩니다. 이는 느리고 비용이 2 센트 이상입니다! 저장된 VCR 응답에 대해 사양을 실행하려면 unset
유사하게 환경에서 제거하십시오.
먼저 VCR없이 사양을 실행하여 실제로 API를 쳤다. 2 센트 이상이 소요됩니다. 환경에서 OpenAi_Access_token을 설정하거나 다음과 같이 전달하십시오.
OPENAI_ACCESS_TOKEN=123abc bundle exec rspec
그런 다음 version.rb
에서 버전 번호를 업데이트하고 CHANGELOG.md
업데이트하고 bundle install
실행하여 gemfile.lock을 업데이트 한 다음 버전에 대한 GIT bundle exec rake release
를 생성하고 GIT 커밋 및 태그를 푸시합니다. .gem
파일로 rubygems.org.
https://github.com/alexrudall/ruby-openai에서 버그 보고서 및 풀 요청은 환영합니다. 이 프로젝트는 협업을위한 안전하고 환영하는 공간이되기위한 것이며, 기고자들은 행동 강령을 준수 할 것으로 예상됩니다.
보석은 MIT 라이센스의 조건에 따라 오픈 소스로 제공됩니다.
Ruby OpenAI 프로젝트의 코드베이스, 문제 추적기, 채팅방 및 메일 링리스트에서 상호 작용하는 모든 사람은 행동 강령을 따라야합니다.