paint-brush
BigQuery ve Langchain ile Nasıl Veri Analizi Asistanı Oluşturdum?ile@yi
435 okumalar
435 okumalar

BigQuery ve Langchain ile Nasıl Veri Analizi Asistanı Oluşturdum?

ile Yi Ai11m2024/06/10
Read on Terminal Reader

Çok uzun; Okumak

Streamlit ve Google Cloud DLP gibi araçlarla veri analizini otomatikleştirmek, işlemeyi kolaylaştırmak ve veri gizliliğini sağlamak için Langchain, OpenAI ve BigQuery'den yararlanın.
featured image - BigQuery ve Langchain ile Nasıl Veri Analizi Asistanı Oluşturdum?
Yi Ai HackerNoon profile picture



İşletmeler her gün çok büyük miktarda veri ürettiğinden, özellikle karmaşık veri kümeleri ve büyük hacimli veriler söz konusu olduğunda tüm bu bilgilerden yararlı bilgiler elde etmek zor olabilir. Ancak üretken yapay zeka ile veri analizini düzenleyip otomatikleştirerek onu verimli ve erişilebilir hale getirebiliriz. Bu makalede size Google Langchain , OpenAI, BigQuery ve Veri Kaybını Önleme (DLP) kullanarak bir AI veri analizi asistanının nasıl kurulacağını ve kullanılacağını göstereceğim.


Kullanım Örneği: BigQuery ile Veri Analizini Otomatikleştirme

Çözüm tasarımı

Çözüm, veri analizini otomatikleştirmek için BigQuery veri kümesiyle etkileşime giren Langchain ve OpenAI kullanarak bir Streamlit uygulaması kurmayı içeriyor. Bu temsilci, PII müşteri özelliklerinin maskelenmesi ve verilerin görselleştirilmesi gibi belirli görevler için özel araçlar kullanacaktır. Ayrıca aracı, bağlamsal olarak doğru yanıtlar sağlayacak şekilde sohbet geçmişini tutacak şekilde yapılandırılacaktır.


Aşağıda çözüm mimarisinin bir diyagramı verilmiştir:


Aşağıdaki tabloları içeren bir BigQuery veri kümesine sahip olduğumuz bir senaryoyu ele alalım:

  • Müşteri Tablosu : Müşteri verilerini içerir.
  • İletişim Tablosu : Müşteri iletişim bilgilerini içerir.
  • Müşteri Adres Tablosu : Müşterileri adreslere bağlar.
  • Adres Tablosu : Adres bilgilerini içerir.
  • İş İstatistikleri Tablosu : Verileri kesip müşteri profili tablolarına yükleyen ETL toplu iş özetlerini günlüğe kaydeder


Langchain'i kurma

Langchain nedir?

LangChain, yapay zeka geliştiricilerine dil modellerini harici veri kaynaklarına bağlamaya yönelik araçlar sağlar. Açık kaynaklıdır ve aktif bir topluluk tarafından desteklenmektedir. Kuruluşlar LangChain'i ücretsiz olarak kullanabilir ve çerçeve konusunda uzman diğer geliştiricilerden destek alabilir.


Langchain kullanarak veri analizi yapabilmek için öncelikle Langchain ve OpenAI kütüphanelerini kurmamız gerekiyor. Bu, gerekli kütüphaneleri indirerek ve ardından bunları projenize aktararak yapılabilir.


Langchain'i yükleyin:

 pip install langchain matplotlib pandas streamlit pip install -qU langchain-openai langchain-community


Langchain Modelini tanımlayın ve Bigquery bağlantısını kurun:

 import os import re import streamlit as st from google.cloud import dlp_v2 from google.cloud.dlp_v2 import types from langchain.agents import create_sql_agent from langchain_community.vectorstores import FAISS from langchain_core.example_selectors import SemanticSimilarityExampleSelector from langchain_core.messages import AIMessage from langchain_core.prompts import ( SystemMessagePromptTemplate, PromptTemplate, FewShotPromptTemplate, ) from langchain_core.prompts.chat import ( ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder, ) from langchain.memory import ConversationBufferMemory from langchain_experimental.utilities import PythonREPL from langchain_openai import ChatOpenAI, OpenAIEmbeddings from langchain.sql_database import SQLDatabase from langchain.tools import Tool service_account_file = f"{os.getcwd()}/service-account-key.json" os.environ["OPENAI_API_KEY"] = ( "xxxxxx" ) os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = service_account_file model = ChatOpenAI(model="gpt-4o", temperature=0) project = "lively-metrics-295911" dataset = "customer_profiles" sqlalchemy_url = ( f"bigquery://{project}/{dataset}?credentials_path={service_account_file}" ) db = SQLDatabase.from_uri(sqlalchemy_url)


