Skip to main content
Glama
ai_chat_assistant.cpython-311.pyc21 kB
� �n�hY=���ddlZddlmZmZmZddlmZddlZddlZddlZej e ��Z Gd�d��Z dS)�N)�Dict�List�Any)�datetimec � �eZdZddefd�Z ddedeeefdeedeeeffd�Zdedeeeffd �Z defd �Z dedeeeffd �Z ded edeefd �Z deeeffd�Z deefd�Zd�ZdS)�AIChatAssistantN�openai_api_keyc���|ptjdd��|_tjdd��|_tjdd��|_g|_i|_dS)N�OPENAI_API_KEY� c3_api_key�OPENAI_API_URLzhttps://api.comput3.ai/v1� OPENAI_MODELz llama3:70b)�os�getenvr �openai_api_url�model�conversation_history� user_context)�selfr s �+/home/runner/workspace/ai_chat_assistant.py�__init__zAIChatAssistant.__init__ s]��,�Y�� �:J�L�0Y�0Y��� �i�(8�:U�V�V����Y�~�|�<�<�� �%'��!������� user_message�portfolio_data�transaction_history�returnc� � |r ||jd<|r|dd�|jd<|jr|�|��}n|�|��}|j�||dt j�����d���t|j��dkr|jdd�|_|S#t$r/}t� d |����d gd �d d �cYd}~Sd}~wwxYw)z%Handle chat conversation with context� portfolio�����N� transactions�message)�user�ai� timestamp� i����z Chat failed: zDSorry, I'm having trouble understanding right now. Please try again!)zCheck portfoliozShow transactions�Get strategy advice�error�r!� suggestions�type) rr �_get_ai_response�_get_fallback_responser�appendr�utcnow� isoformat�len� Exception�loggerr')rrrr�response�es r�chatzAIChatAssistant.chats]�� �� @�1?��!�+�.�"� M�4G����4L��!�.�1��"� E��0�0��>�>����6�6�|�D�D�� � %� ,� ,�$��y�)�%�_�.�.�8�8�:�:�.�.� � � ��4�,�-�-��2�2�,0�,E�c�d�d�,K��)��O��� � � � �L�L�,��,�,� -� -� -�a�^�^�^���� � � � � � ����� ���s�CC � D�$C=�7D�=Dc�b� |���}d|�d�}d|j��dd�}d|d�g}|jdd �D]>}|�d |d d���|�d |d d����?|�d |d���|j|d ddd�}t j|j�d�||d���}|jdkr\|� ��} | dddd� ��} |� || ��} | | dd�St� d|j�d|j����|�|��S#t $r<} t� d| ����|�|��cYd } ~ Sd } ~ wwxYw)z=Get AI-powered response using modern OpenAI API with full NLPayYou are an expert DeFi financial advisor AI with deep knowledge of: - Decentralized Finance (DeFi) protocols, yields, and strategies - Blockchain networks (Ethereum, Polygon, Solana) - Portfolio management and risk assessment - Trading, lending, yield farming, and staking - Market analysis and investment advice - Technical analysis and on-chain data User Portfolio Context: u: Personality & Communication: - Friendly, conversational, and helpful - Explain complex DeFi concepts in simple, everyday language - Use emojis occasionally (📈, 💰, 🚀, ⚠️, 🤔) - Always provide actionable, specific advice - Be encouraging but honest about risks - Answer ANY question about finance, DeFi, crypto, or investment strategies Capabilities: - Analyze portfolio allocations and suggest improvements - Explain why transactions happened and their benefits - Recommend investment strategies based on risk tolerance - Compare DeFi protocols and their yields/risks - Help with yield farming, lending, and staking decisions - Provide market insights and trend analysis - Answer educational questions about blockchain and DeFi Always give detailed, helpful responses regardless of the question complexity.zBearer zapplication/json)� Authorizationz Content-Type�system)�role�content�����Nr"� assistantr#i�gffffff�?g�������?)r�messages� max_tokens� temperature�top_pz/chat/completions�)�headers�json�timeout���choicesrr!r:� ai_responser(zAI API returned status z: zAI response failed: )�_build_contextr rr-r�requests�postr� status_coderC�strip�_generate_smart_suggestionsr2�warning�textr,r1) rr�context� system_promptrBr=�conv�payloadr3�data� ai_messager)r4s rr+z AIChatAssistant._get_ai_response:sB��T =��)�)�+�+�G�R�!�R�R�R�M�<"A�4�+>�!@�!@� 2���G� "*�m�D�D�E�H��1�"�#�#�6� N� N������D��L� I� I�J�J�J������d�� L� L�M�M�M�M� �O�O�V� �E�E� F� F� F���$�!�"�� ��G� �}��&�9�9�9���� ���H��#�s�*�*��}�}����!�)�_�Q�/� �:�9�E�K�K�M�M� �#�>�>�|�Z�X�X� � *�#.�)���� ���`��9M�`�`�QY�Q^�`�`�a�a�a��2�2�<�@�@�@��� =� =� =� �N�N�5�!�5�5� 6� 6� 6��.�.�|�<�<� <� <� <� <� <� <����� =���s$�D&E(�)>E(�( F.�21F)�#F.�)F.c���g}d|jvr�|jd}|�d|�dd��d����|�dg��}|r?d�|dd �D��}|�d d �|������d |jvr2t |jd ��}|�d |����|rd�|��ndS)zBuild context string for AIrzPortfolio Value: $�total_value_usdrz,.2f�tokensc�p�g|]3}|�dd���d|�dd��d�d���4S)�symbol�z (� percentagerz.1fz%))�get)�.0�ts r� <listcomp>z2AIChatAssistant._build_context.<locals>.<listcomp>�sX�� 4� 4� 4�#$�$%�5�5��2�#6�#6� X� X�!�%�%� �a�:P�:P� X� X� X� X� 4� 4� 4rN�zTop Holdings: z, r zRecent Transactions: z | zNo portfolio data available)rr-r]�joinr0)r� context_partsrrX� top_holdings� recent_txss rrHzAIChatAssistant._build_context�s��� � �$�+� +� +��)�+�6�I� � � �!`�i�m�m�DU�WX�6Y�6Y�!`�!`�!`� a� a� a��]�]�8�R�0�0�F�� Q� 4� 4�(.�r��r� � 4� 4� 4� ��$�$�%O�d�i�i� �6M�6M�%O�%O�P�P�P� �T�.� .� .��T�.�~�>�?�?�J� � � �!E��!E�!E� F� F� F�,9�\�u�z�z�-�(�(�(�?\�\rc�,��|����t�fd�dD����rdgd�dd�St�fd�dD����rd gd �dd�St�fd �d D����rd gd�dd�St�fd�dD����rdgd�dd�St�fd�dD����rdgd�dd�St�fd�dD����rdgd�dd�St�fd�dD����rd}gd�}nd}gd �}||dd�S)!z8Enhanced fallback response with better NLP understandingc3� �K�|]}|�vV�� dS�N��r^�word�user_message_lowers �r� <genexpr>z9AIChatAssistant._get_fallback_response.<locals>.<genexpr>�s)�����j�j�d�t�)�)�j�j�j�j�j�jr)�why�moved� transaction�transfer�swapu<I can see you're asking about recent transactions! 📊 While my AI brain is temporarily offline, I can still help explain common transaction patterns. Most moves are typically for yield optimization, gas cost reduction, or portfolio rebalancing. Check your dashboard for detailed transaction history with reasoning.)zView transaction details�Check portfolio healthzExplain strategy logic�fallbackr(c3� �K�|]}|�vV�� dSrhrirjs �rrmz9AIChatAssistant._get_fallback_response.<locals>.<genexpr>��)�����i�i���+�+�i�i�i�i�i�ir)�buy�sell�should� recommend�investu8Great investment question! 💡 While my full AI analysis isn't available right now, I can share some general wisdom: diversification across 3-5 quality protocols, keeping 20-30% in stablecoins, and focusing on established DeFi blue chips (Aave, Uniswap, Compound) tends to work well. What's your risk tolerance?)zAnalyze portfolio allocationzFind safe yield opportunities�Learn risk managementc3� �K�|]}|�vV�� dSrhrirjs �rrmz9AIChatAssistant._get_fallback_response.<locals>.<genexpr>�rvr)�gas�fees� expensive�cost�ethereumu8Ah, gas fees - the eternal crypto challenge! ⛽ Here's the deal: Ethereum mainnet can be pricey ($10-100+ per transaction), but Layer 2s like Polygon offer 90%+ savings. Consider batching transactions, using L2s for smaller amounts, or timing transactions during low-usage periods (weekends, early morning UTC).)zCompare network costszLearn about Layer 2zOptimize transaction timingc3� �K�|]}|�vV�� dSrhrirjs �rrmz9AIChatAssistant._get_fallback_response.<locals>.<genexpr>�s)�����q�q���+�+�q�q�q�q�q�qr)�yield�earn�apy�interestr�profitu Yield hunting - my favorite topic! 📈 Current DeFi landscape offers: Stablecoin lending (3-8% APY, low risk), LP farming (5-20%+ but impermanent loss risk), and staking (4-12%, varies by protocol). Higher yields = higher risks. Want specific protocol recommendations?)�Compare yield rateszLearn about farming riskszFind stable earningsc3� �K�|]}|�vV�� dSrhrirjs �rrmz9AIChatAssistant._get_fallback_response.<locals>.<genexpr>�s)�����h�h���+�+�h�h�h�h�h�hr)�risk�safe� dangerous�loss�secureu.Smart to ask about risks! ⚠️ DeFi risks include: smart contract bugs, impermanent loss (LP farming), liquidation (borrowing), and protocol governance risks. Mitigation strategies: diversify across protocols, start small, use established platforms, and never invest more than you can afford to lose.)zAssess portfolio riskszLearn risk mitigationzCheck protocol safety scoresc3� �K�|]}|�vV�� dSrhrirjs �rrmz9AIChatAssistant._get_fallback_response.<locals>.<genexpr>�s)�����r�r���+�+�r�r�r�r�r�rr)�defi�what�how�explain�learn� understandu7Love the curiosity! 🤓 DeFi (Decentralized Finance) lets you do traditional banking without banks - lending, borrowing, trading, earning interest. Key concepts: smart contracts (automated agreements), liquidity pools (shared funds for trading), and composability (protocols working together like Lego blocks).)zLearn DeFi basicszExplore protocolszUnderstand smart contractsc3� �K�|]}|�vV�� dSrhrirjs �rrmz9AIChatAssistant._get_fallback_response.<locals>.<genexpr>�s)�����i�i�$�4�-�-�i�i�i�i�i�ir)r�balance�holdings�assetsuI see you're asking about portfolio management! 💼 Even without my full AI capabilities, I can suggest checking your asset allocation, diversification across different DeFi sectors, and monitoring for opportunities to optimize yields while managing risk.)rszOptimize allocation�Find rebalancing opportunitiesu�Thanks for the question! 🤖 While my AI is temporarily limited, I'm still here to help with DeFi strategy, yield optimization, risk assessment, and general crypto guidance. I can discuss any aspect of decentralized finance you're curious about!)zAsk about specific protocolsr&zLearn DeFi conceptszCheck market opportunities)�lower�any)rrr!r)rls @rr,z&AIChatAssistant._get_fallback_response�s?���)�/�/�1�1�� �j�j�j�j�6i�j�j�j� j� j�7 �Z�o�o�o�"��� � �i�i�i�i�8h�i�i�i� i� i�0 �V�y�y�y�"��� � �i�i�i�i�8h�i�i�i� i� i�) �V�n�n�n�"��� � �q�q�q�q�8p�q�q�q� q� q�" �k�k�k�k�"��� � �h�h�h�h�8g�h�h�h� h� h� �L�r�r�r�"��� � �r�r�r�r�8q�r�r�r� r� r� �U�g�g�g�"��� ��i�i�i�i�:h�i�i�i�i�i� K�]��q�q�q� � �T��K�K�K� �#�*�"��� rrGc�<���|����|����g}t�fd�dD����r|�gd���t��fd�dD����r|�gd���t�fd�dD����r|�gd ���t�fd �d D����r|�gd ���t��fd �dD����r|�gd���t��fd�dD����r|�gd���t�fd�dD����r|�gd���|sgd�}|dd�S)zAGenerate intelligent contextual suggestions based on conversationc3� �K�|]}|�vV�� dSrhri�r^rk� user_lowers �rrmz>AIChatAssistant._generate_smart_suggestions.<locals>.<genexpr>��(�����`�`�d�t�z�!�`�`�`�`�`�`r)r�holdingr�� allocation)zShow portfolio breakdownzCheck risk scorer�c3�(�K�|] }|��gzvV�� dSrhri�r^rk�response_lowerr�s ��rrmz>AIChatAssistant._generate_smart_suggestions.<locals>.<genexpr>�s0�����k�k��t�z�^�$4�4�4�k�k�k�k�k�kr)r�r�r��stake�farm)r�zShow farming opportunitieszCalculate potential returnsc3� �K�|]}|�vV�� dSrhrir�s �rrmz>AIChatAssistant._generate_smart_suggestions.<locals>.<genexpr>�s(�����W�W�d�t�z�!�W�W�W�W�W�Wr)rp�moverr�trade)zExplain transaction logiczShow gas optimizationzView trading historyc3� �K�|]}|�vV�� dSrhrir�s �rrmz>AIChatAssistant._generate_smart_suggestions.<locals>.<genexpr>�r�r)r�r�r�r�r�)zLearn more DeFi basicszExplore advanced strategieszGet market insightsc3�(�K�|] }|��gzvV�� dSrhrir�s ��rrmz>AIChatAssistant._generate_smart_suggestions.<locals>.<genexpr>�s0�����j�j��t�z�^�$4�4�4�j�j�j�j�j�jr)�aave�uniswap�compound�curve)zCompare protocolszCheck protocol riskszView protocol analyticsc3�(�K�|] }|��gzvV�� dSrhrir�s ��rrmz>AIChatAssistant._generate_smart_suggestions.<locals>.<genexpr>s0�����d�d��t�z�^�$4�4�4�d�d�d�d�d�dr)r�r�r�r�)zAssess portfolio riskr|z Set up alertsc3� �K�|]}|�vV�� dSrhrir�s �rrmz>AIChatAssistant._generate_smart_suggestions.<locals>.<genexpr>s(�����[�[�d�t�z�!�[�[�[�[�[�[r)�price�market�trend�bull�bear)zGet market analysiszCheck price trendszSet price alerts)zAnalyze my portfolio healthzFind the best yields availablezExplain current DeFi trendszHelp optimize my strategyNra)r�r��extend)rrrGr)r�r�s @@rrMz+AIChatAssistant._generate_smart_suggestions�s;����!�'�'�)�)� �$�*�*�,�,��� � �`�`�`�`�._�`�`�`� `� `� s� � � �q�q�q� r� r� r� �k�k�k�k�k�Aj�k�k�k� k� k� u� � � �s�s�s� t� t� t� �W�W�W�W�.V�W�W�W� W� W� o� � � �m�m�m� n� n� n� �`�`�`�`�._�`�`�`� `� `� q� � � �o�o�o� p� p� p� �j�j�j�j�j�Ai�j�j�j� j� j� i� � � �g�g�g� h� h� h� �d�d�d�d�d�Ac�d�d�d� d� d� d� � � �b�b�b� c� c� c� �[�[�[�[�.Z�[�[�[� [� [� b� � � �`�`�`� a� a� a�� ����K��2�A�2��rc��t|j��|���|j���|jr|jddndd�S)zGet summary of conversation�����r$N)�total_messages� recent_topicsr�last_interaction)r0r�_extract_topicsr�keys�rs r�get_conversation_summaryz(AIChatAssistant.get_conversation_summarys`��"�$�";�<�<�!�1�1�3�3� �-�2�2�4�4�NR�Ng� q�� 9�"� =�k� J� J�mq�  � � rc���g}|jD]�}|d����t�fd�dD����r|�d���Mt�fd�dD����r|�d���~t�fd�d D����r|�d ����t�fd �d D����r|�d ����t t |����S)z%Extract main topics from conversationr"c3� �K�|]}|�vV�� dSrhri�r^rkr!s �rrmz2AIChatAssistant._extract_topics.<locals>.<genexpr>!s'�����H�H�t�4�7�?�H�H�H�H�H�Hr)rr�zPortfolio Analysisc3� �K�|]}|�vV�� dSrhrir�s �rrmz2AIChatAssistant._extract_topics.<locals>.<genexpr>#�'�����J�J��T�W�_�J�J�J�J�J�Jr)r�r�r�zYield Optimizationc3� �K�|]}|�vV�� dSrhrir�s �rrmz2AIChatAssistant._extract_topics.<locals>.<genexpr>%s'�����H�H��T�W�_�H�H�H�H�H�Hr)�strategyr{zInvestment Strategyc3� �K�|]}|�vV�� dSrhrir�s �rrmz2AIChatAssistant._extract_topics.<locals>.<genexpr>'r�r)rprozTransaction History)rr�r�r-�list�set)r�topicsrRr!s @rr�zAIChatAssistant._extract_topicss1������-� 5� 5�D��6�l�(�(�*�*�G��H�H�H�H�/G�H�H�H�H�H� 5�� � �2�3�3�3�3��J�J�J�J�1I�J�J�J�J�J� 5�� � �2�3�3�3�3��H�H�H�H�1G�H�H�H�H�H� 5�� � �3�4�4�4�4��J�J�J�J�1I�J�J�J�J�J� 5�� � �3�4�4�4���C��K�K� � � rc�"�g|_i|_dS)zClear conversation historyN)rrr�s r� clear_historyzAIChatAssistant.clear_history,s��$&��!�����rrh)NN)�__name__� __module__� __qualname__�strrrrrr5r+rHr,rMr�r�r�rirrrr s���������s�����HL�/3�#�#��#�d�3��8�n�#�"&�t�*�#�8<�S�#�X��#�#�#�#�JV=�S�V=�T�#�s�(�^�V=�V=�V=�V=�p]��]�]�]�]�(<�3�<�4��S��>�<�<�<�<�|-��-�#�-�RV�WZ�R[�-�-�-�-�^ �$�s�C�x�.� � � � �!��c��!�!�!�!� ����rr) �logging�typingrrrrrCrrI� getLoggerr�r2rrirr�<module>r�s�������"�"�"�"�"�"�"�"�"�"������� � � � � � � � ����� �� �8� $� $��d�d�d�d�d�d�d�d�d�dr

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/JMadhan1/OneDefi-MCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server