MCPcopy Create free account
hub / github.com/mlco2/codecarbon / call_ollama_api

Function call_ollama_api

examples/ollama_local_api.py:52–81  ·  view source on GitHub ↗
(endpoint, payload)

Source from the content-addressed store, hash-verified

50
51
52def call_ollama_api(endpoint, payload):
53 url = f"{OLLAMA_URL}/{endpoint}"
54 headers = {
55 "Content-Type": "application/json",
56 }
57 answer = []
58
59 response = requests.post(url, json=payload, headers=headers)
60 try:
61 for line in response.iter_lines():
62 if line:
63 # print(line)
64 answer.append(line.decode("utf-8"))
65 # print(answer)
66 raw_answer = "".join([json.loads(line).get("response") for line in answer])
67 think_start = raw_answer.find("<think>") + len("<think>")
68 think_end = raw_answer.find("</think>")
69 if think_end == -1:
70 think = ""
71 final_answer = raw_answer
72 else:
73 think = raw_answer[think_start:think_end]
74 final_answer = raw_answer[think_end + len("</think>") :]
75 answer_dict = {"think": think, "answer": final_answer}
76 return answer_dict
77 except Exception as e:
78 print(f"An error occurred: {e}")
79 return {"think": f"An error occurred: {e}", "answer": response.text}
80 finally:
81 response.close()
82
83
84if __name__ == "__main__":

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…