Flutra commited on
Commit
fe5564b
·
1 Parent(s): e9a9c8c

update app and requirements for API documentation chatbot

Browse files
Files changed (2) hide show
  1. app.py +115 -50
  2. requirements.txt +7 -1
app.py CHANGED
@@ -1,64 +1,129 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
  demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
  ],
 
 
 
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
  demo.launch()
 
1
  import gradio as gr
2
+ import os
3
+ from langchain.chains import ConversationalRetrievalChain
4
+ from langchain.memory import ConversationBufferMemory
5
+ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
6
+ from langchain.prompts import PromptTemplate
7
+ from langchain_community.vectorstores import Chroma
8
 
9
+ def create_qa_chain():
10
+ """
11
+ Create the QA chain with the loaded vectorstore
12
+ """
13
+ # Initialize embeddings and load vectorstore
14
+ embeddings = OpenAIEmbeddings()
15
+ vectorstore = Chroma(
16
+ persist_directory="./vectorstore",
17
+ embedding_function=embeddings
18
+ )
19
+
20
+ # Set up retriever
21
+ retriever = vectorstore.as_retriever(
22
+ search_type="mmr",
23
+ search_kwargs={
24
+ "k": 6,
25
+ "fetch_k": 20,
26
+ "lambda_mult": 0.3,
27
+ }
28
+ )
29
+
30
+ # Set up memory
31
+ memory = ConversationBufferMemory(
32
+ memory_key="chat_history",
33
+ return_messages=True,
34
+ output_key='answer'
35
+ )
36
+
37
+ # Create prompt template
38
+ qa_prompt = PromptTemplate.from_template("""You are an expert technical writer specializing in API documentation.
39
+ When describing API endpoints, structure your response in this exact format:
40
 
41
+ 1. Start with the HTTP method and base URI structure
42
+ 2. List all key parameters with:
43
+ - Parameter name in bold (**parameter**)
44
+ - Type and requirement status
45
+ - Clear description
46
+ - Example values where applicable
47
+ 3. Show complete example requests with:
48
+ - Basic example
49
+ - Full example with all parameters
50
+ - Headers included
51
+ 4. Include any relevant response information
52
+
53
+ Use markdown formatting for:
54
+ - Code blocks with syntax highlighting
55
+ - Bold text for important terms
56
+ - Clear section separation
57
 
58
+ Context: {context}
 
 
 
 
 
 
 
 
59
 
60
+ Question: {question}
 
 
 
 
61
 
62
+ Technical answer (following the exact structure above):""")
63
+
64
+ # Create the chain
65
+ qa_chain = ConversationalRetrievalChain.from_llm(
66
+ llm=ChatOpenAI(
67
+ temperature=0.1,
68
+ model_name="gpt-4-turbo-preview"
69
+ ),
70
+ retriever=retriever,
71
+ memory=memory,
72
+ return_source_documents=True,
73
+ combine_docs_chain_kwargs={"prompt": qa_prompt},
74
+ verbose=False
75
+ )
76
+
77
+ return qa_chain
78
 
79
+ def chat(message, history):
80
+ """
81
+ Process chat messages and return responses
82
+ """
83
+ # Get or create QA chain
84
+ if not hasattr(chat, 'qa_chain'):
85
+ chat.qa_chain = create_qa_chain()
86
+
87
+ # Get response
88
+ result = chat.qa_chain({"question": message})
89
+
90
+ # Format sources
91
+ sources = "\n\nSources:\n"
92
+ seen_components = set()
93
+ shown_sources = 0
94
+
95
+ for doc in result["source_documents"]:
96
+ component = doc.metadata.get('component', '')
97
+ title = doc.metadata.get('title', '')
98
+ combo = (component, title)
99
+
100
+ if combo not in seen_components and shown_sources < 3:
101
+ seen_components.add(combo)
102
+ shown_sources += 1
103
+ sources += f"\nSource {shown_sources}:\n"
104
+ sources += f"Title: {title}\n"
105
+ sources += f"Component: {component}\n"
106
+ sources += f"Content: {doc.page_content[:300]}...\n"
107
+
108
+ # Combine response with sources
109
+ full_response = result["answer"] + sources
110
+
111
+ return full_response
112
 
113
+ # Create and launch the Gradio interface
 
 
114
  demo = gr.ChatInterface(
115
+ chat,
116
+ title="Apple Music API Documentation Assistant",
117
+ description="Ask questions about the Apple Music API documentation.",
118
+ examples=[
119
+ "How to search for songs on Apple Music API?",
120
+ "What are the required parameters for searching songs?",
121
+ "Show me an example request with all parameters"
 
 
 
 
 
122
  ],
123
+ retry_btn=None,
124
+ undo_btn=None,
125
+ clear_btn="Clear Chat"
126
  )
127
 
 
128
  if __name__ == "__main__":
129
  demo.launch()
requirements.txt CHANGED
@@ -1 +1,7 @@
1
- huggingface_hub==0.25.2
 
 
 
 
 
 
 
1
+ huggingface_hub==0.25.2
2
+ gradio
3
+ langchain
4
+ langchain-openai
5
+ langchain-community
6
+ openai
7
+ chromadb