Özel Araçlar Ayarlama

Temsilcimizin yeteneklerini geliştirmek amacıyla, PII verilerini maskelemek ve verileri görselleştirmek gibi belirli görevlere yönelik özel araçlar ayarlayabiliriz.


  1. Google Cloud DLP ile Kimlik Bilgilerini Maskeleme

    Veri gizliliği çok önemlidir. Çıkışlardaki kişisel bilgileri korumak için Google Cloud Veri Kaybını Önleme'yi (DLP) kullanabiliriz. Yanıtta mevcut olan tüm PII verilerini maskelemek için DLP API'sini çağıran özel bir araç oluşturacağız.


 def mask_pii_data(text): dlp = dlp_v2.DlpServiceClient() project_id = project parent = f"projects/{project_id}" info_types = [ {"name": "EMAIL_ADDRESS"}, {"name": "PHONE_NUMBER"}, {"name": "DATE_OF_BIRTH"}, {"name": "LAST_NAME"}, {"name": "STREET_ADDRESS"}, {"name": "LOCATION"}, ] deidentify_config = types.DeidentifyConfig( info_type_transformations=types.InfoTypeTransformations( transformations=[ types.InfoTypeTransformations.InfoTypeTransformation( primitive_transformation=types.PrimitiveTransformation( character_mask_config=types.CharacterMaskConfig( masking_character="*", number_to_mask=0, reverse_order=False ) ) ) ] ) ) item = {"value": text} inspect_config = {"info_types": info_types} request = { "parent": parent, "inspect_config": inspect_config, "deidentify_config": deidentify_config, "item": item, } response = dlp.deidentify_content(request=request) return response.item.value


  1. Python REPL'i

    Daha sonra, LLM'nin Python kullanarak veri görselleştirmesini gerçekleştirmesini sağlamak için Python REPL'den yararlanacağız ve temsilcimiz için özel bir araç tanımlayacağız.


 python_repl = PythonREPL()


Şimdi mask_pii_data ve python_repl:

 def sql_agent_tools(): tools = [ Tool.from_function( func=mask_pii_data, name="mask_pii_data", description="Masks PII data in the input text using Google Cloud DLP.", ), Tool( name="python_repl", description=f"A Python shell. Use this to execute python commands. \ Input should be a valid python command. \ If you want to see the output of a value, \ you should print it out with `print(...)`.", func=python_repl.run, ), ] return tools

Birkaç Çekim Örneklerini Kullanma

Modele birkaç örnek vermek, yanıtlarını yönlendirmeye ve performansı artırmaya yardımcı olur.

Örnek SQL sorgularının tanımlanması,

 # Example Queries sql_examples = [ { "input": "Count of Customers by Source System", "query": f""" SELECT source_system_name, COUNT(*) AS customer_count FROM `{project}.{dataset}.customer` GROUP BY source_system_name ORDER BY customer_count DESC; """, }, { "input": "Average Age of Customers by Gender", "query": f""" SELECT gender, AVG(EXTRACT(YEAR FROM CURRENT_DATE()) - EXTRACT(YEAR FROM dob)) AS average_age FROM `{project}.{dataset}.customer` GROUP BY gender; """, }, ... ]


Daha sonra birkaç çekimli bilgi istemi şablonuna örnekler ekleyin.

 example_selector = SemanticSimilarityExampleSelector.from_examples( sql_examples, OpenAIEmbeddings(), FAISS, k=2, input_keys=["input"], )


Daha sonra önek ve son eki tanımlayın ve ardından few_shot_prompt doğrudan from_messages fabrika yöntemine iletin.


