SDK и библиотеки
Официальные клиентские библиотеки для интеграции платформы Coren в ваши приложения. Все SDK оптимизированы для работы в on-premise окружении банка.
OpenAI-совместимый
Простая миграция
Async поддержка
Высокая производительность
Retry логика
Надёжность соединения
Type Safety
Строгая типизация
Python SDK
v1.2.0Официальный Python клиент для платформы Coren
Async поддержкаStreamingRetry логикаType hints
Установка
pip install corenПример использования
from coren import CorenClient# Инициализация клиента для on-premise установкиclient = CorenClient(base_url="https://api.internal:8080",api_key="sk_live_...")# Создание чат-запросаresponse = client.chat.completions.create(model="llama-3-70b-chat",messages=[{"role": "system", "content": "Вы - помощник банка."},{"role": "user", "content": "Какие документы нужны для кредита?"}],temperature=0.7,max_tokens=500)print(response.choices[0].message.content)# Streaming режим для длинных ответовstream = client.chat.completions.create(model="llama-3-70b-chat",messages=[{"role": "user", "content": "Расскажите о видах вкладов"}],stream=True)for chunk in stream:if chunk.choices[0].delta.content:print(chunk.choices[0].delta.content, end="")
TypeScript SDK
v1.1.0Официальный TypeScript/JavaScript клиент для платформы Coren
ESM и CommonJSNode.js и BrowserTypeScript типыReact хуки
Установка
npm install @coren/sdkПример использования
import { CorenClient } from '@coren/sdk';// Инициализация клиентаconst client = new CorenClient({baseUrl: 'https://api.internal:8080',apiKey: 'sk_live_...',});// Создание чат-запросаconst response = await client.chat.completions.create({model: 'llama-3-70b-chat',messages: [{ role: 'system', content: 'Вы - финансовый консультант банка.' },{ role: 'user', content: 'Как рассчитать ежемесячный платеж по ипотеке?' }],temperature: 0.7,});console.log(response.choices[0].message.content);// Streaming с async итераторомconst stream = await client.chat.completions.create({model: 'llama-3-70b-chat',messages: [{ role: 'user', content: 'Объясните принцип работы кредитной карты' }],stream: true,});for await (const chunk of stream) {process.stdout.write(chunk.choices[0]?.delta?.content || '');}
Go SDK
v0.9.0Официальный Go клиент для платформы Coren
Context поддержкаRetry с backoffConnection poolingMetrics
Установка
go get git.internal/coren/coren-goПример использования
package mainimport ("context""fmt""log"coren "git.internal/coren/coren-go")func main() {// Создание клиентаclient := coren.NewClient(coren.WithBaseURL("https://api.internal:8080"),coren.WithAPIKey("sk_live_..."),)// Создание запросаresp, err := client.Chat.Completions.Create(context.Background(),&coren.ChatCompletionRequest{Model: "llama-3-70b-chat",Messages: []coren.Message{{Role: "system", Content: "Вы - помощник банка"},{Role: "user", Content: "Проверьте статус моей заявки"},},Temperature: 0.7,},)if err != nil {log.Fatal(err)}fmt.Println(resp.Choices[0].Message.Content)}
Java SDK
v1.0.0Официальный Java клиент для платформы Coren
Spring Boot интеграцияReactive поддержкаConnection poolMetrics
Установка
implementation "ai.coren:coren-java:1.0.0"Пример использования
import ai.coren.CorenClient;import ai.coren.model.*;public class BankAssistant {public static void main(String[] args) {// Создание клиентаCorenClient client = CorenClient.builder().baseUrl("https://api.internal:8080").apiKey("sk_live_...").build();// Создание запросаChatCompletionRequest request = ChatCompletionRequest.builder().model("llama-3-70b-chat").addMessage(Message.system("Вы - помощник банка")).addMessage(Message.user("Какой курс валют на сегодня?")).temperature(0.7).build();ChatCompletionResponse response = client.chat().completions().create(request);System.out.println(response.getChoices().get(0).getMessage().getContent());}}
Примеры интеграции
Spring Boot интеграция
Конфигурация для Spring Boot приложений банка.
@Configurationpublic class CorenConfig {@Value("${coren.api.base-url}")private String baseUrl;@Value("${coren.api.key}")private String apiKey;@Beanpublic CorenClient corenClient() {return CorenClient.builder().baseUrl(baseUrl).apiKey(apiKey).connectionTimeout(Duration.ofSeconds(30)).readTimeout(Duration.ofSeconds(120)).retryPolicy(RetryPolicy.exponentialBackoff(3)).build();}}@Servicepublic class BankAssistantService {private final CorenClient corenClient;public String processCustomerQuery(String query, String customerId) {return corenClient.chat().completions().create(ChatCompletionRequest.builder().model("llama-3-70b-chat").addMessage(Message.system("Вы - помощник банка. ID клиента: " + customerId)).addMessage(Message.user(query)).build()).getChoices().get(0).getMessage().getContent();}}
FastAPI интеграция
Async интеграция для высоконагруженных Python сервисов.
from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom coren import AsyncCorenClientapp = FastAPI()client = AsyncCorenClient(base_url="https://api.internal:8080",api_key="sk_live_...")class ChatRequest(BaseModel):message: strcustomer_id: str@app.post("/api/assistant")async def bank_assistant(request: ChatRequest):try:response = await client.chat.completions.create(model="llama-3-70b-chat",messages=[{"role": "system", "content": f"Помощник банка. Клиент: {request.customer_id}"},{"role": "user", "content": request.message}],temperature=0.7)return {"response": response.choices[0].message.content}except Exception as e:raise HTTPException(status_code=500, detail=str(e))
Конфигурация окружения
Рекомендуемые переменные окружения для настройки SDK в production среде банка.
# .env файл для on-premise установкиCOREN_API_BASE_URL=https://api.internal:8080COREN_API_KEY=sk_live_your_api_key_here# Настройки подключенияCOREN_CONNECTION_TIMEOUT=30000COREN_READ_TIMEOUT=120000COREN_MAX_RETRIES=3# TLS/SSL настройки (для внутреннего CA)COREN_CA_CERT_PATH=/etc/ssl/certs/internal-ca.crtCOREN_VERIFY_SSL=true# ЛогированиеCOREN_LOG_LEVEL=INFOCOREN_LOG_REQUESTS=false # Не логировать тела запросов (PII данные)
Техническая поддержка
Для получения помощи по интеграции SDK обратитесь в службу поддержки платформы.