Package: unique-sdk
Unique Python SDKUnique FinanceGPT is a tailored solution for the financial industry, designed to increase productivity by automating manual workloads through AI and ChatGPT solutions.The Unique Python SDK provides access to the public API of Unique FinanceGPT. It also enables verification of Webhook signatures to ensure the authenticity of incoming Webhook requests.Table of ContentsInstallationRequirementsUsage InstructionsWebhook TriggersAvailable API ResourcesMessageChat CompletionSearchSearch StringError HandlingExamplesInstallationInstall UniqueSDK and its peer dependencyrequestsvia pip using the following commands:pipinstallunique_sdk
pipinstallrequestsRequirementsPython 3.12 (Other Python versions 3.6+ might work but are not tested)requests (peer dependency. Other HTTP request libraries might be supported in the future)Unique App-ID & API KeyPlease contact your customer success manager at Unique for your personal developer App-ID & API Key.Usage instructionsThe library needs to be configured with your Uniqueapp_id&api_key. Additionally, each individual request must be scoped to a User and provide auser_id&company_id.importunique_sdkunique_sdk.api_key="ukey_..."unique_sdk.app_id="app_..."The SDK includes a set of classes for API resources. Each class contains CRUD methods to interact with the resource.Exampleimportunique_sdkunique_sdk.api_key="ukey_..."unique_sdk.app_id="app_..."# list messages for a single chatmessages=unique_sdk.Message.list(user_id=user_id,company_id=company_id,chatId=chat_id,)print(messages.data[0].text)Webhook TriggersA core functionality of FinanceGPT is the ability for users to engage in an interactive chat feature. SDK developers can hook into this chat to provide new functionalities.Your App (refer toapp-idinRequirements) must be subscribed to each individual Unique event in order to receive a webhook.Each webhook sent by Unique includes a set of headers:X-Unique-Id:evt_...# Event id, same as in the body.X-Unique-Signature:...# A HMAC-SHA256 hex signature of the entire body.X-Unique-Version:1.0.0# Event payload version.X-Unique-Created-At:1705960141# Unix timestamp (seconds) of the delivery time.X-Unique-User-Id:...# The user who initiated the message.X-Unique-Company-Id:...# The company to which the user belongs.Success & Retry on FailureWebhooks are considered successfully delivered if your endpoint returns a status code between200and299.If your endpoint returns a status code of300-399,429, or500-599, Unique will retry the delivery of the webhook with an exponential backoff up to five times.If your endpoint returns any other status (e.g.,404), it is marked as expired and will not receive any further requests.Webhook Signature VerificationThe webhook body, containing a timestamp of the delivery time, is signed with HMAC-SHA256. Verify the signature by constructing theeventwith theunique_sdk.Webhookclass:fromhttpimportHTTPStatusfromflaskimportFlask,jsonify,requestimportunique_sdkendpoint_secret="YOUR_ENDPOINT_SECRET"@app.route("/webhook",methods=["POST"])defwebhook():event=Nonepayload=request.datasig_header=request.headers.get("X-Unique-Signature")timestamp=request.headers.get("X-Unique-Created-At")ifnotsig_headerornottimestamp:print("⚠️  Webhook signature or timestamp headers missing.")returnjsonify(success=False),HTTPStatus.BAD_REQUESTtry:event=unique_sdk.Webhook.construct_event(payload,sig_header,timestamp,endpoint_secret)exceptunique_sdk.SignatureVerificationErrorase:print("⚠️  Webhook signature verification failed. "+str(e))returnjsonify(success=False),HTTPStatus.BAD_REQUESTTheconstruct_eventmethod will compare the signature and raise aunique_sdk.SignatureVerificationErrorif the signature does not match. It will also raise this error if thecreatedAttimestamp is outside of a default tolerance of 5 minutes. Adjust thetoleranceby passing a fifth parameter to the method (tolerance in seconds), e.g.:event=unique_sdk.Webhook.construct_event(payload,sig_header,timestamp,endpoint_secret,0)Available Unique EventsUser Message Created{"id":"evt_...",// see header"version":"1.0.0",// see header"event":"unique.chat.user-message.created",// The name of the event"createdAt":"1705960141",// see header"userId":"...",// see header"companyId":"...",// see header"payload":{"chatId":"chat_...",// The id of the chat"assistantId":"assistant_...",// The id of the selected assistant"text":"Hello, how can I help you?"// The user message}}This webhook is triggered for every new chat message sent by the user. This event occurs regardless of whether it is the first or a subsequent message in a chat. Use theunique_sdk.Messageclass to retrieve other messages from the samechatIdor maintain a local state of the messages in a single chat.This trigger can be used in combination with assistants marked asexternal. Those assistants will not execute any logic, enabling your code to respond to the user message and create an answer.External Module Chosen{"id":"evt_...","version":"1.0.0","event":"unique.chat.external-module.chosen","createdAt":"1705960141",// Unix timestamp (seconds)"userId":"...","companyId":"...","payload":{"name":"example-sdk",// The name of the module selected by the module chooser"description":"Example SDK",// The description of the module"configuration":{},// Module configuration in JSON format"chatid":"chat_...",// The chat ID"assistantId:":"assistant_...",// The assistant ID"userMessage":{"id":"msg_...","text":"Hello World!",// The user message leading to the module selection"createdAt":"2024-01-01T00:00:00.000Z"// ISO 8601},"assistantMessage":{"id":"msg_...","createdAt":"2024-01-01T00:00:00.000Z"// ISO 8601}}}This Webhook is triggered when the Unique FinanceGPT AI selects an external module as the best response to a user message. The module must be marked asexternaland available for the assistant used in the chat to be selected by the AI.Unique's UI will create an emptyassistantMessagebelow the user message and update this message with status updates.The SDK is expected to modify this assistantMessage with its answer to the user message.unique_sdk.Message.modify(user_id=user_id,company_id=company_id,id=assistant_message_id,chatId=chat_id,text="Here is your answer.",)Available API ResourcesMessageChat CompletionSearchSearch StringMessageunique_sdk.Message.listRetrieve a list of messages for a providedchatId.messages=unique_sdk.Message.list(user_id=user_id,company_id=company_id,chatId=chat_id,)unique_sdk.Message.retrieveGet a single chat message.message=unique_sdk.Message.retrieve(user_id=user_id,company_id=company_id,id=message_id,chatId=chat_id,)unique_sdk.Message.createCreate a new message in a chat.message=unique_sdk.Message.create(user_id=user_id,company_id=company_id,chatId=chat_id,assistantId=assistant_id,text="Hello.",role="ASSISTANT",)unique_sdk.Message.modifyModify an existing chat message.message=unique_sdk.Message.modify(user_id=user_id,company_id=company_id,id=message_id,chatId=chat_id,text="Updated message text")unique_sdk.Message.deleteDelete a chat message.message=unique_sdk.Message.delete(message_id,user_id=user_id,company_id=company_id,chatId=chat_id,)Warning:Currently, the deletion of a chat message does not automatically sync with the user UI. Users must refresh the chat page to view the updated state. This issue will be addressed in a future update of our API.Chat Completionunique_sdk.ChatCompletion.createSend a prompt to an AI model supported by Unique FinanceGPT and receive a result. Themessagesattribute must follow theOpenAI API format.chat_completion=unique_sdk.ChatCompletion.create(company_id=company_id,model="AZURE_GPT_35_TURBO",messages=[{"role":"system","content":"You are a helpful assistant."},{"role":"user","content":"Hello!"},])Searchunique_sdk.Search.createSearch the Unique FinanceGPT Knowledge database for RAG (Retrieval-Augmented Generation). The API supports vector search and asearchTypethat combines vector and full-text search, enhancing the precision of search results.search=unique_sdk.Search.create(user_id,company_id,chatId=chat_idsearchString="What is the meaning of life, the universe and everything?",searchType="VECTOR",)Search Stringunique_sdk.SearchString.createUser messages are sometimes suboptimal as input prompts for vector or full-text knowledge base searches. This is particularly true as a conversation progresses and a user question may lack crucial context for a successful search.This API transforms and translates (into English) the user's message into an ideal search string for use in theSearch.createAPI method.Adding achatIdormessagesas arguments allows the message history to provide additional context to the search string. For example, "Who is the author?" will be expanded to "Who is the author of the book 'The Hitchhiker's Guide to the Galaxy'?" if previous messages referenced the book.search_string=unique_sdk.SearchString.create(user_id,company_id,prompt="Was ist der Sinn des Lebens, des Universums und des ganzen Rests?",chat_id=chat_id)Error HandlingExamplesAn example Flask app demonstrating the usage of each API resource and how to interact with Webhooks is available in our repository at/examples/custom-assistant.CreditsThis is afork/ inspired-by the fantastic Stripe Python SDK (https://github.com/stripe/stripe-python).