Not: SUFFIX'te bir {chat_history} değişkeni var, bunu bir sonraki adımda aracıyı oluşturup bellek eklediğimizde açıklayacağım.

 PREFIX = """ You are a SQL expert. You have access to a BigQuery database. Identify which tables can be used to answer the user's question and write and execute a SQL query accordingly. Given an input question, create a syntactically correct SQL query to run against the dataset customer_profiles, then look at the results of the query and return the answer. Unless the user specifies a specific number of examples they wish to obtain, always limit your query to at most {top_k} results. You can order the results by a relevant column to return the most interesting examples in the database. Never query for all the columns from a specific table; only ask for the relevant columns given the question. You have access to tools for interacting with the database. Only use the information returned by these tools to construct your final answer. You MUST double check your query before executing it. If you get an error while executing a query, rewrite the query and try again.DO NOT make any DML statements (INSERT, UPDATE, DELETE, DROP etc.) to the database. If the question does not seem related to the database, just return "I don't know" as the answer. If the user asks for a visualization of the results, use the python_agent tool to create and display the visualization. After obtaining the results, you must use the mask_pii_data tool to mask the results before providing the final answer. """ SUFFIX = """Begin! {chat_history} Question: {input} Thought: I should look at the tables in the database to see what I can query. Then I should query the schema of the most relevant tables. {agent_scratchpad}""" few_shot_prompt = FewShotPromptTemplate( example_selector=example_selector, example_prompt=PromptTemplate.from_template( "User input: {input}\nSQL query: {query}" ), prefix=PREFIX, suffix="", input_variables=["input", "top_k"], example_separator="\n\n", ) messages = [ SystemMessagePromptTemplate(prompt=few_shot_prompt), MessagesPlaceholder(variable_name="chat_history"), HumanMessagePromptTemplate.from_template("{input}"), AIMessage(content=SUFFIX), MessagesPlaceholder(variable_name="agent_scratchpad"), ] prompt = ChatPromptTemplate.from_messages(messages)


Değişkenlerin Açıklaması

  • input : Kullanıcının girişi veya sorgusu.

  • Agent_scratchpad : Ara adımlar veya düşünceler için geçici bir depolama alanı.

  • chat_history : Bağlamı korumak için önceki etkileşimleri takip eder.

  • hand_parsing_errors : Aracının ayrıştırma hatalarını düzgün bir şekilde işleyebilmesini ve bu hatalardan kurtulabilmesini sağlar.

  • bellek : Sohbet geçmişini depolamak ve almak için kullanılan modül.


Son adımın zamanı geldi. Uygulamayı oluşturalım!


Streamlit ile Yüksek Lisans Uygulaması Oluşturma

Yeni oluşturduğumuz Langchain aracısını test etmek amacıyla etkileşimli bir arayüz oluşturmak için Streamlit'i kullanabiliriz.


 st.title("Data Analysis Assistant") if "history" not in st.session_state: st.session_state.history = [] user_input = st.text_input("Ask your question:") if st.button("Run Query"): if user_input: with st.spinner("Processing..."): st.session_state.history.append(f"User: {user_input}") response = agent_executor.run(input=user_input) if "sandbox:" in response: response = response.replace(f"sandbox:", "") match = re.search(r"\((.+\.png)\)", response) if match: image_file_path = match.group(1) if os.path.isfile(image_file_path): st.session_state.history.append({"image": image_file_path}) else: st.error("The specified image file does not exist.") else: st.session_state.history.append(f"Agent: {response}") st.experimental_rerun() else: st.error("Please enter a question.") for message in st.session_state.history: if isinstance(message, str): st.write(message) elif isinstance(message, dict) and "image" in message: st.image(message["image"])


Her şeyi ayarladık. Streamlit uygulamasını çalıştıralım

 streamlit run app.py


ve birkaç analiz sorusu sorarak test edin.


Çözüm

Langchain ve OpenAI'den yararlanarak karmaşık veri analizi görevlerini otomatikleştirebilir, büyük veri kümelerinden içgörü elde etmeyi çok daha kolay hale getirebiliriz. Bu yaklaşım hem zamandan tasarruf sağlar hem de doğru ve tutarlı analiz yapılmasını sağlar. İster müşteri profilleri, iletişim bilgileri veya iş istatistikleriyle çalışıyor olun, yapay zeka destekli bir veri analizi asistanı, veri işleme yeteneklerinizi büyük ölçüde geliştirebilir. Kaynak kodunun tamamı için şu adresi ziyaret edin: GitHub deposu .