איך להגדיל את ה timeout עם langchainrb
ספריית langchainrb היא הסבה של langchain ל Ruby, רק קצת פחות טובה מהמקור. אחת הבעיות של גירסת ה Ruby היא timeout קצר מדי, מה שגורם לשאילתות להיכשל כשמנסים לדבר עם ג'מני פרו.
הממשק עצמו של langchainrb ממש נוח ובמיוחד אהבתי את היכולת לקבל תוצאה בתור אוביקט כשמעבירים JSON Schema, כלומר קוד כזה:
json_schema = {
type: "object",
properties: {
name: {
type: "string",
description: "Persons name"
},
age: {
type: "number",
description: "Persons age"
},
interests: {
type: "array",
items: {
type: "object",
properties: {
interest: {
type: "string",
description: "A topic of interest"
},
levelOfInterest: {
type: "number",
description: "A value between 0 and 100 of how interested the person is in this interest"
}
},
required: ["interest", "levelOfInterest"],
additionalProperties: false
},
minItems: 1,
maxItems: 3,
description: "A list of the person's interests"
}
},
required: ["name", "age", "interests"],
additionalProperties: false
}
parser = Langchain::OutputParsers::StructuredOutputParser.from_json_schema(json_schema)
prompt = Langchain::Prompt::PromptTemplate.new(template: "Generate details of a fictional character.\n{format_instructions}\nCharacter description: {description}", input_variables: ["description", "format_instructions"])
prompt_text = prompt.format(description: "Korean chemistry student", format_instructions: parser.get_format_instructions)
llm = Langchain::LLM::OpenAI.new(api_key: ENV["OPENAI_API_KEY"])
llm_response = llm.chat(messages: [{role: "user", content: prompt_text}]).completion
parser.parse(llm_response)
הבעיה היחידה היא ה timeouts הקצרים מדי ובמיוחד בעבודה עם Gemini. הבעיה היא הקוד הזה מקוד הספריה:
def http_post(url, params)
http = Net::HTTP.new(url.hostname, url.port)
http.use_ssl = url.scheme == "https"
http.set_debug_output(Langchain.logger) if Langchain.logger.debug?
request = Net::HTTP::Post.new(url)
request.content_type = "application/json"
request.body = params.to_json
response = http.request(request)
JSON.parse(response.body)
end
שאחראי לתקשורת עם ג'מיני ולא כולל אפשרות להגדרת timeout.
אז כן קודם כל פתחתי Issue אבל אז נזכרתי שאנחנו ברובי והוספתי את הקובץ config/initializers/langchain_patch.rb
עם התוכן הבא:
require 'langchain/llm/google_gemini'
# This module adds a dedicated `read_timeout` attribute to the class.
module GoogleGeminiTimeoutAttribute
# This one line creates two methods for us:
# 1. `read_timeout` (the getter, to read the value)
# 2. `read_timeout=` (the setter, to assign the value)
# It manages the underlying instance variable `@read_timeout`.
attr_accessor :read_timeout
# We still patch http_post to use the value from our new attribute.
def http_post(url, params)
http = Net::HTTP.new(url.hostname, url.port)
http.use_ssl = url.scheme == "https"
http.set_debug_output(Langchain.logger) if Langchain.logger.debug?
http.read_timeout = @read_timeout if @read_timeout
request = Net::HTTP::Post.new(url)
request.content_type = "application/json"
request.body = params.to_json
response = http.request(request)
JSON.parse(response.body)
end
end
Langchain::LLM::GoogleGemini.prepend(GoogleGeminiTimeoutAttribute)
שורת המפתח היא:
http.read_timeout = @read_timeout if @read_timeout
וברור שהיה נחמד אם לא הייתי צריך לשכפל את כל המימוש של http_post
אבל אי אפשר לקבל הכל בחיים.
ועכשיו אפשר להגדיר את ה timeout בצורה פשוטה על ידי כתיבת הערך לאוביקט:
llm = Langchain::LLM::GoogleGemini.new(
api_key: Rails.application.credentials.google_api_key,
default_options: { chat_model: 'gemini-2.5-pro-preview-05-06' },
)
llm.read_timeout = 600