liuxiaocs7 commented on code in PR #49: URL: https://github.com/apache/incubator-hugegraph-ai/pull/49#discussion_r1630671172
########## hugegraph-llm/src/hugegraph_llm/llms/ollama.py: ########## @@ -0,0 +1,102 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + +from typing import Callable, List, Optional, Dict, Any + +import requests +from hugegraph_llm.llms.base import BaseLLM +from retry import retry + + +class OllamaChat(BaseLLM): + """Wrapper around Ollama API Chat large language models.""" + + def __init__( + self, + model_name: str, + base_url: str = "http://127.0.0.1:11434" + ) -> None: + self.model = model_name + self.base_url = base_url + + @retry(tries=3, delay=1) + def generate( + self, + messages: Optional[List[Dict[str, Any]]] = None, + prompt: Optional[str] = None, + ) -> str: + """Generate a response to the query messages/prompt.""" + if messages is None: + assert prompt is not None, "Messages or prompt must be provided." + messages = [{"role": "user", "content": prompt}] + data = {"model": self.model, "messages": messages, "stream": False} + response = requests.post( + f"{self.base_url}/api/chat", + headers={"Content-Type": "application/json"}, + json=data, + timeout=60 + ) + if response.status_code != 200: + raise requests.exceptions.RequestException(f"Error code: {response.status_code}.") + return response.json()["message"]["content"] + + def generate_streaming( + self, + messages: Optional[List[Dict[str, Any]]] = None, + prompt: Optional[str] = None, + on_token_callback: Callable = None, + ) -> str: + """Generate a response to the query messages/prompt in streaming mode.""" + if messages is None: + assert prompt is not None, "Messages or prompt must be provided." + messages = [{"role": "user", "content": prompt}] + try: + data = {"model": self.model, "messages": messages, "stream": True} + response = requests.post( + f"{self.base_url}/api/chat", + headers={"Content-Type": "application/json"}, + json=data, + timeout=60, + stream=True + ) + if response.status_code != 200: + raise Exception(f"Error: {response.status_code}") + for line in response.iter_lines(decode_unicode=True): + import json + chunk = json.loads(line.decode("utf-8")) + if not chunk["done"]: + yield chunk["message"]["content"] + else: + yield "" + except requests.exceptions.RequestException: + import traceback + traceback.print_exc() + yield "" + + def num_tokens_from_string(self, string: str) -> int: + """Get token count from string.""" + # TODO: implement + return len(string) + + def max_allowed_token_length(self) -> int: + """Get max-allowed token length""" + # TODO: list all models and their max tokens from api + return 2049 Review Comment: Use `pass` instead of copying other content? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
