1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| import requests import ollama import json
ollama_client = ollama.Client(host='http://192.168.100.135:11434')
METASO_API_KEY = 'mk-xxx' METASO_BASE_URL = 'https://metaso.cn/api/v1/search'
def retrieve_documents(query): try: headers = { 'Authorization': f'Bearer {METASO_API_KEY}', 'Accept': 'application/json', 'Content-Type': 'application/json' } payload = { "q": query, "scope": "webpage" } response = requests.post(METASO_BASE_URL, json=payload, headers=headers) response.raise_for_status() data = response.json() documents = [] if 'webpages' in data: for item in data['webpages'][:10]: if 'snippet' in item: documents.append(item['snippet']) elif 'title' in item: documents.append(item['title']) return documents except Exception as e: print(f"Error retrieving documents: {e}") return []
def generate_answer(query, documents): documents = documents[:3] context = "\n\n".join(documents) + "\n\nQuestion: " + query + "\nAnswer:" try: response = ollama_client.generate( model="llama3.1:8b", prompt=context, options={ "temperature": 0.7, "max_tokens": 512, } ) answer = response['response'] return answer except ollama.ResponseError as e: return f"API 调用失败: {e.error}" except Exception as e: return f"发生未知错误: {e}"
def main(): query = "What is the capital of France?" documents = retrieve_documents(query) if documents: answer = generate_answer(query, documents) print("Question:", query) print("Retrieved documents:", len(documents)) print("Answer:", answer) else: print("No documents retrieved.")
if __name__ == "__main__": main()
|